mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-10-06 09:38:12 +08:00
Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes
* Implement StaticType for Item<T>
* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input
* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate
* Document the Item kernel implementation and staging plan
* Route Item<Vector> through TaggedValue::TypeDefault
* Add executor integration tests covering the Item and List wire variants
* Collapse element-wise Item/List wire pairs to the List form for conversion insertion
* Migrate sixteen vector modifier nodes to Item element-wise kernels
* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels
* Fix bevel_with_transform test to actually exercise the transform attribute
* Implement From<T> for Item<T>
* Register PromoteNode rank adapters wrapping bare values into Item wires
* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor
* Define a real promote node backing the PromoteNode registry identifiers
* Zip ranked Item connectors by frame slot in the mapped element-wise variant
* Register ItemToListNode singleton raise adapters
* Resolve Item wires against List connectors by inserting promotion adapters at construction
* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end
* Implement Clampable for Item and List wires with per-variant clamp bounds
* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire
* Implement ApplyTransform for Item
* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0
* Detect element-wise nodes by lazy primary connectors declaring Output = Item
* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone
* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2
* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters
* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes
* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro
* Amend the audit with the DashPattern value type resolution
* Migrate the string family to Item element-wise kernels
* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters
* Shadow owned node parameters in bodies instead of mut in signatures
* Migrate the math family and string measure nodes to Item element-wise kernels
* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows
* Flat-map expander kernels returning List under the mapped variant's frame
* Migrate the expander nodes to Item kernels flat-mapping under the frame
* Remove the unused peel_list helper
* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in
Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).
Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.
* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk
* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites
* Flip the vector shape generators to emit rank-0 Item<Vector>
The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.
Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.
* Parse ranked Item<T> parameter defaults against the bare element type
A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.
* Parse an element-wise primary's scalar default against the bare element type
An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.
* Add the DashPattern value type for stroke dash sequences
Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.
* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector
Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.
Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.
Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.
* Register rank adapters for the ranked Stroke enum parameters
The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.
* Display Item wires in the Data panel without a List's ID column
Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.
* Register MonitorNode for Item wire types so the Data panel introspects them directly
Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.
* Color and double Item/List wires and cleave layer-stack connectors in the node graph
* Route wire color and rank through hidden nodes and refresh them on type changes
* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node
* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires
* Back DashPattern with a List<f64> so the Data panel can introspect its lengths
* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>
* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions
* Rank the remaining bare and unnecessarily-List connectors across the node catalog
* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values
* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill
* Restore generator frame-from-params ranking to the roadmap as a planned stage
* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract
* Unload only the wires whose displayed style changed when types update
* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized
* Restore the whole-List Transform variant so rank-1 content wires resolve again
* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes
* Give every ranked connector a field adapter and add numeric cast variants for legacy wires
* Key a ranked param's type default off its Item wire form when no literal default exists
* Inherit the layer's content value when splicing a node into an empty chain
* Migrate stale List-form TypeDefault inputs to the definition's current default
* Generate the mapped wire variant only when the element-wise node has a frame source
* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps
* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot
* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers
* Convert the measure family to element-wise Item kernels per the audit classification
* Prefer the bare element value over the Item type default so ranked params keep their widgets
* Rename GradientStopsUI to GradientUI
* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix
* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2
* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes
* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions
* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius
* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness
* Rank the value, color, and text generator params to Item
* Rank the raster, web-request, and context-reader generator params to Item
* Fix the repeat and brush test wirings left behind by the param-ranking sweeps
* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes
* Delete the Attach Attribute node, folding its role into Write Attribute
* Add the Filter and Sort list companion nodes
* Guard the removed-definition migration swap target with a test
* Add the Box Corners value type in place of the rectangle corner radius list
* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node
* Rank the Combine Channels node's channel connectors to Item
* Make Map Points an element-wise node
* Delete the deprecated Upload Texture node
* Update the implementation roadmap to reflect the landed stages
* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path
* Prefer the rank-0 default when disconnecting a rank-capable input
* Make Path Modify an element-wise node
* Wrap node paths in a NodeIdPath newtype so they flow as a single Item
* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves
* Stop the Brush node from setting layer attributes its paint operation doesn't produce
* Present-gate Flatten Path's adopted layer path like its fill and stroke
* Gate carried layer attributes on static column presence, not runtime values
* Give the remaining graphic Item<T> types a default so unconnected primaries resolve
* Dispatch a ranked param's Properties widget from its rank-0 element type
* Make Extract Transform an element-wise node, restoring the Origins to Polyline body
* Rename Flatten Path to Combine Paths
* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath
* Drop the dead List<u8> and List<NodeId> wire rows
* Rank Flatten Graphic's Fully Flatten toggle to Item
* Update the implementation roadmap with the endgame scope
* Make Combine Paths a reducer that collapses the whole frame into one path
* Stop type-converter nodes from carrying the source's unrelated attributes
* Format the Origins to Polyline regression test
* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value
* Make Switch a framed element-wise select, bundling whole collections
* Widen and align element-type coverage across the list and graphic nodes
* Register the compiler's cache chain pair for every ranked enum and newtype wire
* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires
* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion
* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg
* Delete the vestigial Clone debug node
* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters
* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR
* Deduplicate the promotion adapter registrations into the field adapter macro
* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge
* Vertical wire styling
* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>
* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row
* Rank Path Modify's modification parameter to Item<Box<VectorModification>>
* Rename the field adapter node family to input adapter
* Drop the dead bare scalar rows from Context Modification's implementations list
* Move the dynamic executor's test module into its own file
* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode
* Materialize stored TaggedValues as ranked Item wires at the source
* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization
* Plant the input adapter for List-only inputs, composing position conversion from standard rows
* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers
* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect
* Enforce ranked node inputs in the macro, rejecting bare wire declarations
* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel
* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration
* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced
* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs
* Rewrite the element-wise accessor wire type at the primary input, not raw index 0
* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row
* Gate the remaining Raster<GPU> registry rows behind the gpu feature
* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter
* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index
* Store paint picks as plain color/gradient values, removing the FillChoice value type
* Code review restructuring
* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node
* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR
* Parse Fill and Stroke color defaults through the paint wire's Graphic element
* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing
* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration
* Migrate the legacy 4-input Fill directly to the split has-transform shape
* Upgrade the demo artwork
* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues
* Remove the rank polymorphism working documents
* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation
* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types
* Derive PartialEq for Item now that attributes participate in equality
* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types
* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
[package]
|
||||
name = "graphene-std"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Graphene standard library"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["wgpu"]
|
||||
gpu = []
|
||||
wgpu = ["gpu", "graph-craft/wgpu", "graphene-application-io/wgpu", "graphene-canvas-utils?/wgpu"]
|
||||
wasm = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"graphene-application-io/wasm",
|
||||
"image/png",
|
||||
"core-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"graphic-types/wasm",
|
||||
"text-nodes/wasm",
|
||||
"raster-nodes/wasm",
|
||||
"vector-nodes/wasm",
|
||||
"graphene-core/wasm",
|
||||
"graph-craft/wasm",
|
||||
"dep:graphene-canvas-utils"
|
||||
]
|
||||
image-compare = []
|
||||
vello = ["gpu"]
|
||||
resvg = []
|
||||
shader-nodes = ["raster-nodes/shader-nodes"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
blending-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
transform-nodes = { workspace = true }
|
||||
vector-nodes = { workspace = true }
|
||||
path-bool-nodes = { workspace = true }
|
||||
math-nodes = { workspace = true }
|
||||
rendering = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
raster-nodes = { workspace = true }
|
||||
brush-nodes = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
graphic-nodes = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
log = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
image = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
|
||||
# Optional local dependencies
|
||||
graphene-canvas-utils = { workspace = true, optional = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
wasm-bindgen-futures = { workspace = true, optional = true }
|
||||
tokio = { workspace = true, optional = true }
|
||||
vello = { workspace = true }
|
||||
vello_encoding = { workspace = true }
|
||||
web-sys = { workspace = true, optional = true, features = [
|
||||
"Window",
|
||||
"CanvasRenderingContext2d",
|
||||
"ImageData",
|
||||
"Document",
|
||||
"Navigator",
|
||||
"Gpu",
|
||||
"HtmlCanvasElement",
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,119 @@
|
||||
pub mod platform_application_io;
|
||||
pub mod render_background;
|
||||
pub mod render_cache;
|
||||
pub mod render_node;
|
||||
pub mod render_pixel_preview;
|
||||
pub mod runtime;
|
||||
pub mod text;
|
||||
pub use blending_nodes;
|
||||
pub use brush_nodes as brush;
|
||||
pub use core_types::*;
|
||||
pub use graphene_application_io as application_io;
|
||||
pub use graphene_core;
|
||||
pub use graphene_core::debug;
|
||||
pub use graphic_nodes;
|
||||
pub use graphic_types::{Artboard, Graphic, Vector};
|
||||
pub use math_nodes;
|
||||
pub use path_bool_nodes;
|
||||
pub use raster_nodes;
|
||||
pub use repeat_nodes;
|
||||
pub use text_nodes;
|
||||
pub use transform_nodes;
|
||||
pub use vector_nodes;
|
||||
pub use vector_types;
|
||||
|
||||
/// Backward compatibility re-exports
|
||||
pub mod vector {
|
||||
pub use graphic_types::Vector;
|
||||
pub use vector_types::vector::{VectorModification, VectorModificationType, misc, style};
|
||||
pub use vector_types::*;
|
||||
|
||||
// Re-export commonly used types and submodules
|
||||
pub use vector_types::vector::algorithms;
|
||||
pub use vector_types::vector::click_target;
|
||||
pub use vector_types::vector::misc::HandleId;
|
||||
pub use vector_types::vector::{PointId, RegionId, SegmentId, StrokeId};
|
||||
pub use vector_types::vector::{deserialize_hashmap, serialize_hashmap, serialize_hashmap_as_sorted_object};
|
||||
|
||||
// Re-export HandleExt trait and NoHashBuilder
|
||||
pub use vector_types::vector::HandleExt;
|
||||
pub use vector_types::vector::NoHashBuilder;
|
||||
|
||||
// Re-export vector node modules and functions
|
||||
pub use vector_nodes::*;
|
||||
}
|
||||
|
||||
pub mod graphic {
|
||||
pub use graphic_nodes::graphic::*;
|
||||
pub use graphic_types::graphic::*;
|
||||
}
|
||||
|
||||
pub mod artboard {
|
||||
pub use graphic_nodes::artboard::*;
|
||||
pub use graphic_types::artboard::*;
|
||||
}
|
||||
|
||||
pub mod subpath {
|
||||
pub use vector_types::subpath::*;
|
||||
}
|
||||
|
||||
pub mod gradient {
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
pub use core_types::transform::*;
|
||||
pub use vector_types::ReferencePoint;
|
||||
}
|
||||
|
||||
pub mod repeat {
|
||||
pub use repeat_nodes::repeat_nodes::*;
|
||||
}
|
||||
|
||||
pub mod math {
|
||||
pub use core_types::math::quad;
|
||||
|
||||
pub mod math_ext {
|
||||
pub use vector_types::{QuadExt, RectExt};
|
||||
}
|
||||
}
|
||||
|
||||
pub mod context {
|
||||
pub use graphene_core::context::*;
|
||||
}
|
||||
|
||||
// Re-export graphene_core modules for backward compatibility
|
||||
pub mod ops {
|
||||
pub use core_types::ops::*;
|
||||
pub use graphene_core::ops::*;
|
||||
}
|
||||
|
||||
pub mod extract_xy {
|
||||
pub use graphene_core::extract_xy::*;
|
||||
}
|
||||
|
||||
pub mod animation {
|
||||
pub use graphene_core::animation::*;
|
||||
}
|
||||
|
||||
/// stop gap solutions until all paths have been replaced with their absolute ones
|
||||
pub mod renderer {
|
||||
pub use core_types::math::quad::Quad;
|
||||
pub use core_types::math::rect::Rect;
|
||||
pub use rendering::*;
|
||||
}
|
||||
|
||||
pub mod raster {
|
||||
pub use graphic_types::raster_types::*;
|
||||
pub use raster_nodes::adjustments::*;
|
||||
pub use raster_nodes::*;
|
||||
}
|
||||
|
||||
pub mod raster_types {
|
||||
pub use graphic_types::raster_types::*;
|
||||
}
|
||||
|
||||
pub mod memo {
|
||||
pub use core_types::memo::*;
|
||||
pub use graphene_core::memo::*;
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
#[cfg(target_family = "wasm")]
|
||||
use base64::Engine;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use canvas_utils::{Canvas, CanvasHandle};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::attribute::{Attr, OwnedAttr, Transform};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::Item;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::list::List;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::runtime::SourceFuture;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::{Color, Ctx};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
pub use graph_craft::document::value::RenderOutputType;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use graphene_canvas_utils as canvas_utils;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::Graphic;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::IntoGraphicList;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::Vector;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::markers::EditorMergedLayers;
|
||||
use graphic_types::raster_types::Image;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
|
||||
fn parse_headers(headers: &str) -> reqwest::header::HeaderMap {
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
|
||||
let mut header_map = HeaderMap::new();
|
||||
for line in headers.lines() {
|
||||
if let Some((key, value)) = line.split_once(':') {
|
||||
let Ok(header_name) = HeaderName::from_bytes(key.trim().as_bytes()) else { continue };
|
||||
let Ok(header_value) = HeaderValue::from_str(value.trim()) else { continue };
|
||||
header_map.insert(header_name, header_value);
|
||||
}
|
||||
}
|
||||
header_map
|
||||
}
|
||||
|
||||
/// Sends an HTTP GET request to a specified URL and optionally waits for the response (unless discarded) which is output as a string.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn get_request(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The web address to send the GET request to.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
|
||||
discard_result: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
|
||||
) -> Item<String> {
|
||||
let (url, headers) = (url.into_element(), headers.into_element());
|
||||
let discard_result = *discard_result.element();
|
||||
|
||||
let header_map = parse_headers(&headers);
|
||||
let request = reqwest::Client::new().get(url).headers(header_map);
|
||||
|
||||
if discard_result {
|
||||
#[cfg(target_family = "wasm")]
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
#[cfg(all(not(target_family = "wasm"), feature = "tokio"))]
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return Item::default();
|
||||
};
|
||||
Item::new_from_element(response.text().await.ok().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Sends an HTTP POST request to a specified URL with the provided binary data and optionally waits for the response (unless discarded) which is output as a string.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn post_request(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The web address to send the POST request to.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
/// The binary data to include in the body of the POST request.
|
||||
body: Item<Resource>,
|
||||
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
|
||||
discard_result: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
|
||||
) -> Item<String> {
|
||||
let (url, headers) = (url.into_element(), headers.into_element());
|
||||
let discard_result = *discard_result.element();
|
||||
|
||||
let mut header_map = parse_headers(&headers);
|
||||
header_map.insert("Content-Type", "application/octet-stream".parse().unwrap());
|
||||
let body_bytes: Vec<u8> = body.element().as_ref().to_vec();
|
||||
let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map);
|
||||
|
||||
if discard_result {
|
||||
#[cfg(target_family = "wasm")]
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
#[cfg(all(not(target_family = "wasm"), feature = "tokio"))]
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return Item::default();
|
||||
};
|
||||
Item::new_from_element(response.text().await.ok().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Converts a text string to raw binary data. Useful for transmission over HTTP or writing to files.
|
||||
#[node_macro::node(category("Web Request"), name("String to Bytes"))]
|
||||
fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
|
||||
Item::new_from_element(Resource::new(string.into_element().into_bytes()))
|
||||
}
|
||||
|
||||
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
|
||||
#[node_macro::node(category("Web Request"), name("Image to Bytes"))]
|
||||
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
|
||||
let bytes: Vec<u8> = image
|
||||
.element()
|
||||
.data
|
||||
.iter()
|
||||
.flat_map(|color| {
|
||||
let SRGBA8 { red, green, blue, alpha } = (*color).into();
|
||||
[red, green, blue, alpha]
|
||||
})
|
||||
.collect();
|
||||
|
||||
Item::new_from_element(Resource::new(bytes))
|
||||
}
|
||||
|
||||
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: Item<String>) -> Item<Resource> {
|
||||
let url = url.into_element();
|
||||
let placeholder = || -> Item<Resource> { Item::new_from_element(Resource::empty()) };
|
||||
|
||||
let response = match reqwest::Client::new().get(&url).send().await {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
log::error!("HTTP request for `{url}` failed: {error}");
|
||||
return placeholder();
|
||||
}
|
||||
};
|
||||
|
||||
match response.bytes().await {
|
||||
Ok(bytes) => Item::new_from_element(Resource::new(bytes)),
|
||||
Err(error) => {
|
||||
log::error!("Failed to read HTTP response for `{url}`: {error}");
|
||||
placeholder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts raw binary data to a raster image.
|
||||
///
|
||||
/// Works with standard image format (PNG, JPEG, WebP, etc.). Automatically converts the color space to linear sRGB for accurate compositing.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
fn decode_image(_: impl Ctx, data: Item<Resource>) -> Item<Raster<CPU>> {
|
||||
let data = data.into_element();
|
||||
let Some(image) = image::load_from_memory(data.as_ref()).ok() else {
|
||||
return Item::default();
|
||||
};
|
||||
let image = image.to_rgba32f();
|
||||
let image = Image {
|
||||
data: image
|
||||
.chunks(4)
|
||||
.map(|pixel| {
|
||||
// Decoded bytes are unassociated gamma sRGB; premultiply in gamma then lift to linear
|
||||
let a = pixel[3];
|
||||
Color::from_gamma_srgb_channels(pixel[0] * a, pixel[1] * a, pixel[2] * a, a)
|
||||
})
|
||||
.collect(),
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Item::new_from_element(Raster::new_cpu(image))
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
fn create_canvas(_: impl Ctx) -> Item<CanvasHandle> {
|
||||
Item::new_from_element(CanvasHandle::new())
|
||||
}
|
||||
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn rasterize<T: WasmNotSend + Clone>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
)]
|
||||
data: List<T>,
|
||||
footprint: Item<Footprint>,
|
||||
canvas: Item<CanvasHandle>,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
|
||||
where
|
||||
List<T>: Render + Clone + graphic_types::IntoGraphicList,
|
||||
{
|
||||
let mut data = data;
|
||||
let mut canvas = canvas.into_element();
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
let footprint = footprint.into_element();
|
||||
|
||||
if footprint.transform.matrix2.determinant() == 0. {
|
||||
log::trace!("Invalid footprint received for rasterization");
|
||||
// A zero-size raster renders as nothing, matching the legacy empty list
|
||||
return (Raster::new_cpu(Image::default()), Attr(DAffine2::IDENTITY), OwnedAttr::new(None));
|
||||
}
|
||||
|
||||
// Snapshot the input as a List<Graphic> so the renderer can recurse into the original child layers
|
||||
// when collecting metadata, exposing their click targets to editor tools (same mechanism as Boolean Operation).
|
||||
// The copy is owned before the first await: the input's arena content dies with the spawning evaluation.
|
||||
let upstream_graphic_list = data.clone().into_graphic_list();
|
||||
let merged_layers = OwnedAttr::new(Some(&upstream_graphic_list));
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox();
|
||||
let size = aabb.size();
|
||||
let resolution = footprint.resolution;
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for transform in data.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*transform = DAffine2::from_translation(-aabb.start) * *transform;
|
||||
}
|
||||
data.render_svg(&mut render, &render_params);
|
||||
render.format_svg(DVec2::ZERO, size);
|
||||
let svg_string = render.svg.to_svg_string();
|
||||
|
||||
canvas.set_resolution(resolution);
|
||||
let context = canvas.context();
|
||||
|
||||
let preamble = "data:image/svg+xml;base64,";
|
||||
let mut base64_string = String::with_capacity(preamble.len() + svg_string.len() * 4);
|
||||
base64_string.push_str(preamble);
|
||||
base64::engine::general_purpose::STANDARD.encode_string(svg_string, &mut base64_string);
|
||||
|
||||
let image_data = web_sys::HtmlImageElement::new().unwrap();
|
||||
image_data.set_src(base64_string.as_str());
|
||||
wasm_bindgen_futures::JsFuture::from(image_data.decode()).await.unwrap();
|
||||
context
|
||||
.draw_image_with_html_image_element_and_dw_and_dh(&image_data, 0., 0., resolution.x as f64, resolution.y as f64)
|
||||
.unwrap();
|
||||
|
||||
let rasterized = context.get_image_data(0, 0, resolution.x as i32, resolution.y as i32).unwrap();
|
||||
|
||||
let image = Image::from_image_data(&rasterized.data().0, resolution.x as u32, resolution.y as u32);
|
||||
(Raster::new_cpu(image), Attr(footprint.transform), merged_layers)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Arc<PlatformEditorApi>> {
|
||||
editor_api
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn resource<'a: 'n>(
|
||||
_: impl Ctx,
|
||||
/// The scope-provided editor API giving access to the platform's resource storage.
|
||||
#[scope(editor_api::IDENTIFIER)]
|
||||
editor_api: Item<&'a PlatformEditorApi>,
|
||||
/// The content hash identifying which stored resource to load.
|
||||
hash: Item<ResourceHash>,
|
||||
) -> Item<Resource> {
|
||||
let hash = hash.into_element();
|
||||
let application_io = editor_api.into_element().application_io.as_ref().expect("ApplicationIo must be available when using resources");
|
||||
let resource = application_io.load_resource(hash).await.unwrap_or_else(|| panic!("Resource {hash} not found"));
|
||||
Item::new_from_element(resource)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
let executor = editor_api
|
||||
.into_element()
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not available")
|
||||
.gpu_executor()
|
||||
.expect("GPU executor not available");
|
||||
Item::new_from_element(executor)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<Option<&'a ::wgpu_executor::WgpuExecutor>> {
|
||||
let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor());
|
||||
Item::new_from_element(executor)
|
||||
}
|
||||
|
||||
/// Uploads image data from CPU memory into a GPU texture so that GPU-based nodes can process it.
|
||||
#[node_macro::node(category("Debug"), memoize)]
|
||||
pub async fn upload_texture<'a: 'n>(_: impl Ctx, content: Item<Raster<CPU>>, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<&'a ::wgpu_executor::WgpuExecutor>) -> Item<Raster<GPU>> {
|
||||
let executor = executor.into_element();
|
||||
let (raster, attributes) = content.into_parts();
|
||||
|
||||
Item::from_parts(raster.convert(Footprint::DEFAULT, executor).await, attributes)
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
use core_types::ExtractVarArgs;
|
||||
use core_types::color::Linear;
|
||||
use core_types::list::Item;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{Ctx, ExtractFootprint};
|
||||
use glam::{Affine2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::fmt::Write;
|
||||
use wgpu::util::DeviceExt;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_background(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: Item<RenderOutput>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
if !render_params.to_canvas() || render_params.viewport_zoom <= 0.0 {
|
||||
return data;
|
||||
}
|
||||
|
||||
let RenderOutput { data: foreground_data, metadata } = data.into_element();
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
let data = match foreground_data {
|
||||
RenderOutputType::Texture(foreground_texture) => {
|
||||
let doc_to_screen = render_params.footprint.transform.as_affine2();
|
||||
let blended = pipeline.into_element().run::<CompositeBackground>(&CompositeBackgroundArgs {
|
||||
foreground: foreground_texture.as_ref(),
|
||||
backgrounds: &metadata.backgrounds,
|
||||
document_to_screen: doc_to_screen,
|
||||
zoom: render_params.viewport_zoom.to_f32(),
|
||||
});
|
||||
|
||||
RenderOutputType::Texture(blended)
|
||||
}
|
||||
RenderOutputType::Svg {
|
||||
svg: foreground_svg,
|
||||
image_data: foreground_images,
|
||||
} => {
|
||||
let mut render = SvgRender::new();
|
||||
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * render_params.footprint.transform;
|
||||
|
||||
if render_params.viewport_zoom > 0. {
|
||||
let draw_checkerboard = |render: &mut SvgRender, rect: vello::kurbo::Rect, pattern_origin: glam::DVec2, checker_id_prefix: &str| {
|
||||
let checker_id = format!("{checker_id_prefix}-{}", generate_uuid());
|
||||
let cell_size = 8. / render_params.viewport_zoom;
|
||||
let pattern_size = cell_size * 2.;
|
||||
|
||||
write!(
|
||||
&mut render.svg_defs,
|
||||
r##"<pattern id="{checker_id}" x="{}" y="{}" width="{pattern_size}" height="{pattern_size}" patternUnits="userSpaceOnUse"><rect width="{pattern_size}" height="{pattern_size}" fill="#ffffff" /><rect x="{cell_size}" y="0" width="{cell_size}" height="{cell_size}" fill="#cccccc" /><rect x="0" y="{cell_size}" width="{cell_size}" height="{cell_size}" fill="#cccccc" /></pattern>"##,
|
||||
pattern_origin.x,
|
||||
pattern_origin.y,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
render.leaf_tag("rect", |attributes| {
|
||||
attributes.push("x", rect.x0.to_string());
|
||||
attributes.push("y", rect.y0.to_string());
|
||||
attributes.push("width", rect.width().to_string());
|
||||
attributes.push("height", rect.height().to_string());
|
||||
attributes.push("fill", format!("url(#{checker_id})"));
|
||||
});
|
||||
};
|
||||
|
||||
if metadata.backgrounds.is_empty() {
|
||||
if render_params.scale > 0. {
|
||||
let logical_resolution = render_params.footprint.resolution.as_dvec2() / render_params.scale;
|
||||
let logical_footprint = Footprint {
|
||||
transform: logical_transform,
|
||||
resolution: logical_resolution.round().as_uvec2().max(glam::UVec2::ONE),
|
||||
..render_params.footprint
|
||||
};
|
||||
let bounds = logical_footprint.viewport_bounds_in_local_space();
|
||||
let min = bounds.start.floor();
|
||||
let max = bounds.end.ceil();
|
||||
|
||||
if min.is_finite() && max.is_finite() {
|
||||
let rect = vello::kurbo::Rect::new(min.x, min.y, max.x, max.y);
|
||||
draw_checkerboard(&mut render, rect, glam::DVec2::ZERO, "checkered-viewport");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for background in &metadata.backgrounds {
|
||||
let [a, b] = [background.location, background.location + background.dimensions];
|
||||
let rect = vello::kurbo::Rect::new(a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y));
|
||||
draw_checkerboard(&mut render, rect, glam::DVec2::new(rect.x0, rect.y0), "checkered-artboard");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let logical_resolution = render_params.footprint.resolution.as_dvec2() / render_params.scale;
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let background = SvgRenderOutput::from(render);
|
||||
assert!(background.svg_defs.is_empty());
|
||||
|
||||
let svg = format!("{}{}", background.svg, foreground_svg);
|
||||
let image_data = foreground_images;
|
||||
|
||||
RenderOutputType::Svg { svg, image_data }
|
||||
}
|
||||
_ => unreachable!("Render background node received unsupported render output type"),
|
||||
};
|
||||
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn composite_background_pipeline(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<CompositeBackground>(pipeline);
|
||||
}
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct CompositeBackground {
|
||||
checker_rect_pipeline: wgpu::RenderPipeline,
|
||||
checker_viewport_pipeline: wgpu::RenderPipeline,
|
||||
fullscreen_pipeline: wgpu::RenderPipeline,
|
||||
checker_bind_group_layout: wgpu::BindGroupLayout,
|
||||
fullscreen_bind_group_layout: wgpu::BindGroupLayout,
|
||||
sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
pub struct CompositeBackgroundArgs<'a> {
|
||||
foreground: &'a wgpu::Texture,
|
||||
backgrounds: &'a [rendering::Background],
|
||||
document_to_screen: Affine2,
|
||||
zoom: f32,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for CompositeBackground {
|
||||
type Args<'a> = CompositeBackgroundArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
fn create(executor: &WgpuExecutor) -> Self {
|
||||
let device = &executor.context().device;
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let checker_rect_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_checker_rect.wgsl"));
|
||||
let checker_viewport_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_checker_viewport.wgsl"));
|
||||
let fullscreen_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_fullscreen.wgsl"));
|
||||
|
||||
let checker_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("background_checker_bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
|
||||
let checker_rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_checker_rect_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&checker_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let checker_viewport_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_checker_viewport_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&checker_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let fullscreen_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("background_fullscreen_bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let fullscreen_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_fullscreen_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&fullscreen_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let checker_rect_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_checker_rect_pipeline"),
|
||||
layout: Some(&checker_rect_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &checker_rect_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &checker_rect_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let checker_viewport_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_checker_viewport_pipeline"),
|
||||
layout: Some(&checker_viewport_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &checker_viewport_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &checker_viewport_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let fullscreen_blend = wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
|
||||
let fullscreen_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_fullscreen_pipeline"),
|
||||
layout: Some(&fullscreen_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &fullscreen_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &fullscreen_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(fullscreen_blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("background_fullscreen_sampler"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Self {
|
||||
checker_rect_pipeline,
|
||||
checker_viewport_pipeline,
|
||||
fullscreen_pipeline,
|
||||
checker_bind_group_layout,
|
||||
fullscreen_bind_group_layout,
|
||||
sampler,
|
||||
}
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let &CompositeBackgroundArgs {
|
||||
foreground,
|
||||
backgrounds,
|
||||
document_to_screen,
|
||||
zoom,
|
||||
} = args;
|
||||
|
||||
let foreground_size = foreground.size();
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height));
|
||||
|
||||
if zoom <= 0. {
|
||||
return output;
|
||||
}
|
||||
|
||||
let device = &executor.context().device;
|
||||
let queue = &executor.context().queue;
|
||||
|
||||
let checker_size_doc = 8. / zoom;
|
||||
let screen_to_document = document_to_screen.inverse();
|
||||
let viewport_size = output.size();
|
||||
let viewport_size = Vec2::new(viewport_size.width as f32, viewport_size.height as f32);
|
||||
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let foreground_view = foreground.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let checker_draws = if backgrounds.is_empty() {
|
||||
vec![(
|
||||
3,
|
||||
self.create_checker_bind_group(device, CompositeUniforms::fullscreen(viewport_size, screen_to_document, checker_size_doc)),
|
||||
)]
|
||||
} else {
|
||||
backgrounds
|
||||
.iter()
|
||||
.filter_map(|background| {
|
||||
let a = background.location.as_vec2();
|
||||
let b = (background.location + background.dimensions).as_vec2();
|
||||
|
||||
let min = a.min(b);
|
||||
let max = a.max(b);
|
||||
|
||||
if max.x <= min.x || max.y <= min.y {
|
||||
return None;
|
||||
}
|
||||
|
||||
let uniforms = CompositeUniforms::rect(min, max, document_to_screen, viewport_size, checker_size_doc);
|
||||
Some((6, self.create_checker_bind_group(device, uniforms)))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let fullscreen_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("background_fullscreen_bind_group"),
|
||||
layout: &self.fullscreen_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&foreground_view),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("background_encoder") });
|
||||
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("background_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &output_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
|
||||
if backgrounds.is_empty() {
|
||||
pass.set_pipeline(&self.checker_viewport_pipeline);
|
||||
for (vertex_count, bind_group) in &checker_draws {
|
||||
pass.set_bind_group(0, bind_group, &[]);
|
||||
pass.draw(0..*vertex_count, 0..1);
|
||||
}
|
||||
} else {
|
||||
pass.set_pipeline(&self.checker_rect_pipeline);
|
||||
for (vertex_count, bind_group) in &checker_draws {
|
||||
pass.set_bind_group(0, bind_group, &[]);
|
||||
pass.draw(0..*vertex_count, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
pass.set_pipeline(&self.fullscreen_pipeline);
|
||||
pass.set_bind_group(0, &fullscreen_bind_group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
impl CompositeBackground {
|
||||
fn create_checker_bind_group(&self, device: &wgpu::Device, uniforms: CompositeUniforms) -> wgpu::BindGroup {
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("background_checker_uniforms"),
|
||||
contents: bytemuck::bytes_of(&uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("background_checker_bind_group"),
|
||||
layout: &self.checker_bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct CompositeUniforms {
|
||||
transform_x: [f32; 2],
|
||||
transform_y: [f32; 2],
|
||||
transform_translation: [f32; 2],
|
||||
rect_min: [f32; 2],
|
||||
rect_max: [f32; 2],
|
||||
viewport_size: [f32; 2],
|
||||
pattern_origin: [f32; 2],
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
}
|
||||
|
||||
impl CompositeUniforms {
|
||||
fn fullscreen(viewport_size: Vec2, screen_to_document: Affine2, checker_size_doc: f32) -> Self {
|
||||
Self::new(screen_to_document, Vec2::ZERO, Vec2::ZERO, viewport_size, Vec2::ZERO, checker_size_doc)
|
||||
}
|
||||
|
||||
fn rect(rect_min: Vec2, rect_max: Vec2, document_to_screen: Affine2, viewport_size: Vec2, checker_size_doc: f32) -> Self {
|
||||
Self::new(document_to_screen, rect_min, rect_max, viewport_size, rect_min, checker_size_doc)
|
||||
}
|
||||
|
||||
fn new(transform: Affine2, rect_min: Vec2, rect_max: Vec2, viewport_size: Vec2, pattern_origin: Vec2, checker_size: f32) -> Self {
|
||||
Self {
|
||||
transform_x: transform.matrix2.x_axis.to_array(),
|
||||
transform_y: transform.matrix2.y_axis.to_array(),
|
||||
transform_translation: transform.translation.to_array(),
|
||||
rect_min: rect_min.to_array(),
|
||||
rect_max: rect_max.to_array(),
|
||||
viewport_size: viewport_size.to_array(),
|
||||
pattern_origin: pattern_origin.to_array(),
|
||||
checker_size,
|
||||
_pad: 0.,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
struct CompositeUniforms {
|
||||
transform_x: vec2<f32>,
|
||||
transform_y: vec2<f32>,
|
||||
transform_translation: vec2<f32>,
|
||||
rect_min: vec2<f32>,
|
||||
rect_max: vec2<f32>,
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: CompositeUniforms;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) document_position: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let document_corners = array<vec2<f32>, 6>(
|
||||
uniforms.rect_min,
|
||||
vec2<f32>(uniforms.rect_max.x, uniforms.rect_min.y),
|
||||
vec2<f32>(uniforms.rect_min.x, uniforms.rect_max.y),
|
||||
vec2<f32>(uniforms.rect_min.x, uniforms.rect_max.y),
|
||||
vec2<f32>(uniforms.rect_max.x, uniforms.rect_min.y),
|
||||
uniforms.rect_max,
|
||||
);
|
||||
let document_position = document_corners[vertex_index];
|
||||
|
||||
let transformed = uniforms.transform_x * document_position.x + uniforms.transform_y * document_position.y + uniforms.transform_translation;
|
||||
let normalized = transformed / uniforms.viewport_size;
|
||||
let clip = vec2<f32>(normalized.x * 2.0 - 1.0, 1.0 - normalized.y * 2.0);
|
||||
|
||||
var out: VertexOutput;
|
||||
out.position = vec4<f32>(clip, 0.0, 1.0);
|
||||
out.document_position = document_position;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
let luminance = select(1.0, 0.8, parity == 1);
|
||||
|
||||
let fw = fwidthFine(in.document_position);
|
||||
let coverage_max = 1.0 - smoothstep(uniforms.rect_max - fw, uniforms.rect_max, in.document_position);
|
||||
let coverage_min = smoothstep(uniforms.rect_min, uniforms.rect_min + fw, in.document_position);
|
||||
let coverage = coverage_max * coverage_min;
|
||||
let alpha = coverage.x * coverage.y;
|
||||
|
||||
return vec4<f32>(vec3<f32>(luminance), alpha);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
struct CompositeUniforms {
|
||||
transform_x: vec2<f32>,
|
||||
transform_y: vec2<f32>,
|
||||
transform_translation: vec2<f32>,
|
||||
rect_min: vec2<f32>,
|
||||
rect_max: vec2<f32>,
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: CompositeUniforms;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) document_position: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let positions = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
);
|
||||
let position = positions[vertex_index];
|
||||
|
||||
let screen_position = vec2<f32>((position.x + 1.0) * 0.5 * uniforms.viewport_size.x, (1.0 - position.y) * 0.5 * uniforms.viewport_size.y);
|
||||
let document_position = uniforms.transform_x * screen_position.x + uniforms.transform_y * screen_position.y + uniforms.transform_translation;
|
||||
|
||||
var out: VertexOutput;
|
||||
out.position = vec4<f32>(position, 0.0, 1.0);
|
||||
out.document_position = document_position;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
let luminance = vec3<f32>(select(1.0, 0.8, parity == 1));
|
||||
return vec4<f32>(luminance, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
@group(0) @binding(0)
|
||||
var foreground_sampler: sampler;
|
||||
|
||||
@group(0) @binding(1)
|
||||
var foreground_texture: texture_2d<f32>;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tex_coord: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let positions = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
);
|
||||
|
||||
let tex_coords = array<vec2<f32>, 3>(
|
||||
vec2<f32>(0.0, 1.0),
|
||||
vec2<f32>(0.0, -1.0),
|
||||
vec2<f32>(2.0, 1.0),
|
||||
);
|
||||
|
||||
var vertex_out: VertexOutput;
|
||||
vertex_out.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
|
||||
vertex_out.tex_coord = tex_coords[vertex_index];
|
||||
return vertex_out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(fragment_in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return textureSample(foreground_texture, foreground_sampler, fragment_in.tex_coord);
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
//! Tile-based render caching for efficient viewport panning.
|
||||
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::AxisAlignedBbox;
|
||||
use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::Texture;
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
const BYTES_PER_PIXEL: usize = 4;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
||||
pub struct TileCoord {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedRegion {
|
||||
pub texture: Texture,
|
||||
pub texture_size: UVec2,
|
||||
pub tiles: Vec<TileCoord>,
|
||||
pub metadata: rendering::RenderMetadata,
|
||||
last_access: u64,
|
||||
memory_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
pub struct CacheKey {
|
||||
pub max_region_area: u32,
|
||||
pub render_mode_hash: u64,
|
||||
pub zoom: u64,
|
||||
pub rotation: u64,
|
||||
pub for_export: bool,
|
||||
pub for_mask: bool,
|
||||
pub thumbnail: bool,
|
||||
pub aligned_strokes: bool,
|
||||
pub override_paint_order: bool,
|
||||
pub animation_time_ms: i64,
|
||||
pub real_time_ms: i64,
|
||||
pub pointer: [u8; 16],
|
||||
}
|
||||
|
||||
impl CacheKey {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn new(
|
||||
max_region_area: u32,
|
||||
render_mode_hash: u64,
|
||||
zoom: f64,
|
||||
rotation: f64,
|
||||
for_export: bool,
|
||||
for_mask: bool,
|
||||
thumbnail: bool,
|
||||
aligned_strokes: bool,
|
||||
override_paint_order: bool,
|
||||
animation_time: f64,
|
||||
real_time: f64,
|
||||
pointer: Option<DVec2>,
|
||||
) -> Self {
|
||||
let pointer_bytes = pointer
|
||||
.map(|p| {
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..8].copy_from_slice(&p.x.to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&p.y.to_le_bytes());
|
||||
bytes
|
||||
})
|
||||
.unwrap_or([0u8; 16]);
|
||||
const ROTATION_QUANTIZATION_DIGITS: i32 = 5;
|
||||
let quantization_amount = 10f64.powi(ROTATION_QUANTIZATION_DIGITS);
|
||||
let quantized_rotation = (rotation * quantization_amount).round() * quantization_amount.recip();
|
||||
Self {
|
||||
max_region_area,
|
||||
render_mode_hash,
|
||||
zoom: zoom.to_bits(),
|
||||
rotation: quantized_rotation.to_bits(),
|
||||
for_export,
|
||||
for_mask,
|
||||
thumbnail,
|
||||
aligned_strokes,
|
||||
override_paint_order,
|
||||
animation_time_ms: (animation_time * 1000.).round() as i64,
|
||||
real_time_ms: (real_time * 1000.).round() as i64,
|
||||
pointer: pointer_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, dyn_any::DynAny, Debug)]
|
||||
pub struct TileCache(Arc<Mutex<TileCacheImpl>>);
|
||||
|
||||
impl TileCache {
|
||||
pub fn query(&self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_area: u32) -> CacheQuery {
|
||||
self.0.lock().unwrap().query(viewport_bounds, cache_key, max_region_area)
|
||||
}
|
||||
|
||||
pub fn store_regions(&self, regions: Vec<CachedRegion>) {
|
||||
self.0.lock().unwrap().store_regions(regions);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct TileCacheImpl {
|
||||
regions: Vec<CachedRegion>,
|
||||
timestamp: u64,
|
||||
total_memory: usize,
|
||||
cache_key: CacheKey,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RenderRegion {
|
||||
pub tiles: Vec<TileCoord>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CacheQuery {
|
||||
pub cached_regions: Vec<CachedRegion>,
|
||||
pub missing_regions: Vec<RenderRegion>,
|
||||
}
|
||||
|
||||
fn bounds_to_tiles(bounds: &AxisAlignedBbox) -> Vec<TileCoord> {
|
||||
let tile_size = TILE_SIZE as f64;
|
||||
let tile_start_x = (bounds.start.x / tile_size).floor() as i32;
|
||||
let tile_start_y = (bounds.start.y / tile_size).floor() as i32;
|
||||
let tile_end_x = (bounds.end.x / tile_size).ceil() as i32;
|
||||
let tile_end_y = (bounds.end.y / tile_size).ceil() as i32;
|
||||
|
||||
let mut tiles = Vec::new();
|
||||
for y in tile_start_y..tile_end_y {
|
||||
for x in tile_start_x..tile_end_x {
|
||||
tiles.push(TileCoord { x, y });
|
||||
}
|
||||
}
|
||||
tiles
|
||||
}
|
||||
|
||||
fn tile_bounds(coord: &TileCoord) -> AxisAlignedBbox {
|
||||
let tile_size = TILE_SIZE as f64;
|
||||
let start = DVec2::new(coord.x as f64, coord.y as f64) * tile_size;
|
||||
AxisAlignedBbox {
|
||||
start,
|
||||
end: start + DVec2::splat(tile_size),
|
||||
}
|
||||
}
|
||||
|
||||
fn tiles_bounds(tiles: &[TileCoord]) -> AxisAlignedBbox {
|
||||
if tiles.is_empty() {
|
||||
return AxisAlignedBbox::ZERO;
|
||||
}
|
||||
let mut result = tile_bounds(&tiles[0]);
|
||||
for tile in &tiles[1..] {
|
||||
result = result.union(&tile_bounds(tile));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl TileCacheImpl {
|
||||
fn query(&mut self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_area: u32) -> CacheQuery {
|
||||
if &self.cache_key != cache_key {
|
||||
self.invalidate_all();
|
||||
self.cache_key = cache_key.clone();
|
||||
}
|
||||
|
||||
let required_tiles = bounds_to_tiles(viewport_bounds);
|
||||
let required_tile_set: HashSet<_> = required_tiles.iter().cloned().collect();
|
||||
let mut cached_regions = Vec::new();
|
||||
let mut covered_tiles = HashSet::new();
|
||||
|
||||
for region in &mut self.regions {
|
||||
let region_tiles: HashSet<_> = region.tiles.iter().cloned().collect();
|
||||
if region_tiles.iter().any(|t| required_tile_set.contains(t)) {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
cached_regions.push(region.clone());
|
||||
covered_tiles.extend(region_tiles);
|
||||
}
|
||||
}
|
||||
|
||||
let missing_tiles: Vec<_> = required_tiles.into_iter().filter(|t| !covered_tiles.contains(t)).collect();
|
||||
let missing_regions = group_into_regions(&missing_tiles, max_region_area);
|
||||
CacheQuery { cached_regions, missing_regions }
|
||||
}
|
||||
|
||||
fn store_regions(&mut self, new_regions: Vec<CachedRegion>) {
|
||||
for mut region in new_regions {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
self.total_memory += region.memory_size;
|
||||
self.regions.push(region);
|
||||
}
|
||||
self.evict_until_under_budget();
|
||||
}
|
||||
|
||||
fn evict_until_under_budget(&mut self) {
|
||||
while self.total_memory > MAX_CACHE_MEMORY_BYTES && !self.regions.is_empty() {
|
||||
if let Some((oldest_idx, _)) = self.regions.iter().enumerate().min_by_key(|(_, r)| r.last_access) {
|
||||
let removed = self.regions.remove(oldest_idx);
|
||||
self.total_memory = self.total_memory.saturating_sub(removed.memory_size);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_all(&mut self) {
|
||||
self.regions.clear();
|
||||
self.total_memory = 0;
|
||||
}
|
||||
}
|
||||
|
||||
fn group_into_regions(tiles: &[TileCoord], max_region_area: u32) -> Vec<RenderRegion> {
|
||||
if tiles.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let tile_set: HashSet<_> = tiles.iter().cloned().collect();
|
||||
let mut visited = HashSet::new();
|
||||
let mut regions = Vec::new();
|
||||
|
||||
for &tile in tiles {
|
||||
if visited.contains(&tile) {
|
||||
continue;
|
||||
}
|
||||
let region_tiles = flood_fill(&tile, &tile_set, &mut visited);
|
||||
let region = RenderRegion { tiles: region_tiles };
|
||||
regions.extend(split_oversized_region(region, max_region_area));
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// Recursively subdivides a region until all sub-regions have area <= max_region_area.
|
||||
/// Uses axis-aligned splits on the longest dimension.
|
||||
fn split_oversized_region(region: RenderRegion, max_region_area: u32) -> Vec<RenderRegion> {
|
||||
let pixel_size = tiles_bounds(®ion.tiles).size();
|
||||
let area = (pixel_size.x * pixel_size.y) as u32;
|
||||
|
||||
// Base case: region is small enough
|
||||
if area <= max_region_area {
|
||||
return vec![region];
|
||||
}
|
||||
|
||||
// Determine split axis: choose the longer dimension
|
||||
let split_horizontally = pixel_size.x > pixel_size.y;
|
||||
|
||||
// Split tiles into two groups based on midpoint
|
||||
let mut group1 = Vec::new();
|
||||
let mut group2 = Vec::new();
|
||||
|
||||
if split_horizontally {
|
||||
let min_x = region.tiles.iter().map(|t| t.x).min().unwrap();
|
||||
let max_x = region.tiles.iter().map(|t| t.x).max().unwrap();
|
||||
let mid_x = min_x + (max_x - min_x) / 2;
|
||||
|
||||
for &tile in ®ion.tiles {
|
||||
if tile.x <= mid_x {
|
||||
group1.push(tile);
|
||||
} else {
|
||||
group2.push(tile);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let min_y = region.tiles.iter().map(|t| t.y).min().unwrap();
|
||||
let max_y = region.tiles.iter().map(|t| t.y).max().unwrap();
|
||||
let mid_y = min_y + (max_y - min_y) / 2;
|
||||
|
||||
for &tile in ®ion.tiles {
|
||||
if tile.y <= mid_y {
|
||||
group1.push(tile);
|
||||
} else {
|
||||
group2.push(tile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if group1.is_empty() || group2.is_empty() {
|
||||
log::error!("Failed to split oversized region.");
|
||||
return vec![region];
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
for tiles in [group1, group2] {
|
||||
if !tiles.is_empty() {
|
||||
let sub_region = RenderRegion { tiles };
|
||||
result.extend(split_oversized_region(sub_region, max_region_area));
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut HashSet<TileCoord>) -> Vec<TileCoord> {
|
||||
let mut result = Vec::new();
|
||||
let mut stack = vec![*start];
|
||||
|
||||
while let Some(current) = stack.pop() {
|
||||
if visited.contains(¤t) || !tile_set.contains(¤t) {
|
||||
continue;
|
||||
}
|
||||
visited.insert(current);
|
||||
result.push(current);
|
||||
|
||||
for neighbor in [
|
||||
TileCoord { x: current.x - 1, y: current.y },
|
||||
TileCoord { x: current.x + 1, y: current.y },
|
||||
TileCoord { x: current.x, y: current.y - 1 },
|
||||
TileCoord { x: current.x, y: current.y + 1 },
|
||||
] {
|
||||
if tile_set.contains(&neighbor) && !visited.contains(&neighbor) {
|
||||
stack.push(neighbor);
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_output_cache(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<std::sync::Arc<PlatformEditorApi>>,
|
||||
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
|
||||
#[data] tile_cache: TileCache,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let footprint = *ctx.footprint();
|
||||
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else {
|
||||
log::warn!("render_output_cache: missing or invalid render params, falling back to direct render");
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
|
||||
// Fall back to direct render for non-Vello or zero-size viewports
|
||||
let physical_resolution = footprint.resolution;
|
||||
if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let zoom = footprint.scale_magnitudes().x;
|
||||
let rotation = footprint.decompose_rotation();
|
||||
|
||||
let device_origin_offset = footprint.transform.translation;
|
||||
let viewport_bounds_device = AxisAlignedBbox {
|
||||
start: -device_origin_offset,
|
||||
end: footprint.resolution.as_dvec2() - device_origin_offset,
|
||||
};
|
||||
|
||||
let max_region_area = editor_api.into_element().editor_preferences.max_render_region_area();
|
||||
|
||||
let cache_key = CacheKey::new(
|
||||
max_region_area,
|
||||
render_params.render_mode as u64,
|
||||
zoom,
|
||||
rotation,
|
||||
render_params.for_export,
|
||||
render_params.for_mask,
|
||||
render_params.thumbnail,
|
||||
render_params.aligned_strokes,
|
||||
render_params.override_paint_order,
|
||||
ctx.try_animation_time().unwrap_or(0.),
|
||||
ctx.try_real_time().unwrap_or(0.),
|
||||
ctx.try_pointer_position(),
|
||||
);
|
||||
|
||||
let cache_query = tile_cache.query(&viewport_bounds_device, &cache_key, max_region_area);
|
||||
|
||||
let mut new_regions = Vec::new();
|
||||
for missing_region in &cache_query.missing_regions {
|
||||
if missing_region.tiles.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let min_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
let max_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
|
||||
|
||||
let tile_count = (max_tile - min_tile) + IVec2::ONE;
|
||||
let region_pixel_size = (tile_count * TILE_SIZE as i32).as_uvec2();
|
||||
|
||||
let tile_global_offset = min_tile.as_dvec2() * TILE_SIZE as f64 + device_origin_offset;
|
||||
let region_transform = DAffine2::from_translation(-tile_global_offset) * footprint.transform;
|
||||
let region_footprint = Footprint {
|
||||
transform: region_transform,
|
||||
resolution: region_pixel_size,
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
|
||||
let mut result = data.eval(&ctx.with_footprint(®ion_footprint))?;
|
||||
|
||||
let RenderOutputType::Texture(texture) = result.data else {
|
||||
unreachable!("render_output_cache: expected texture output from Vello render");
|
||||
};
|
||||
|
||||
result.metadata.apply_transform(region_transform.inverse());
|
||||
|
||||
let memory_size = (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL;
|
||||
|
||||
new_regions.push(CachedRegion {
|
||||
texture,
|
||||
texture_size: region_pixel_size,
|
||||
tiles: missing_region.tiles.clone(),
|
||||
metadata: result.metadata,
|
||||
last_access: 0,
|
||||
memory_size,
|
||||
});
|
||||
}
|
||||
|
||||
tile_cache.store_regions(new_regions.clone());
|
||||
|
||||
let all_regions: Vec<_> = cache_query.cached_regions.into_iter().chain(new_regions).collect();
|
||||
|
||||
// If no regions, fall back to direct render
|
||||
if all_regions.is_empty() {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let executor = executor.into_element().expect("GPU executor not available");
|
||||
let output_texture = executor.request_texture(physical_resolution);
|
||||
|
||||
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, &executor);
|
||||
|
||||
Ok(Item::new_from_element(RenderOutput {
|
||||
data: RenderOutputType::Texture(output_texture),
|
||||
metadata: combined_metadata,
|
||||
}))
|
||||
}
|
||||
|
||||
fn composite_cached_regions(
|
||||
regions: &[CachedRegion],
|
||||
output_texture: &wgpu::Texture,
|
||||
device_origin_offset: &DVec2,
|
||||
viewport_transform: &DAffine2,
|
||||
exec: &wgpu_executor::WgpuExecutor,
|
||||
) -> rendering::RenderMetadata {
|
||||
let device = &exec.context().device;
|
||||
let queue = &exec.context().queue;
|
||||
let output_resolution = UVec2::new(output_texture.width(), output_texture.height());
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("composite") });
|
||||
let mut combined_metadata = rendering::RenderMetadata::default();
|
||||
|
||||
for region in regions {
|
||||
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
|
||||
// Convert global tile position to physical pixel offset in the output texture
|
||||
let offset_pixels = min_tile * TILE_SIZE as i32 + device_origin_offset.round().as_ivec2();
|
||||
|
||||
let (src_x, dst_x, width) = if offset_pixels.x >= 0 {
|
||||
(0, offset_pixels.x as u32, region.texture_size.x.min(output_resolution.x.saturating_sub(offset_pixels.x as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.x) as u32;
|
||||
(skip, 0, region.texture_size.x.saturating_sub(skip).min(output_resolution.x))
|
||||
};
|
||||
|
||||
let (src_y, dst_y, height) = if offset_pixels.y >= 0 {
|
||||
(0, offset_pixels.y as u32, region.texture_size.y.min(output_resolution.y.saturating_sub(offset_pixels.y as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.y) as u32;
|
||||
(skip, 0, region.texture_size.y.saturating_sub(skip).min(output_resolution.y))
|
||||
};
|
||||
|
||||
if width > 0 && height > 0 {
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: region.texture.as_ref(),
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: src_x, y: src_y, z: 0 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: output_texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: dst_x, y: dst_y, z: 0 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut region_metadata = region.metadata.clone();
|
||||
region_metadata.apply_transform(*viewport_transform);
|
||||
combined_metadata.merge(®ion_metadata);
|
||||
}
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
combined_metadata
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractIndex, ExtractVarArgs, InjectIndex, VarArgLink, VarArgSlots, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::sync::Arc;
|
||||
use vector_types::GradientStops;
|
||||
use wgpu_executor::RenderContext;
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub enum RenderIntermediateType {
|
||||
Vello(Arc<(vello::Scene, RenderContext)>),
|
||||
Svg(Arc<SvgRenderOutput>),
|
||||
}
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RenderIntermediate {
|
||||
pub(crate) ty: RenderIntermediateType,
|
||||
pub(crate) metadata: RenderMetadata,
|
||||
}
|
||||
|
||||
fn intermediate_of<R: Render>(data: &R, render_params: &RenderParams) -> RenderIntermediate {
|
||||
let footprint = Footprint::default();
|
||||
let mut metadata = RenderMetadata::default();
|
||||
data.collect_metadata(&mut metadata, footprint, None);
|
||||
let intermediate = match &render_params.render_output_type {
|
||||
RenderOutputTypeRequest::Vello => {
|
||||
let mut scene = vello::Scene::new();
|
||||
|
||||
let mut context = wgpu_executor::RenderContext::default();
|
||||
data.render_to_vello(&mut scene, Default::default(), &mut context, render_params);
|
||||
|
||||
RenderIntermediate {
|
||||
ty: RenderIntermediateType::Vello(Arc::new((scene, context))),
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
RenderOutputTypeRequest::Svg => {
|
||||
let mut render = SvgRender::new();
|
||||
|
||||
data.render_svg(&mut render, render_params);
|
||||
|
||||
RenderIntermediate {
|
||||
ty: RenderIntermediateType::Svg(Arc::new(render.into())),
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Item::new_from_element(intermediate)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_intermediate<T: dyn_any::StaticTypeSized + 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'_>, Output = T>,
|
||||
) -> Result<RenderIntermediate, Interrupt> {
|
||||
let data = data.eval(&ctx.derived())?;
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
Ok(intermediate_of(&data, render_params))
|
||||
}
|
||||
|
||||
/// The leveled form of `render_intermediate`: the input's records materialize
|
||||
/// into a run, which renders directly.
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_intermediate_leveled<T: Clone + Send + Sync + core_types::CacheHash + dyn_any::StaticTypeSized + 'static>(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractIndex + InjectIndex + Copy,
|
||||
#[implementations(Artboard, Graphic, Vector, Raster<CPU>, Color, GradientStops, String)] data: IList<T>,
|
||||
) -> Result<RenderIntermediate, Interrupt>
|
||||
where
|
||||
for<'a> core_types::record::RunView<'a, T>: Render,
|
||||
{
|
||||
let item = data.as_group_item();
|
||||
let run = core_types::record::RunView::<T>::new(&item).expect("the run holds the row's element type");
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
Ok(intermediate_of(&run, render_params))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
data: Item<RenderIntermediate>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
let RenderIntermediate { ty, mut metadata } = data.into_element();
|
||||
metadata.apply_transform(footprint.transform);
|
||||
|
||||
let data = match (render_params.render_output_type, ty) {
|
||||
(RenderOutputTypeRequest::Svg, RenderIntermediateType::Svg(data)) => {
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * footprint.transform;
|
||||
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
|
||||
|
||||
let mut render = SvgRender::from(data.as_ref());
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let output = SvgRenderOutput::from(render);
|
||||
assert!(output.svg_defs.is_empty());
|
||||
|
||||
RenderOutputType::Svg {
|
||||
svg: output.svg,
|
||||
image_data: output.image_data.into_iter().map(|(image, id)| (id, image.0)).collect(),
|
||||
}
|
||||
}
|
||||
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
||||
let (scene, context) = data.as_ref();
|
||||
|
||||
let footprint_transform_vello = vello::kurbo::Affine::new(footprint.transform.to_cols_array());
|
||||
|
||||
let mut transformed_scene = vello::Scene::new();
|
||||
transformed_scene.append(scene, Some(footprint_transform_vello));
|
||||
|
||||
// We now replace all transforms which are supposed to be infinite with a transform which covers the entire viewport.
|
||||
// See <https://xi.zulipchat.com/#narrow/channel/197075-vello/topic/Full.20screen.20color.2Fgradients/near/538435044> for more detail.
|
||||
//
|
||||
// `!is_finite()` rather than `== f32::INFINITY`: `scene.append` composes the child's `Affine::scale(INFINITY)` with
|
||||
// the viewport rotation, leaving `matrix[0] = cos(θ) * INFINITY`. In the (90°, 270°) tilt range cos is negative so
|
||||
// the result is `-INFINITY`, which the old equality check missed; Vello then rasterized a unit rect with non-finite
|
||||
// vertices, dropping the gradient and tanking performance. `!is_finite()` also covers NaN as a guard against future
|
||||
// code paths where `matrix[0]` could land on `0 * INFINITY`.
|
||||
let scaled_infinite_transform = vello::kurbo::Affine::scale_non_uniform(footprint.resolution.x as f64, footprint.resolution.y as f64);
|
||||
for transform in transformed_scene.encoding_mut().transforms.iter_mut() {
|
||||
if !transform.matrix[0].is_finite() {
|
||||
*transform = vello_encoding::Transform::from_kurbo(&scaled_infinite_transform);
|
||||
}
|
||||
}
|
||||
|
||||
let texture = executor
|
||||
.into_element()
|
||||
.expect("GPU executor not available")
|
||||
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
|
||||
.expect("Failed to render Vello scene");
|
||||
RenderOutputType::Texture(texture)
|
||||
}
|
||||
_ => unreachable!("Render node did not receive its requested data type"),
|
||||
};
|
||||
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn create_context(ctx: impl Ctx + ExtractVarArgs + DeriveCtx, data: impl Node<Context<'_>, Output = RenderOutput>) -> Result<RenderOutput, Interrupt> {
|
||||
let render_config = *ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderConfig>()
|
||||
.expect("Downcasting render config yielded invalid type");
|
||||
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
};
|
||||
|
||||
let logical_viewport = render_config.viewport;
|
||||
let footprint = Footprint {
|
||||
transform: glam::DAffine2::from_scale(glam::DVec2::splat(render_config.scale)) * logical_viewport.transform,
|
||||
..logical_viewport
|
||||
};
|
||||
|
||||
let render_params = RenderParams {
|
||||
render_mode: render_config.render_mode,
|
||||
for_export: render_config.for_export,
|
||||
render_output_type,
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: logical_viewport.scale_magnitudes().x,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let scope = ctx
|
||||
.scope()
|
||||
.with_real_time(Some(render_config.time.time))
|
||||
.with_animation_time(Some(render_config.time.animation_time.as_secs_f64()))
|
||||
.with_pointer_position(Some(render_config.pointer));
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_params),
|
||||
outer: None,
|
||||
};
|
||||
let scoped = ctx.with_scope(&scope);
|
||||
let with_params = scoped.with_varargs(&varargs);
|
||||
let mut result = data.eval(&with_params.with_footprint(&footprint))?;
|
||||
|
||||
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, VarArgsResult};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::node::Node;
|
||||
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use graphene_application_io::TimingInformation;
|
||||
|
||||
fn probe(ctx: &ContextImpl) -> GPoll<RenderOutput> {
|
||||
let render_params = ctx.vararg(0).unwrap().downcast_ref::<RenderParams>().expect("the vararg chain must start with RenderParams");
|
||||
assert_eq!(render_params.scale, 2.0);
|
||||
assert!(matches!(ctx.vararg(1), Err(VarArgsResult::IndexOutOfBounds)), "the RenderConfig must not leak downstream");
|
||||
assert_eq!(ctx.footprint().transform, glam::DAffine2::from_scale(glam::DVec2::splat(2.0)) * Footprint::DEFAULT.transform);
|
||||
assert_eq!(ctx.try_real_time(), Some(1.5));
|
||||
assert_eq!(ctx.try_animation_time(), Some(2.0));
|
||||
assert_eq!(ctx.try_pointer_position(), Some(glam::DVec2::new(3.0, 4.0)));
|
||||
GPoll::Final(RenderOutput {
|
||||
data: RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
metadata: RenderMetadata::default(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let render_config = RenderConfig {
|
||||
scale: 2.0,
|
||||
time: TimingInformation {
|
||||
time: 1.5,
|
||||
animation_time: std::time::Duration::from_secs(2),
|
||||
},
|
||||
pointer: glam::DVec2::new(3.0, 4.0),
|
||||
..Default::default()
|
||||
};
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_config),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&varargs);
|
||||
|
||||
let probe = core_types::record::LiftedSource::<RenderOutput, _>::new(probe);
|
||||
let layout = Node::<ContextImpl>::layout(&probe).clone();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes().max(1 << 12));
|
||||
let mut graph = CreateContextNode::new(probe, &layout);
|
||||
// The executor resolves and installs the node's own layout at wiring;
|
||||
// without it the flip tail writes through the default empty layout.
|
||||
Node::<ContextImpl>::set_layout(
|
||||
&mut graph,
|
||||
core_types::record::RecordLayout {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
lane_invariant: u32::MAX,
|
||||
},
|
||||
);
|
||||
let GPoll::Final(result) = core_types::record::serve_input(&graph, &ctx, &frames) else {
|
||||
panic!("create_context must complete synchronously");
|
||||
};
|
||||
let output: &RenderOutput = unsafe { core_types::record::borrow_element(layout.rec(&result)) };
|
||||
assert_eq!(
|
||||
output.data,
|
||||
RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::Item;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use glam::{DAffine2, DVec2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use vector_types::vector::style::RenderMode;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_pixel_preview(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else {
|
||||
log::error!("invalid render params for pixel preview");
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
let physical_scale = render_params.scale;
|
||||
|
||||
let footprint = *ctx.footprint();
|
||||
let viewport_zoom = footprint.scale_magnitudes().x;
|
||||
|
||||
if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let physical_resolution = footprint.resolution;
|
||||
let logical_resolution = physical_resolution.as_dvec2() / physical_scale;
|
||||
|
||||
let logical_footprint = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform,
|
||||
resolution: logical_resolution.as_uvec2().max(UVec2::ONE),
|
||||
..footprint
|
||||
};
|
||||
|
||||
let bounds = logical_footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let upstream_min = bounds.start.floor();
|
||||
let upstream_max = bounds.end.ceil();
|
||||
|
||||
let upstream_size = (upstream_max - upstream_min).max(DVec2::ONE);
|
||||
let upstream_resolution = upstream_size.as_uvec2().max(UVec2::ONE);
|
||||
|
||||
let upstream_footprint = Footprint {
|
||||
transform: DAffine2::from_translation(-upstream_min),
|
||||
resolution: upstream_resolution,
|
||||
quality: footprint.quality,
|
||||
};
|
||||
|
||||
let scoped = ctx.push_vararg(&render_params);
|
||||
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?.into_element();
|
||||
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else {
|
||||
return Ok(Item::new_from_element(result));
|
||||
};
|
||||
|
||||
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
|
||||
let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution);
|
||||
|
||||
let resampled = pipeline.into_element().run::<PixelPreview>(&PixelPreviewArgs {
|
||||
source: source_texture.as_ref(),
|
||||
transform: &transform,
|
||||
size: physical_resolution,
|
||||
});
|
||||
|
||||
result.data = RenderOutputType::Texture(resampled);
|
||||
|
||||
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
|
||||
|
||||
Ok(Item::new_from_element(result))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn pixel_preview_pipeline(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<PixelPreview>(pipeline);
|
||||
}
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct PixelPreview {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
pub struct PixelPreviewArgs<'a> {
|
||||
source: &'a wgpu::Texture,
|
||||
transform: &'a DAffine2,
|
||||
size: UVec2,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for PixelPreview {
|
||||
type Args<'a> = PixelPreviewArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
fn create(executor: &WgpuExecutor) -> Self {
|
||||
let device = &executor.context().device;
|
||||
let shader = device.create_shader_module(wgpu::include_wgsl!("render_pixel_preview.wgsl"));
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("resample_bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("resample_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("resample_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
PixelPreview { pipeline, bind_group_layout }
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let context = &executor.context();
|
||||
let &PixelPreviewArgs { source, transform, size } = args;
|
||||
|
||||
let output = executor.request_texture(size);
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let params_buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("resample_params"),
|
||||
size: 32,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let params_data = [transform.matrix2.x_axis.as_vec2(), transform.matrix2.y_axis.as_vec2(), transform.translation.as_vec2(), Vec2::ZERO];
|
||||
context.queue.write_buffer(¶ms_buffer, 0, bytemuck::cast_slice(¶ms_data));
|
||||
|
||||
let bind_group = context.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("resample_bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&source_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: params_buffer.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("resample_encoder") });
|
||||
|
||||
{
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("resample_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &output_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &bind_group, &[]);
|
||||
render_pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
context.queue.submit([encoder.finish()]);
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// =============
|
||||
// VERTEX SHADER
|
||||
// =============
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
let pos = array(
|
||||
vec2f(-1.0, -1.0),
|
||||
vec2f(3.0, -1.0),
|
||||
vec2f(-1.0, 3.0),
|
||||
);
|
||||
let xy = pos[vertex_index];
|
||||
out.clip_position = vec4f(xy, 0.0, 1.0);
|
||||
let coords = xy / 2. + 0.5;
|
||||
out.tex_coords = vec2f(coords.x, 1. - coords.y);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ===============
|
||||
// FRAGMENT SHADER
|
||||
// ===============
|
||||
|
||||
@group(0) @binding(0)
|
||||
var t_source: texture_2d<f32>;
|
||||
|
||||
struct Params {
|
||||
matrix: mat2x2<f32>,
|
||||
translation: vec2<f32>,
|
||||
_pad: vec2<f32>,
|
||||
};
|
||||
|
||||
// We need to use a uniform buffer for the params because push constants are not supported on web
|
||||
@group(0) @binding(1)
|
||||
var<uniform> params: Params;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let position = params.matrix * in.tex_coords + params.translation;
|
||||
let texel = vec2<i32>(floor(position));
|
||||
let texture_size = vec2<i32>(textureDimensions(t_source));
|
||||
if (texel.x >= 0 && texel.x < texture_size.x && texel.y >= 0 && texel.y < texture_size.y) {
|
||||
return textureLoad(t_source, texel, 0);
|
||||
}
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub use core_types::runtime::*;
|
||||
|
||||
use crate::platform_application_io::editor_api;
|
||||
use core_types::Ctx;
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn runtime(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> RuntimeHandle {
|
||||
editor_api.runtime.clone()
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graphic_types::Vector;
|
||||
pub use text_nodes::*;
|
||||
|
||||
/// Produces a styled text string carrying all typographic attributes.
|
||||
///
|
||||
/// Use the **Text to Vector** node to convert this into vector geometry if desired.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn text(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The text content to be drawn.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")]
|
||||
#[default("Lorem ipsum")]
|
||||
text: Item<String>,
|
||||
/// The loaded font file used to draw the text. The editor resolves the chosen typeface to these bytes via the resource system.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_font")]
|
||||
font: Item<Resource>,
|
||||
/// The font size used to draw the text.
|
||||
#[unit(" px")]
|
||||
#[default(24.)]
|
||||
#[hard(1..)]
|
||||
size: Item<f64>,
|
||||
/// The line height ratio, relative to the font size. Each line is drawn lower than its previous line by the distance of *Size* × *Line Height*.
|
||||
///
|
||||
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
|
||||
#[unit("x")]
|
||||
#[hard(0..)]
|
||||
#[step(0.1)]
|
||||
#[default(1.2)]
|
||||
line_height: Item<f64>,
|
||||
/// Additional spacing, in pixels, added between each character.
|
||||
#[unit(" px")]
|
||||
#[step(0.1)]
|
||||
letter_spacing: Item<f64>,
|
||||
/// The angle of faux italic slant applied to each glyph.
|
||||
#[unit("°")]
|
||||
#[hard(-85..85)]
|
||||
letter_tilt: Item<f64>,
|
||||
/// Enables the maximum width constraint so lines can wrap.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_max_width: Item<bool>,
|
||||
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
max_width: Item<f64>,
|
||||
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_max_height: Item<bool>,
|
||||
/// The maximum height that the text block can occupy. Excess lines are not drawn.
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
max_height: Item<f64>,
|
||||
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_align")]
|
||||
align: Item<TextAlign>,
|
||||
) -> Item<String> {
|
||||
let text = text.into_element();
|
||||
let font = font.into_element();
|
||||
let (size, line_height, letter_spacing, letter_tilt) = (*size.element(), *line_height.element(), *letter_spacing.element(), *letter_tilt.element());
|
||||
let (has_max_width, max_width, has_max_height, max_height) = (*has_max_width.element(), *max_width.element(), *has_max_height.element(), *max_height.element());
|
||||
let align = align.into_element();
|
||||
|
||||
let mut item = Item::new_from_element(text);
|
||||
|
||||
if font != Resource::default() {
|
||||
item.set_attribute(ATTR_FONT, font);
|
||||
}
|
||||
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_FONT_SIZE, size);
|
||||
}
|
||||
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
|
||||
}
|
||||
if letter_spacing != 0. {
|
||||
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
|
||||
}
|
||||
if letter_tilt != 0. {
|
||||
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
item.set_attribute(ATTR_TEXT_ALIGN, align);
|
||||
}
|
||||
|
||||
item
|
||||
}
|
||||
|
||||
/// Converts a styled text string into a vector compound path.
|
||||
#[node_macro::node(category("Text"), name("Text to Vector"))]
|
||||
fn text_to_vector(
|
||||
_: impl Ctx,
|
||||
/// A styled text string produced by the **Text** node (or any other string source).
|
||||
string: Item<String>,
|
||||
) -> Item<Vector> {
|
||||
shape_text_item(&string, false).into_iter().next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Splits a styled text string into a separate vector item for each of its glyphs (letterforms).
|
||||
#[node_macro::node(category("Text"), name("Text to Vector Glyphs"))]
|
||||
fn text_to_vector_glyphs(
|
||||
_: impl Ctx,
|
||||
/// A styled text string produced by the **Text** node (or any other string source).
|
||||
string: Item<String>,
|
||||
) -> List<Vector> {
|
||||
shape_text_item(&string, true)
|
||||
}
|
||||
Reference in New Issue
Block a user