Compare commits

..
Author SHA1 Message Date
Dennis Kobert a93cdf3c17 New node: 'Bake Footprint', with a draggable footprint cage (#5014)
* New node: "Bake Footprint" with a draggable footprint cage

* Add migration

* Address review comments on the footprint cage
2026-12-06 19:07:18 +01:00
Timon 674221fbc3 Add transient nodes that are exempt from versions and migration checks (#5098)
* Add the transient node attribute for nodes that are never saved

* Refuse to save transient nodes

* Leave transient nodes out of the migration checks and the corpus coverage

* Mark the render chain, scope and resource nodes as transient

* Document the transient attribute
2026-12-06 17:23:44 +00:00
Dennis Kobert 1300b4f92a Identify conversion nodes via node macro annotations (#5083)
Flag adapter nodes and register them by identifier
2026-12-06 13:57:52 +00:00
Timon c0778752ab Fix running out of GPU memory from textures allocated outside the shared texture cache (#5070)
* Give the Vello renderer the executor and pool textures with mip levels

* Take split and grown render targets from the texture pool (fixup #4821, #5063)

* Take the premultiplied render target from the texture pool (fixup #4807)

* Premultiply textures drawn as images into texture pool copies (fixup #4807)

* Take effect textures from the texture pool (fixup #4976, #5023)

* Park generator tiles in the texture pool (fixup #5008, #5009, #5010)

* Park image uploads and adjusted copies in the texture pool (fixup #4807, #4855, #4908, #4997, #5037)

* Park adjustment uploads in the texture pool (fixup #4997)

* Take effect row textures and Mandelbrot reference orbits from the texture pool (fixup #5010)

* Review
2026-12-06 13:49:37 +00:00
Timon 27cded81af Utilize executor multi-output capabilities in runtime (#5084)
* Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

* Answer an export on a channel of its own, so the viewport's answers stay in order

* Render a copy's SVG as an export of the copied layers' own network

* Record in the executor which paths' types changed, to be taken with take_type_changes

* Prepare every network in the node graph executor, and send the runtime the thumbnail sources instead of the previews and layers
2026-12-06 13:48:46 +00:00
d5fdb12320 Desktop: Fix rendering getting stuck on stale WGPU surfaces (#4966)
Reconfigure WGPU surface and request redraw on Outdated

Co-authored-by: Carlos Ferrabone <[email protected]>
Co-authored-by: Timon <[email protected]>
2026-12-06 13:42:47 +00:00
Dennis Kobert 436c943196 Hash vector modifications deterministically instead of with a random ID (#5082) 2026-12-05 12:33:12 +01:00
Keavon Chambers 5add0191f4 Make middle-clicking a node toggle its visibility in the node graph, Inspector, and Layers panels (#5080) 2026-12-04 16:22:27 -08:00
Timon c7e9aaa016 Fix value nodes leaking source map rows on every graph compile (#5078)
* Fix value nodes leaking source map rows on every graph compile

* Update the flatten test for value nodes without a document path
2026-12-04 19:22:18 +00:00
Keavon Chambers 9c9b393420 Rename the 'Add Noise' node to 'Speckle' (#5073) 2026-12-04 10:27:02 +00:00
Keavon Chambers 01c5455ecf Fix the 'Clipping Mask' node not clipping endless color, gradient, and generator layers (#5072) 2026-12-04 01:21:12 -08:00
Keavon Chambers 41586d6967 Add the blend modes Linear Burn, Darker Color, Linear Dodge (Add), Lighter Color, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, and Divide (#5067)
Allow layers to use every blend mode
2026-12-03 15:56:34 -08:00
Keavon Chambers 7c37cc504b Fix how Darker Color, Lighter Color, Hard Mix, and Color Dodge blend (#5066) 2026-12-03 14:48:39 -08:00
125 changed files with 5611 additions and 1662 deletions

No files matched your search

Generated
+12 -12
View File
@@ -2746,9 +2746,8 @@ dependencies = [
"fd-lock", "fd-lock",
"futures", "futures",
"glam", "glam",
"graphite-desktop-ui-cef", "graphite-desktop-ui",
"graphite-desktop-wrapper", "graphite-desktop-wrapper",
"graphite-wasm-wrapper",
"interprocess", "interprocess",
"lzma-rust2", "lzma-rust2",
"muda", "muda",
@@ -2779,6 +2778,13 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "graphite-desktop-embedded-resources"
version = "0.0.0"
dependencies = [
"include_dir",
]
[[package]] [[package]]
name = "graphite-desktop-platform-linux" name = "graphite-desktop-platform-linux"
version = "0.0.0" version = "0.0.0"
@@ -2791,7 +2797,7 @@ name = "graphite-desktop-platform-mac"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"graphite-desktop", "graphite-desktop",
"graphite-desktop-ui-cef", "graphite-desktop-ui",
] ]
[[package]] [[package]]
@@ -2803,14 +2809,14 @@ dependencies = [
] ]
[[package]] [[package]]
name = "graphite-desktop-ui-cef" name = "graphite-desktop-ui"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"ash", "ash",
"bytemuck", "bytemuck",
"cef", "cef",
"dirs", "dirs",
"graphite-desktop-ui-cef-embedded-resources", "graphite-desktop-embedded-resources",
"ipc-channel", "ipc-channel",
"libc", "libc",
"mach2", "mach2",
@@ -2830,13 +2836,6 @@ dependencies = [
"winit", "winit",
] ]
[[package]]
name = "graphite-desktop-ui-cef-embedded-resources"
version = "0.0.0"
dependencies = [
"include_dir",
]
[[package]] [[package]]
name = "graphite-desktop-wrapper" name = "graphite-desktop-wrapper"
version = "0.0.0" version = "0.0.0"
@@ -2844,6 +2843,7 @@ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"graph-craft", "graph-craft",
"graphite-editor", "graphite-editor",
"graphite-wasm-wrapper",
"image", "image",
"keyboard-types", "keyboard-types",
"serde", "serde",
+1 -1
View File
@@ -3,7 +3,7 @@ members = [
"desktop", "desktop",
"desktop/wrapper", "desktop/wrapper",
"desktop/ui", "desktop/ui",
"desktop/ui/embedded-resources", "desktop/embedded-resources",
"desktop/bundle", "desktop/bundle",
"desktop/platform/linux", "desktop/platform/linux",
"desktop/platform/mac", "desktop/platform/mac",
+3 -4
View File
@@ -21,14 +21,13 @@ path = "src/main.rs"
[features] [features]
default = ["recommended", "embedded_resources"] default = ["recommended", "embedded_resources"]
recommended = ["accelerated_paint"] recommended = ["accelerated_paint"]
embedded_resources = ["graphite-desktop-ui-cef/embedded_resources"] embedded_resources = ["graphite-desktop-ui/embedded_resources"]
accelerated_paint = ["graphite-desktop-ui-cef/accelerated_paint"] accelerated_paint = ["graphite-desktop-ui/accelerated_paint"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
graphite-desktop-wrapper = { path = "wrapper" } graphite-desktop-wrapper = { path = "wrapper" }
graphite-desktop-ui-cef = { path = "ui" } graphite-desktop-ui = { path = "ui" }
graphite-wasm-wrapper = { path = "../frontend/wrapper", default-features = false, features = ["editor"] }
wgpu = { workspace = true } wgpu = { workspace = true }
winit = { workspace = true, features = [ winit = { workspace = true, features = [
@@ -1,5 +1,5 @@
[package] [package]
name = "graphite-desktop-ui-cef-embedded-resources" name = "graphite-desktop-embedded-resources"
description = "Graphite Desktop Embedded Resources" description = "Graphite Desktop Embedded Resources"
version.workspace = true version.workspace = true
license.workspace = true license.workspace = true
@@ -1,5 +1,5 @@
const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES"; const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES";
const DEFAULT_RESOURCES_DIR: &str = "../../../frontend/dist"; const DEFAULT_RESOURCES_DIR: &str = "../../frontend/dist";
fn main() { fn main() {
let mut embedded_resources: Option<String> = None; let mut embedded_resources: Option<String> = None;
+2 -2
View File
@@ -16,7 +16,7 @@ workspace = true
[features] [features]
main = ["dep:graphite-desktop"] main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui-cef"] helper = ["dep:graphite-desktop-ui"]
[[bin]] [[bin]]
name = "graphite" name = "graphite"
@@ -30,4 +30,4 @@ required-features = ["helper"]
[dependencies] [dependencies]
graphite-desktop = { path = "../..", optional = true } graphite-desktop = { path = "../..", optional = true }
graphite-desktop-ui-cef = { path = "../../ui", optional = true } graphite-desktop-ui = { path = "../../ui", optional = true }
+1 -1
View File
@@ -1,3 +1,3 @@
fn main() -> std::process::ExitCode { fn main() -> std::process::ExitCode {
graphite_desktop_ui_cef::run_helper() graphite_desktop_ui::run_helper()
} }
+18 -11
View File
@@ -20,13 +20,13 @@ use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler}; use crate::event::{AppEvent, AppEventScheduler};
use crate::input::InputState; use crate::input::InputState;
use crate::persist; use crate::persist;
use crate::preferences::{self, Acceleration}; use crate::preferences;
use crate::render::{RenderError, RenderState}; use crate::render::{RenderError, RenderState};
use crate::spawner::TokioSpawner; use crate::spawner::TokioSpawner;
use crate::ui::{InputEvent, Ui, UiBackend, UiCommand}; use crate::ui::{Acceleration, InputEvent, UiCommand, UiConfig, UiInstance};
use crate::window::Window; use crate::window::Window;
use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, FrontendMessage, IngestAction}; use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, IngestAction};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor}; use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor, serialize_frontend_messages};
pub(crate) struct App { pub(crate) struct App {
render_state: Option<RenderState>, render_state: Option<RenderState>,
@@ -43,10 +43,10 @@ pub(crate) struct App {
app_event_scheduler: AppEventScheduler, app_event_scheduler: AppEventScheduler,
desktop_wrapper: DesktopWrapper, desktop_wrapper: DesktopWrapper,
runtime_command_sender: Sender<RuntimeCommand>, runtime_command_sender: Sender<RuntimeCommand>,
ui: Ui, ui: UiInstance,
ui_initialized: Option<Instant>, ui_initialized: Option<Instant>,
ui_frame_received: bool, ui_frame_received: bool,
ui_startup_buffer: Vec<Vec<FrontendMessage>>, ui_startup_buffer: Vec<Vec<u8>>,
preferences: preferences::DesktopPreferences, preferences: preferences::DesktopPreferences,
launch_documents: Option<Vec<PathBuf>>, launch_documents: Option<Vec<PathBuf>>,
exiting: bool, exiting: bool,
@@ -59,7 +59,7 @@ impl App {
} }
pub(crate) fn new( pub(crate) fn new(
ui: Ui, ui: UiInstance,
wgpu_context: WgpuContext, wgpu_context: WgpuContext,
app_event_receiver: Receiver<AppEvent>, app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler, app_event_scheduler: AppEventScheduler,
@@ -181,7 +181,8 @@ impl App {
} }
fn restart_ui(&mut self) { fn restart_ui(&mut self) {
if let Err(error) = self.ui.restart(&self.preferences) { let acceleration = self.preferences.acceleration;
if let Err(error) = self.ui.restart(UiConfig { acceleration }) {
tracing::error!("Failed to restart the UI: {error}"); tracing::error!("Failed to restart the UI: {error}");
self.exit(Some(ExitReason::Shutdown)); self.exit(Some(ExitReason::Shutdown));
return; return;
@@ -247,7 +248,13 @@ impl App {
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) { fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) {
match message { match message {
DesktopFrontendMessage::ToUi(messages) => self.send_or_queue_ui_message(messages), DesktopFrontendMessage::ToWeb(messages) => {
let Some(bytes) = serialize_frontend_messages(messages) else {
tracing::error!("Failed to serialize frontend messages");
return;
};
self.send_or_queue_web_message(bytes);
}
DesktopFrontendMessage::OpenFileDialog { title, options, action } => { DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
let app_event_scheduler = self.app_event_scheduler.clone(); let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || { let _ = thread::spawn(move || {
@@ -458,7 +465,7 @@ impl App {
self.handle_desktop_frontend_messages(responses); self.handle_desktop_frontend_messages(responses);
} }
fn send_or_queue_ui_message(&mut self, message: Vec<FrontendMessage>) { fn send_or_queue_web_message(&mut self, message: Vec<u8>) {
if self.ui_initialized.is_some() { if self.ui_initialized.is_some() {
self.ui.send(UiCommand::Message(message)); self.ui.send(UiCommand::Message(message));
} else { } else {
@@ -468,7 +475,7 @@ impl App {
fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) { fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) {
match event { match event {
AppEvent::UiInitialized => { AppEvent::WebCommunicationInitialized => {
self.ui_initialized = Some(Instant::now()); self.ui_initialized = Some(Instant::now());
self.ui_frame_received = false; self.ui_frame_received = false;
for message in self.ui_startup_buffer.drain(..) { for message in self.ui_startup_buffer.drain(..) {
+19
View File
@@ -9,6 +9,25 @@ pub(crate) fn ensure_dir_exists(path: &PathBuf) {
} }
} }
pub(crate) fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
pub(crate) fn app_data_dir() -> PathBuf { pub(crate) fn app_data_dir() -> PathBuf {
let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME); let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME);
ensure_dir_exists(&path); ensure_dir_exists(&path);
+1 -1
View File
@@ -5,7 +5,7 @@ use crate::wrapper::messages::{DataTransfer, DesktopWrapperMessage};
pub(crate) enum AppEvent { pub(crate) enum AppEvent {
UiUpdate(wgpu::Texture), UiUpdate(wgpu::Texture),
CursorChange(Cursor), CursorChange(Cursor),
UiInitialized, WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage), DesktopWrapperMessage(DesktopWrapperMessage),
ViewportTexture(Option<Texture>), ViewportTexture(Option<Texture>),
ClipboardRead, ClipboardRead,
+29 -9
View File
@@ -3,13 +3,13 @@ use crate::cli::Cli;
use crate::consts::APP_LOCK_FILE_NAME; use crate::consts::APP_LOCK_FILE_NAME;
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt}; use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
use clap::Parser; use clap::Parser;
use preferences::Acceleration;
use std::io::Write; use std::io::Write;
use std::process::ExitCode; use std::process::ExitCode;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use ui::{Ui, UiBackend, UiEvent}; use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
pub(crate) use graphite_desktop_ui as ui;
pub(crate) use graphite_desktop_wrapper as wrapper; pub(crate) use graphite_desktop_wrapper as wrapper;
mod app; mod app;
@@ -24,7 +24,6 @@ mod preferences;
mod render; mod render;
mod socket; mod socket;
mod spawner; mod spawner;
mod ui;
mod window; mod window;
pub(crate) mod consts; pub(crate) mod consts;
@@ -32,9 +31,14 @@ pub(crate) mod consts;
pub fn start() -> ExitCode { pub fn start() -> ExitCode {
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init(); tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
if let Some(code) = ui::setup() { let ui_context = match UiContext::setup() {
return code; UiSetupResult::Ready(context) => context,
} UiSetupResult::Helper(code) => return code,
UiSetupResult::Failed => {
tracing::error!("Failed to set up the UI runtime");
return ExitCode::FAILURE;
}
};
let cli = Cli::parse(); let cli = Cli::parse();
@@ -69,6 +73,8 @@ pub fn start() -> ExitCode {
} }
}; };
dirs::clear_dir(&ui::temp_dir_root());
// Must be called before event loop initialization or native window integrations will break // Must be called before event loop initialization or native window integrations will break
App::init(); App::init();
@@ -92,7 +98,14 @@ pub fn start() -> ExitCode {
println!("UI acceleration is disabled"); println!("UI acceleration is disabled");
} }
let ui = match Ui::start(&prefs, &wgpu_context) { let ui_context = match ui_context.start(UiConfig { acceleration: prefs.acceleration }) {
Ok(context) => context,
Err(error) => {
tracing::error!("Failed to start the UI runtime: {error}");
return ExitCode::FAILURE;
}
};
let ui = match ui_context.instance(&wgpu_context.device, &wgpu_context.queue) {
Ok(ui) => ui, Ok(ui) => ui,
Err(error) => { Err(error) => {
tracing::error!("Failed to start the UI: {error}"); tracing::error!("Failed to start the UI: {error}");
@@ -107,10 +120,17 @@ pub fn start() -> ExitCode {
let spawned = std::thread::Builder::new().name("ui-events".to_string()).spawn(move || { let spawned = std::thread::Builder::new().name("ui-events".to_string()).spawn(move || {
while let Some(event) = ui.recv() { while let Some(event) = ui.recv() {
match event { match event {
UiEvent::Ready => scheduler.schedule(AppEvent::UiInitialized), UiEvent::Ready => scheduler.schedule(AppEvent::WebCommunicationInitialized),
UiEvent::Frame(texture) => scheduler.schedule(AppEvent::UiUpdate(texture)), UiEvent::Frame(texture) => scheduler.schedule(AppEvent::UiUpdate(texture)),
UiEvent::Cursor(cursor) => scheduler.schedule(AppEvent::CursorChange(cursor)), UiEvent::Cursor(cursor) => scheduler.schedule(AppEvent::CursorChange(cursor)),
UiEvent::Message(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)), UiEvent::Message(message) => match wrapper::deserialize_editor_message(&message) {
Some(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
None => tracing::error!("Failed to deserialize web message"),
},
UiEvent::Failure(error) => {
tracing::error!("UI failure: {error}");
scheduler.schedule(AppEvent::UiCrashed);
}
UiEvent::Crashed => scheduler.schedule(AppEvent::UiCrashed), UiEvent::Crashed => scheduler.schedule(AppEvent::UiCrashed),
} }
} }
+1 -5
View File
@@ -1,11 +1,7 @@
use graphite_desktop_wrapper::messages::Preferences; use graphite_desktop_wrapper::messages::Preferences;
use wgpu::PresentMode; use wgpu::PresentMode;
#[derive(Clone, Copy, Debug, PartialEq, Eq)] use crate::ui::Acceleration;
pub(crate) enum Acceleration {
Auto,
Disabled,
}
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub(crate) struct DesktopPreferences { pub(crate) struct DesktopPreferences {
+5 -2
View File
@@ -234,7 +234,11 @@ impl RenderState {
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true), WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
WgpuCurrentSurfaceTexture::Occluded => return Ok(()), WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost), WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated), WgpuCurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.executor.context().device, &self.config);
window.request_redraw();
return Ok(());
}
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout), WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation), WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
}; };
@@ -327,7 +331,6 @@ impl RenderState {
pub(crate) enum RenderError { pub(crate) enum RenderError {
OutdatedUITextureError, OutdatedUITextureError,
SurfaceLost, SurfaceLost,
SurfaceOutdated,
SurfaceTimeout, SurfaceTimeout,
SurfaceValidation, SurfaceValidation,
} }
-32
View File
@@ -1,32 +0,0 @@
use crate::preferences::DesktopPreferences;
use crate::wrapper::WgpuContext;
use crate::wrapper::messages::{DesktopWrapperMessage, FrontendMessage};
mod cef;
pub(crate) use cef::*;
pub(crate) trait UiBackend: Sized {
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError>;
fn send(&self, command: UiCommand);
fn recv(&self) -> Option<UiEvent>;
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError>;
fn shutdown(&self);
}
pub(crate) type UiError = Box<dyn std::error::Error + Send + Sync>;
pub(crate) enum UiCommand {
Input(InputEvent),
Resized { width: u32, height: u32 },
ScaleChanged(f64),
Refresh,
Message(Vec<FrontendMessage>),
}
pub(crate) enum UiEvent {
Ready,
Frame(wgpu::Texture),
Cursor(Cursor),
Message(DesktopWrapperMessage),
Crashed,
}
-120
View File
@@ -1,120 +0,0 @@
use super::{UiBackend, UiCommand, UiError, UiEvent};
use crate::preferences::{Acceleration, DesktopPreferences};
use crate::wrapper::WgpuContext;
use crate::wrapper::messages::DesktopWrapperMessage;
use graphite_desktop_ui_cef as cef;
use graphite_wasm_wrapper::native_communication::{decode_editor_command, encode_frontend_messages};
use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Mutex;
pub(crate) use cef::{Cursor, InputEvent, InputEventBuilder, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
#[derive(Clone)]
pub(crate) struct Ui {
instance: cef::UiInstance,
}
static SETUP: Mutex<Option<cef::UiContext<cef::Setup>>> = Mutex::new(None);
pub(crate) fn setup() -> Option<ExitCode> {
match cef::UiContext::setup() {
cef::UiSetupResult::Ready(context) => {
*SETUP.lock().unwrap() = Some(context);
None
}
cef::UiSetupResult::Failed => {
tracing::error!("Failed to set up the UI runtime");
Some(ExitCode::FAILURE)
}
cef::UiSetupResult::Helper(code) => Some(code),
}
}
impl UiBackend for Ui {
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError> {
let setup = SETUP.lock().unwrap().take().ok_or("The UI was started before it was set up")?;
clear_dir(&cef::temp_dir_root());
let context = setup.start(config(preferences))?;
let instance = context.instance(&wgpu_context.device, &wgpu_context.queue)?;
Ok(Self { instance })
}
fn send(&self, command: UiCommand) {
let command = match command {
UiCommand::Input(event) => cef::UiCommand::Input(event),
UiCommand::Resized { width, height } => cef::UiCommand::Resized { width, height },
UiCommand::ScaleChanged(scale) => cef::UiCommand::ScaleChanged(scale),
UiCommand::Refresh => cef::UiCommand::Refresh,
UiCommand::Message(messages) => {
let Some(bytes) = encode_frontend_messages(messages) else {
tracing::error!("Failed to serialize frontend messages");
return;
};
cef::UiCommand::Message(bytes)
}
};
self.instance.send(command);
}
fn recv(&self) -> Option<UiEvent> {
loop {
let event = match self.instance.recv()? {
cef::UiEvent::Ready => UiEvent::Ready,
cef::UiEvent::Frame(texture) => UiEvent::Frame(texture),
cef::UiEvent::Cursor(cursor) => UiEvent::Cursor(cursor),
cef::UiEvent::Message(bytes) => {
let Some(message) = decode_editor_command(&bytes) else {
tracing::error!("Failed to deserialize web message");
continue;
};
UiEvent::Message(DesktopWrapperMessage::FromUi(message.into()))
}
cef::UiEvent::Failure(error) => {
tracing::error!("UI failure: {error}");
UiEvent::Crashed
}
cef::UiEvent::Crashed => UiEvent::Crashed,
};
return Some(event);
}
}
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError> {
Ok(self.instance.restart(config(preferences))?)
}
fn shutdown(&self) {
self.instance.shutdown();
}
}
fn config(preferences: &DesktopPreferences) -> cef::UiConfig {
let acceleration = match preferences.acceleration {
Acceleration::Auto => cef::Acceleration::Auto,
Acceleration::Disabled => cef::Acceleration::Disabled,
};
cef::UiConfig { acceleration }
}
fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
[package] [package]
name = "graphite-desktop-ui-cef" name = "graphite-desktop-ui"
description = "Renders the Graphite editor frontend UI into wgpu textures" description = "Renders the Graphite editor frontend UI into wgpu textures"
version.workspace = true version.workspace = true
license.workspace = true license.workspace = true
@@ -16,12 +16,12 @@ workspace = true
[features] [features]
default = [] default = []
embedded_resources = ["dep:graphite-desktop-ui-cef-embedded-resources"] embedded_resources = ["dep:graphite-desktop-embedded-resources"]
accelerated_paint = ["dep:ash", "dep:bytemuck", "dep:objc2-io-surface", "dep:objc2-metal", "dep:mach2"] accelerated_paint = ["dep:ash", "dep:bytemuck", "dep:objc2-io-surface", "dep:objc2-metal", "dep:mach2"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
graphite-desktop-ui-cef-embedded-resources = { path = "embedded-resources", optional = true } graphite-desktop-embedded-resources = { path = "../embedded-resources", optional = true }
wgpu = { workspace = true } wgpu = { workspace = true }
wgpu-sync = { workspace = true } wgpu-sync = { workspace = true }
+1 -1
View File
@@ -78,7 +78,7 @@ pub(crate) fn load(path: PathBuf) -> Option<Resource> {
WebResources::Embedded => { WebResources::Embedded => {
#[cfg(feature = "embedded_resources")] #[cfg(feature = "embedded_resources")]
{ {
if let Some(resources) = &graphite_desktop_ui_cef_embedded_resources::EMBEDDED_RESOURCES if let Some(resources) = &graphite_desktop_embedded_resources::EMBEDDED_RESOURCES
&& let Some(file) = resources.get_file(&path) && let Some(file) = resources.get_file(&path)
{ {
return Some(Resource { return Some(Resource {
+1
View File
@@ -17,6 +17,7 @@ workspace = true
[dependencies] [dependencies]
# Local dependencies # Local dependencies
graphite-editor = { workspace = true } graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graph-craft = { workspace = true } graph-craft = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
@@ -5,7 +5,7 @@ use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessa
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) { pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message { match message {
DesktopWrapperMessage::FromUi(message) => { DesktopWrapperMessage::FromWeb(message) => {
dispatcher.queue_editor_message(*message); dispatcher.queue_editor_message(*message);
} }
DesktopWrapperMessage::Wake => { DesktopWrapperMessage::Wake => {
+10
View File
@@ -2,6 +2,7 @@ use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage; use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform}; use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder}; use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
use graphite_editor::messages::frontend::FrontendMessage;
use graphite_editor::node_graph_executor::NodeRuntime; use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher; use message_dispatcher::DesktopWrapperMessageDispatcher;
@@ -79,3 +80,12 @@ impl DesktopWrapper {
executor.execute() executor.execute()
} }
} }
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
Some(DesktopWrapperMessage::FromWeb(message.into()))
}
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
}
+1 -1
View File
@@ -60,7 +60,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
} }
if !frontend_messages.is_empty() { if !frontend_messages.is_empty() {
self.respond(DesktopFrontendMessage::ToUi(frontend_messages)); self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
} }
} }
} }
+3 -3
View File
@@ -1,4 +1,4 @@
pub use graphite_editor::messages::prelude::FrontendMessage; use graphite_editor::messages::prelude::FrontendMessage;
use std::path::PathBuf; use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage; pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
@@ -12,7 +12,7 @@ pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMes
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences; pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
pub enum DesktopFrontendMessage { pub enum DesktopFrontendMessage {
ToUi(Vec<FrontendMessage>), ToWeb(Vec<FrontendMessage>),
OpenLaunchDocuments, OpenLaunchDocuments,
OpenFileDialog { OpenFileDialog {
title: String, title: String,
@@ -69,7 +69,7 @@ pub enum DesktopFrontendMessage {
} }
pub enum DesktopWrapperMessage { pub enum DesktopWrapperMessage {
FromUi(Box<EditorMessage>), FromWeb(Box<EditorMessage>),
Wake, Wake,
Input(InputMessage), Input(InputMessage),
Ingest { content: DataTransfer, action: IngestAction }, Ingest { content: DataTransfer, action: IngestAction },
+7 -1
View File
@@ -44,6 +44,8 @@ pub enum ConversionError {
IndexOverflow(usize), IndexOverflow(usize),
#[error("Node ID {0} is used by more than one node in the document")] #[error("Node ID {0} is used by more than one node in the document")]
DuplicateNodeId(u64), DuplicateNodeId(u64),
#[error("The transient node {0} cannot be saved")]
TransientNode(String),
} }
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for /// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
} }
// Nodes the binary doesn't register, such as in tests, are at their first version // Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1); let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
let (version, flags) = registered.unwrap_or((1, Default::default()));
if flags.transient {
return Err(ConversionError::TransientNode(identifier_str));
}
let EncodedDeclaration { id, hash, bytes, proto } = let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?; EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored"); assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
} }
#[test]
fn a_transient_node_is_rejected() {
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
let metadata = NodeMetadata {
display_name: "Transient",
category: "",
icon: None,
fields: Vec::new(),
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags {
transient: true,
..Default::default()
},
version: 1,
output_fields: None,
};
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
let mut network = create_simple_network();
network.nodes.insert(
NodeId(100),
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
},
);
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
}
/// A node input referencing a node in a different network can't be remapped to a valid local runtime /// A node input referencing a node in a different network can't be remapped to a valid local runtime
/// ID, so conversion must reject it rather than emit a dangling reference. /// ID, so conversion must reject it rather than emit a dangling reference.
#[test] #[test]
@@ -3,3 +3,4 @@
use migration_core::rename; use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2); rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
@@ -1,3 +1,3 @@
//! Migrations of the nodes in `graphene_std`. //! Migrations of the nodes in `graphene_std`.
mod renames; mod rasterize_v1;
@@ -0,0 +1,68 @@
use migration_core::{Inputs, MigrationError, NodeInput, migration};
use serde::Serialize;
const EXECUTOR: u32 = 2;
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
#[derive(Serialize)]
enum Reflected {
DocumentNodePath,
}
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
if inputs.len() < EXECUTOR as usize {
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
}
if inputs.len() == EXECUTOR as usize {
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
}
inputs.push_reflection(Reflected::DocumentNodePath);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
fixture.inputs(&migrated, rasterize)
}
#[test]
fn rewrites_history() {
check_commutation(&RasterizeV1, &contract());
check_undo(&RasterizeV1, &contract());
}
#[test]
fn gives_the_node_its_path() {
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
}
#[test]
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
let inputs = vec![literal(1.), literal(2.)];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
}
}
@@ -1,13 +0,0 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
+15 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES))); let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind // Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory); let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?; let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
let problems = api_problems(&baseline_nodes, &current, &migrations); let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() { if !problems.is_empty() {
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
// Moving a module keeps the function and its API, which is what a rename looks like // Moving a module keeps the function and its API, which is what a rename looks like
let moved = current let moved = current
.iter() .iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature); .find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved { problems.push(match moved {
Some(new) => format!( Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`", "`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
}); });
continue; continue;
}; };
if new.transient {
continue;
}
if new.version < version { if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version)); problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
@@ -123,6 +126,7 @@ mod tests {
NodeSource { NodeSource {
identifier: identifier.to_string(), identifier: identifier.to_string(),
version, version,
transient: false,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(), function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"), file: PathBuf::from("lib.rs"),
signature: signature.to_string(), signature: signature.to_string(),
@@ -168,6 +172,15 @@ mod tests {
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]); assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
} }
#[test]
fn a_node_turned_transient_needs_no_migration() {
let transient = NodeSource {
transient: true,
..node("a::b", 1, "(x: f64, y: f64)")
};
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
}
#[test] #[test]
fn a_bump_needs_a_migration_from_the_baseline_version() { fn a_bump_needs_a_migration_from_the_baseline_version() {
let bumped = [node("a::b", 3, "(x: f64)")]; let bumped = [node("a::b", 3, "(x: f64)")];
+1
View File
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))? let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter() .into_iter()
.filter(|node| !node.transient)
.map(|node| (node.identifier, node.version)) .map(|node| (node.identifier, node.version))
.collect(); .collect();
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?; let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
+24
View File
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
/// function name with a `Node` suffix. /// function name with a `Node` suffix.
pub identifier: String, pub identifier: String,
pub version: u32, pub version: u32,
pub transient: bool,
pub function: String, pub function: String,
pub file: PathBuf, pub file: PathBuf,
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit. /// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
let mut path = module_path.join("::"); let mut path = module_path.join("::");
let mut version = 1; let mut version = 1;
let mut transient = false;
for argument in arguments { for argument in arguments {
transient |= argument.path().is_ident("transient");
let syn::Meta::List(list) = argument else { continue }; let syn::Meta::List(list) = argument else { continue };
if list.path.is_ident("path") { if list.path.is_ident("path") {
path = list.tokens.to_string().replace(' ', ""); path = list.tokens.to_string().replace(' ', "");
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
Some(NodeSource { Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)), identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version, version,
transient,
function: function_name, function: function_name,
file: file.to_path_buf(), file: file.to_path_buf(),
signature, signature,
@@ -171,4 +175,24 @@ mod tests {
assert!(!node.signature.contains("cache"), "{}", node.signature); assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature); assert!(node.signature.contains("image"), "{}", node.signature);
} }
#[test]
fn the_transient_attribute_is_read() {
let transient: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(transient, memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let saved: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category(""), memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
assert!(node(&transient).transient);
assert!(!node(&saved).transient);
}
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node, /// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename. /// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> { pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
let nodes = find_nodes(&workspace.join(NODE_CRATES))?; let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
let migrations = workspace.join(MIGRATIONS); let migrations = workspace.join(MIGRATIONS);
match (command, arguments) { match (command, arguments) {
@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}"); assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
} }
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste /// - paste
/// - assert that ellipse was copied /// - assert that ellipse was copied
#[tokio::test] #[tokio::test]
@@ -5,10 +5,14 @@ use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2}; use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graphene_std::application_io::Texture;
use graphene_std::blending_nodes::effects::{blur, drop_shadow}; use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend}; use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List}; use graphene_std::list::{Item, List};
use graphene_std::math_nodes::{color_value, gradient_value};
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::style::RenderMode;
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector}; use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
@@ -136,6 +140,111 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base"); assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
} }
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
#[derive(Clone, Copy, Debug)]
enum Endless {
Color,
Gradient,
NoisePattern,
}
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
editor
}
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
let node = match endless {
Endless::Color => color_value::IDENTIFIER,
Endless::Gradient => gradient_value::IDENTIFIER,
Endless::NoisePattern => noise_pattern::IDENTIFIER,
};
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
}
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.expect("a document is open");
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).expect("the active document exists");
let submitted = executor
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.expect("the evaluation is submitted");
let mut messages = editor.dispatch(submitted);
editor.runtime.update();
let frame = editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
(messages, frame)
}
#[tokio::test]
async fn endless_layers_clip_to_the_shape_beneath_them() {
let size = UVec2::new(256, 256);
let frame_pixels = async |editor: &mut EditorTestUtils| {
let (_, frame) = evaluate_viewport(editor, size).await;
let frame = frame.expect("the viewport presents a frame");
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
};
let pixel = |pixels: &[u8], x: u32, y: u32| {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
let rectangle_alone = frame_pixels(&mut editor).await;
add_clipped_endless_layer(&mut editor, endless).await;
let clipped = frame_pixels(&mut editor).await;
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
assert_eq!(
pixel(&clipped, x, y),
pixel(&rectangle_alone, x, y),
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
);
}
// In SVG Preview, the endless content is drawn only within the rectangle's mask
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
add_clipped_endless_layer(&mut editor, endless).await;
let (messages, _) = evaluate_viewport(&mut editor, size).await;
let svg = messages
.into_iter()
.find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
_ => None,
})
.expect("the viewport's artwork is sent as SVG");
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
assert!(
!draws_endless_content(unmasked) && draws_endless_content(masked),
"{endless:?}: the content is drawn within the mask: {svg}"
);
}
}
#[tokio::test] #[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() { async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] { for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
@@ -319,6 +319,9 @@ pub enum DocumentMessage {
UpdateTextFrames { UpdateTextFrames {
text_frames: HashMap<NodeId, DAffine2>, text_frames: HashMap<NodeId, DAffine2>,
}, },
UpdateFootprintAreas {
footprint_areas: HashMap<NodeId, DAffine2>,
},
UpdateClipTargets { UpdateClipTargets {
clip_targets: HashSet<NodeId>, clip_targets: HashSet<NodeId>,
}, },
@@ -1921,6 +1921,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect(); .collect();
self.network_interface.update_text_frames(layer_text_frames); self.network_interface.update_text_frames(layer_text_frames);
} }
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
self.network_interface.update_footprint_areas(footprint_areas);
}
DocumentMessage::UpdateClipTargets { clip_targets } => { DocumentMessage::UpdateClipTargets { clip_targets } => {
self.network_interface.update_clip_targets(clip_targets); self.network_interface.update_clip_targets(clip_targets);
} }
@@ -4138,7 +4141,7 @@ impl DocumentMessageHandler {
}) })
.unwrap_or((None, None, None)); .unwrap_or((None, None, None));
let blend_mode_menu_entries = BlendMode::list_svg_subset() let blend_mode_menu_entries = BlendMode::list()
.iter() .iter()
.map(|modes| { .map(|modes| {
modes modes
@@ -4155,7 +4158,7 @@ impl DocumentMessageHandler {
let widgets = vec![ let widgets = vec![
DropdownInput::new(blend_mode_menu_entries) DropdownInput::new(blend_mode_menu_entries)
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32)) .selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
.disabled(disabled) .disabled(disabled)
.draw_icon(false) .draw_icon(false)
.sizing(WidgetSizing::default().grow(false)) .sizing(WidgetSizing::default().grow(false))
@@ -1,11 +1,11 @@
use crate::application::Environment; use crate::application::Environment;
use crate::consts::{ use crate::consts::{
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN, DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR, VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
}; };
use crate::messages::frontend::utility_types::MouseCursorIcon; use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion}; use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition; use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation; use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ; use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface; use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
abortable_pan_start: Option<f64>, abortable_pan_start: Option<f64>,
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself. /// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
artwork_behind_graph: bool, artwork_behind_graph: bool,
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
graph_middle_click_start: Option<ViewportPosition>,
} }
#[message_handler_data] #[message_handler_data]
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
return; return;
}; };
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan }; self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
} }
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => { NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else { let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
responses.add(ToolMessage::UpdateCursor); responses.add(ToolMessage::UpdateCursor);
responses.add(ToolMessage::UpdateHints); responses.add(ToolMessage::UpdateHints);
responses.add(NavigateToolMessage::End); responses.add(NavigateToolMessage::End);
// Not a pan after all, but a middle click in the graph
let middle_click_start = self.graph_middle_click_start.take();
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
responses.add(NodeGraphMessage::MiddleClick);
}
} }
NavigationMessage::EndCanvasPTZWithClick { commit_key } => { NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
self.finish_operation_with_click = false; self.finish_operation_with_click = false;
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
} }
} }
NavigationMessage::PointerMove { snap } => { NavigationMessage::PointerMove { snap } => {
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
self.graph_middle_click_start = None;
}
match self.navigation_operation { match self.navigation_operation {
NavigationOperation::None => {} NavigationOperation::None => {}
NavigationOperation::Pan { .. } => { NavigationOperation::Pan { .. } => {
@@ -170,6 +170,8 @@ pub enum NodeGraphMessage {
PointerOutsideViewport { PointerOutsideViewport {
shift: Key, shift: Key,
}, },
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
MiddleClick,
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes. /// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
WireHoverTick, WireHoverTick,
/// Sends where everything gliding into place is drawn, along with the wires that follow it. /// Sends where everything gliding into place is drawn, along with the wires that follow it.
@@ -437,6 +439,7 @@ impl NodeGraphMessage {
| Self::PointerMove { .. } | Self::PointerMove { .. }
| Self::PointerUp | Self::PointerUp
| Self::PointerOutsideViewport { .. } | Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick | Self::WireHoverTick
| Self::SendGlide | Self::SendGlide
| Self::GlideTick | Self::GlideTick
@@ -1752,6 +1752,20 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.auto_panning.stop(&messages, responses); self.auto_panning.stop(&messages, responses);
} }
} }
// Middle-clicking a node toggles its visibility
NodeGraphMessage::MiddleClick => {
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
return;
}
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
return;
};
responses.add(NodeGraphMessage::ToggleVisibility {
node_id,
network_path: breadcrumb_network_path.to_vec(),
});
}
NodeGraphMessage::WireHoverTick => { NodeGraphMessage::WireHoverTick => {
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses); self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
} }
@@ -1337,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
return LayoutGroup::row(vec![]); return LayoutGroup::row(vec![]);
}; };
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() { if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
let entries = BlendMode::list_svg_subset() let entries = BlendMode::list()
.iter() .iter()
.map(|category| { .map(|category| {
category category
@@ -1354,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
widgets.extend_from_slice(&[ widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries) DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
]); ]);
} }
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.") LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
@@ -46,6 +46,8 @@ pub struct DocumentMetadata {
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>, pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
pub clip_targets: HashSet<NodeId>, pub clip_targets: HashSet<NodeId>,
pub vector_modify: HashMap<NodeId, VectorGeometry>, pub vector_modify: HashMap<NodeId, VectorGeometry>,
/// Per node with a footprint input, the unit square mapped onto its area in document space.
pub footprint_areas: HashMap<NodeId, DAffine2>,
/// Vector data keyed by layer ID, used as fallback when no Path node exists. /// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes. /// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>, pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
@@ -3399,6 +3399,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
); );
} }
#[tokio::test]
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
let graph_pan = |editor: &EditorTestUtils| {
editor
.active_document()
.network_interface
.network_metadata(&[])
.unwrap()
.persistent_metadata
.navigation_metadata
.node_graph_ptz
.pan
};
let layer_in_viewport = |editor: &EditorTestUtils| {
let network_interface = &editor.active_document().network_interface;
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
(0..=(max.x - min.x) as i32)
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
.expect("the layer should be pressable")
};
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
editor_position: position,
mouse_keys,
..Default::default()
};
// Pressed and released with a wobble too small to count as a drag
let start = layer_in_viewport(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
// Dragged away and back before the release
let start = layer_in_viewport(&editor);
let pan_before = graph_pan(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
editor.handle_message(DocumentMessage::Undo).await;
assert!(is_visible(&editor), "one undo should revert the middle click");
}
#[tokio::test] #[tokio::test]
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() { async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
@@ -138,6 +138,7 @@ impl NodeNetworkInterface {
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node)); self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node)); self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node)); self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer)); self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer)); self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer)); self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
@@ -189,6 +190,11 @@ impl NodeNetworkInterface {
self.document_metadata.vector_modify = new_vector_modify; self.document_metadata.vector_modify = new_vector_modify;
} }
/// Update the cached document space areas of the nodes with a footprint input
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
self.document_metadata.footprint_areas = new_footprint_areas;
}
/// Update the layer vector data (for layers without Path nodes) /// Update the layer vector data (for layers without Path nodes)
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) { pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
self.document_metadata.mark_changed(); self.document_metadata.mark_changed();
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
artboard_name, artboard_name,
artboard_count, artboard_count,
}; };
let result = self.executor.submit_document_export(document, document_id, export_config); let result = self.executor.submit_document_export(document, export_config);
if let Err(description) = result { if let Err(description) = result {
responses.add(DialogMessage::DisplayDialogError { responses.add(DialogMessage::DisplayDialogError {
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} }
} }
PortfolioMessage::SubmitClipboardSvg { id } => { PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| { let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
let selected = document.partition_selection().layers; responses.add(ClipboardMessage::Rendered { id, svg: None });
let mut layers = document return;
.metadata() };
.all_layers() let selected = document.partition_selection().layers;
.filter(|layer| selected.contains(layer)) let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
.map(|layer| layer.to_node()) layers.reverse();
.collect::<Vec<_>>(); responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
} }
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => { PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open; self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
@@ -0,0 +1,332 @@
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::context::bake_footprint;
use graphene_std::platform_application_io::rasterize;
use graphene_std::renderer::Quad;
use graphene_std::transform::Footprint;
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
#[derive(Clone, Debug, Default)]
pub struct FootprintCage {
target: Option<CageTarget>,
drag: Option<CageDrag>,
}
#[derive(Clone, Debug)]
struct CageTarget {
footprint_input: InputConnector,
area: Footprint,
/// Spans the area, with the unit square as its bounds.
bounding_box: BoundingBoxManager,
}
#[derive(Clone, Debug)]
struct CageDrag {
footprint_input: InputConnector,
original_area: Footprint,
unit_square_to_viewport: DAffine2,
kind: CageDragKind,
}
#[derive(Clone, Debug)]
enum CageDragKind {
Resize(SelectedEdges),
Move { grab: DVec2 },
}
impl FootprintCage {
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
self.target = visible.then(|| Self::find_target(document)).flatten();
}
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
let network_path = document.selection_network_path();
let network_interface = &document.network_interface;
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
let footprint_input = footprint_inputs.next()?;
if footprint_inputs.next().is_some() {
return None;
}
let node_id = footprint_input.node_id()?;
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
if unit_square_to_viewport.matrix2.determinant() == 0. {
return None;
}
let bounding_box = BoundingBoxManager {
bounds: [DVec2::ZERO, DVec2::ONE],
transform: unit_square_to_viewport,
..Default::default()
};
Some(CageTarget { footprint_input, area, bounding_box })
}
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
if let Some(target) = &mut self.target {
target.bounding_box.render_overlays(overlay_context, true);
}
}
/// The cursor for the part of the cage under the pointer, if any.
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
let target = self.target.as_ref()?;
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
if edge_cursor != MouseCursorIcon::Default {
return Some(edge_cursor);
}
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
}
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
let Some(target) = &self.target else { return false };
let bounding_box = &target.bounding_box;
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
} else if target.contains(mouse) {
CageDragKind::Move {
grab: bounding_box.transform.inverse().transform_point2(mouse),
}
} else {
return false;
};
self.drag = Some(CageDrag {
footprint_input: target.footprint_input,
original_area: target.area,
unit_square_to_viewport: bounding_box.transform,
kind,
});
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
true
}
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
let Some(drag) = &self.drag else { return };
let (position, size) = match &drag.kind {
CageDragKind::Resize(edges) => {
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
(position.min(position + size), size.abs())
}
CageDragKind::Move { grab } => {
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
(pointer - *grab, DVec2::ONE)
}
};
let original_area = drag.original_area;
let one_pixel = original_area.resolution.as_dvec2().recip();
let size = size.max(one_pixel);
let area = Footprint {
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
..original_area
};
responses.add(NodeGraphMessage::SetInput {
input_connector: drag.footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Keeps the drag in place on the document while the viewport pans by `shift`.
pub fn pan(&mut self, shift: DVec2) {
if let Some(drag) = &mut self.drag {
drag.unit_square_to_viewport.translation += shift;
}
}
/// Finishes the drag, undoing its changes if it was aborted.
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
if self.drag.take().is_none() {
return;
}
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
}
}
/// The input holding the footprint of a node that has one.
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
let reference = network_interface.reference(&node_id, network_path)?;
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
Some(InputConnector::node(node_id, rasterize::FootprintInput))
} else {
None
}
}
impl CageTarget {
fn contains(&self, viewport_point: DVec2) -> bool {
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::test_prelude::*;
#[tokio::test]
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let document = editor.active_document();
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
let metadata = document.metadata();
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
}
#[tokio::test]
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
use graphene_std::transform_nodes::transform;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: bake_footprint_node,
parent: layer,
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: transform_node,
parent: layer,
})
.await;
let translation = DVec2::new(100., 50.);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
input: NodeInput::value(TaggedValue::DVec2(translation), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let transformed = *editor
.active_document()
.metadata()
.footprint_areas
.get(&bake_footprint_node)
.expect("the area should still be reported");
let expected = DAffine2::from_translation(translation) * untransformed;
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
}
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::tool::utility_types::ToolType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
let area = Footprint {
transform: DAffine2::from_scale(DVec2::splat(100.)),
resolution: UVec2::splat(200),
..Default::default()
};
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
let metadata = editor.active_document().metadata();
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
editor.select_tool(ToolType::Select).await;
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
(area, dragged)
}
#[tokio::test]
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(300, 200));
}
#[tokio::test]
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
let one_pixel = 1. / area.resolution.x as f64;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(1, 200));
}
}
@@ -1,2 +1,3 @@
pub mod footprint_cage;
pub mod gizmo_manager; pub mod gizmo_manager;
pub mod shape_gizmos; pub mod shape_gizmos;
@@ -15,6 +15,7 @@ use crate::messages::tool::common_functionality::color_selector::{
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state, DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
}; };
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose}; use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::measure; use crate::messages::tool::common_functionality::measure;
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget}; use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
@@ -505,6 +506,7 @@ enum SelectToolFsmState {
}, },
RotatingBounds, RotatingBounds,
DraggingPivot, DraggingPivot,
DraggingFootprintCage,
} }
impl Default for SelectToolFsmState { impl Default for SelectToolFsmState {
@@ -545,6 +547,7 @@ struct SelectToolData {
axis_align: bool, axis_align: bool,
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>, non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
bounding_box_manager: Option<BoundingBoxManager>, bounding_box_manager: Option<BoundingBoxManager>,
footprint_cage: FootprintCage,
cursor: MouseCursorIcon, cursor: MouseCursorIcon,
pivot_gizmo: PivotGizmo, pivot_gizmo: PivotGizmo,
/// The pivot as it was when a drag of it began, restored if the drag is aborted. /// The pivot as it was when a drag of it began, restored if the drag is aborted.
@@ -954,6 +957,9 @@ impl Fsm for SelectToolFsmState {
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => { (_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document); crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
tool_data.footprint_cage.overlays(&mut overlay_context);
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count(); let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
let paintable_layers_selected = has_paintable_selection(document); let paintable_layers_selected = has_paintable_selection(document);
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected; tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
@@ -1388,6 +1394,10 @@ impl Fsm for SelectToolFsmState {
tool_data.drag_current = input.mouse.position; tool_data.drag_current = input.mouse.position;
tool_data.selection_mode = None; tool_data.selection_mode = None;
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
return SelectToolFsmState::DraggingFootprintCage;
}
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect(); let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>(); let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
let intersection = document.find_deepest(&intersection_list); let intersection = document.find_deepest(&intersection_list);
@@ -1620,6 +1630,18 @@ impl Fsm for SelectToolFsmState {
remove, remove,
} }
} }
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
let messages = [
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
SelectToolMessage::PointerMove { modifier_keys }.into(),
];
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
SelectToolFsmState::DraggingFootprintCage
}
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => { (SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
if let Some(bounds) = &mut tool_data.bounding_box_manager { if let Some(bounds) = &mut tool_data.bounding_box_manager {
resize_bounds( resize_bounds(
@@ -1721,6 +1743,10 @@ impl Fsm for SelectToolFsmState {
.as_ref() .as_ref()
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge))); .map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
cursor = footprint_cage_cursor;
}
// Dragging the pivot overrules the other operations // Dragging the pivot overrules the other operations
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() { if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
cursor = MouseCursorIcon::Move; cursor = MouseCursorIcon::Move;
@@ -1772,6 +1798,14 @@ impl Fsm for SelectToolFsmState {
self self
} }
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
tool_data.footprint_cage.pan(shift);
}
self
}
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => { (SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning // Auto-panning
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
@@ -1917,6 +1951,14 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior; let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection } SelectToolFsmState::Ready { selection }
} }
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
tool_data.footprint_cage.end_drag(drag_too_small, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => { (SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
let quad = tool_data.selection_quad(); let quad = tool_data.selection_quad();
@@ -2006,6 +2048,13 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior; let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection } SelectToolFsmState::Ready { selection }
} }
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
tool_data.footprint_cage.end_drag(true, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => { (SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
responses.add(DocumentMessage::AbortTransaction); responses.add(DocumentMessage::AbortTransaction);
tool_data.axis_align = false; tool_data.axis_align = false;
@@ -2175,6 +2224,13 @@ impl Fsm for SelectToolFsmState {
]); ]);
hint_data.send_layout(responses); hint_data.send_layout(responses);
} }
SelectToolFsmState::DraggingFootprintCage => {
let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
]);
hint_data.send_layout(responses);
}
SelectToolFsmState::RotatingBounds => { SelectToolFsmState::RotatingBounds => {
let hint_data = HintData(vec![ let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
+217 -176
View File
@@ -1,30 +1,37 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::list;
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List}; use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes}; use graphene_std::vector::{Vector, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter}; use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
mod observations;
#[cfg(test)] #[cfg(test)]
mod recompile_tests; mod recompile_tests;
mod runtime; mod runtime;
pub use observations::ObservationKey;
use observations::{path_content_observations, path_contents};
pub use runtime::*; pub use runtime::*;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -52,18 +59,6 @@ struct ViewportCanvasInfo {
resolution: DVec2, resolution: DVec2,
} }
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
#[derive(Debug)] #[derive(Debug)]
pub enum ExecutionResult { pub enum ExecutionResult {
Pending, Pending,
@@ -97,7 +92,8 @@ impl std::fmt::Display for EvaluationErrors {
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
pub struct CompilationResponse { pub struct CompilationResponse {
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>, result: Result<(), String>,
resolved_types: ResolvedDocumentNodeTypesDelta,
node_graph_errors: GraphErrors, node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors, node_graph_warnings: GraphErrors,
} }
@@ -112,19 +108,24 @@ pub enum NodeGraphUpdate {
}, },
/// The latest result of each observation, sent outside an execution after one of them changed. /// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>), Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg { Export {
id: u64, id: u64,
svg: Option<String>, result: Box<ExecutionResult>,
}, },
} }
#[derive(Debug)] #[derive(Debug)]
pub struct NodeGraphExecutor { pub struct NodeGraphExecutor {
sender: Sender<GraphRuntimeRequest>, sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>, receiver: Receiver<NodeGraphUpdate>,
current_execution_id: u64, current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>, futures: VecDeque<(u64, ExecutionContext)>,
pending: Option<(u64, ExecutionContext)>, pending: Option<(u64, ExecutionContext)>,
current_export_id: u64,
exports: HashMap<u64, ExportTarget>,
node_graph_hash: u64, node_graph_hash: u64,
/// The document whose network the graph runtime was last sent. /// The document whose network the graph runtime was last sent.
node_graph_document: Option<DocumentId>, node_graph_document: Option<DocumentId>,
@@ -146,9 +147,14 @@ pub struct NodeGraphExecutor {
gradient_migration_attempted: HashSet<DocumentId>, gradient_migration_attempted: HashSet<DocumentId>,
} }
#[derive(Debug)]
enum ExportTarget {
File(ExportConfig),
Clipboard(u64),
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ExecutionContext { struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId, document_id: DocumentId,
/// The view the render was asked for, which the footprints it reports back are measured in. /// The view the render was asked for, which the footprints it reports back are measured in.
document_to_viewport: DAffine2, document_to_viewport: DAffine2,
@@ -183,6 +189,8 @@ impl NodeGraphExecutor {
futures: Default::default(), futures: Default::default(),
pending: None, pending: None,
current_execution_id: 0, current_execution_id: 0,
current_export_id: 0,
exports: HashMap::new(),
node_graph_hash: 0, node_graph_hash: 0,
node_graph_document: None, node_graph_document: None,
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
@@ -211,6 +219,21 @@ impl NodeGraphExecutor {
execution_id execution_id
} }
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
let id = self.current_export_id;
self.current_export_id += 1;
let request = GraphRuntimeRequest::Export {
id,
render_config,
network,
resources,
};
self.sender.send(request).map_err(|e| e.to_string())?;
self.exports.insert(id, target);
Ok(())
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) { pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) { if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}"); log::error!("Failed to send the overlays: {error}");
@@ -229,13 +252,29 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides"); .expect("Failed to send the context overrides");
} }
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message { pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
if document_id.is_none() || self.node_graph_document != document_id { let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
return ClipboardMessage::Rendered { id, svg: None }.into(); let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
} return no_svg;
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request"); let viewport = Footprint {
Message::NoOp resolution: (max - min).round().as_uvec2(),
transform: DAffine2::from_translation(-min),
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
Ok(()) => Message::NoOp,
Err(_) => no_svg,
}
} }
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) { pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -260,9 +299,11 @@ impl NodeGraphExecutor {
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash()); let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash { if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths(); let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &previewed, &layers);
let thumbnails = thumbnail_sources(&network, &layers);
self.node_graph_hash = graph_hash; self.node_graph_hash = graph_hash;
self.node_graph_document = Some(document_id); self.node_graph_document = Some(document_id);
@@ -272,8 +313,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed, thumbnails,
layers,
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -337,7 +377,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -404,7 +443,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -415,10 +453,9 @@ impl NodeGraphExecutor {
} }
/// Evaluates a node graph for export /// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> { pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg { let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg graphene_std::application_io::ExportFormat::Svg
@@ -452,34 +489,12 @@ impl NodeGraphExecutor {
time: Default::default(), time: Default::default(),
pointer: DVec2::ZERO, pointer: DVec2::ZERO,
export_format, export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal, render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true, for_export: true,
for_eyedropper: false, for_eyedropper: false,
}; };
// Execute the node graph self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
},
));
Ok(())
} }
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile. /// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
@@ -491,8 +506,8 @@ impl NodeGraphExecutor {
} }
let mut all_dropped_thumbnails = Vec::new(); let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter(); let results = self.receiver.try_iter().collect::<Vec<_>>();
for response in results.by_ref() { for response in results {
match response { match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => { NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse { let ExecutionResponse {
@@ -516,7 +531,7 @@ impl NodeGraphExecutor {
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked"); let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { if execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone())); self.pending = Some((execution_id, execution_context.clone()));
} }
execution_context execution_context
@@ -571,7 +586,7 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it // A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { if !matches!(result, ExecutionResult::Pending) {
let errors = match &result { let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| { let in_document = |path: &&[NodeId]| {
@@ -640,15 +655,13 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
if let Some(message) = &message { if let Some(message) = &message {
log::error!("Node graph evaluation failed:\n{message}"); log::error!("Node graph evaluation failed:\n{message}");
} }
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break; continue;
} }
}; };
@@ -666,10 +679,8 @@ impl NodeGraphExecutor {
} }
document.network_interface.update_vector_modify(path_contents(&observations)); document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) { if let Some(node_graph_output) = node_graph_output {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {}
} }
responses.add(DeferMessage::TriggerGraphRun { responses.add(DeferMessage::TriggerGraphRun {
execution_id, execution_id,
@@ -691,49 +702,43 @@ impl NodeGraphExecutor {
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
result, result,
resolved_types,
} = execution_response; } = execution_response;
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend // The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() { if self.gradient_migration.is_some() {
if let Err((_, e)) = &result { if let Err(e) = &result {
log::trace!("Gradient migration measurement compile: {e}"); log::trace!("Gradient migration measurement compile: {e}");
} }
continue; continue;
} }
let type_delta = match result { if let Err(e) = &result {
Err((incomplete_delta, e)) => { // Clear the click targets while the graph is in an un-renderable state
// Clear the click targets while the graph is in an un-renderable state
document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others // The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() { if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}"); log::error!("The node graph failed to compile:\n{e}");
} else { } else {
log::trace!("{e}"); log::trace!("{e}");
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: incomplete_delta,
node_graph_errors,
node_graph_warnings,
});
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
} }
Ok(result) => result, }
};
responses.add(NodeGraphMessage::UpdateTypes { responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: type_delta, resolved_types,
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
}); });
if result.is_err() {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
}
} }
NodeGraphUpdate::EyedropperPreview(raster) => { NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8(); let (data, width, height) = raster.to_flat_u8();
@@ -756,33 +761,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses); Self::receive_thumbnails(document, thumbnails, responses);
} }
} }
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }), NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
}
}
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let execution_context = self.execution_context(execution_response.execution_id);
if execution_context.is_some_and(|context| context.document_id == document_id) {
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
}
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
NodeGraphUpdate::Thumbnails {
responses: thumbnails,
document_id: thumbnails_document,
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
_ => {}
} }
} }
@@ -798,15 +777,6 @@ impl NodeGraphExecutor {
} }
} }
/// What an execution was submitted for, while it's still queued or pending.
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
self.futures
.iter()
.chain(&self.pending)
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
.map(|(_, execution_context)| execution_context)
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running. /// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still /// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
@@ -876,6 +846,10 @@ impl NodeGraphExecutor {
return; return;
} }
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
let fill_measurement = Observation { let fill_measurement = Observation {
node_path: full_path, node_path: full_path,
@@ -887,8 +861,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed: Vec::new(), thumbnails,
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
})) }))
.is_err() .is_err()
@@ -920,7 +893,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: Some((network_path, fill_node_id, gradient)), measure_fill: Some((network_path, fill_node_id, gradient)),
@@ -1051,6 +1023,7 @@ impl NodeGraphExecutor {
outlines, outlines,
group_layers, group_layers,
text_frames, text_frames,
footprint_areas,
clip_targets, clip_targets,
vector_data, vector_data,
appearance_attributes, appearance_attributes,
@@ -1059,6 +1032,9 @@ impl NodeGraphExecutor {
backgrounds: _, backgrounds: _,
} = render_output.metadata; } = render_output.metadata;
let viewport_to_document = document_to_viewport.inverse();
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
// Run these update state messages immediately // Run these update state messages immediately
responses.add(DocumentMessage::UpdateUpstreamTransforms { responses.add(DocumentMessage::UpdateUpstreamTransforms {
upstream_footprints, upstream_footprints,
@@ -1069,6 +1045,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers }); responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
responses.add(DocumentMessage::UpdateOutlines { outlines }); responses.add(DocumentMessage::UpdateOutlines { outlines });
responses.add(DocumentMessage::UpdateTextFrames { text_frames }); responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets }); responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data }); responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes }); responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
@@ -1080,6 +1057,51 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status }); responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
} }
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(target) = self.exports.remove(&export_id) else { return };
let failure = match (result, &target) {
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
return match target {
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
ExportTarget::Clipboard(id) => {
let svg = match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Some(svg),
_ => None,
};
responses.add(ClipboardMessage::Rendered { id, svg });
}
};
}
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
(ExecutionResult::Panic(payload), _) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Some(format!("Panicked: {}", message.unwrap_or("no message")))
}
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
};
if let Some(message) = &failure {
log::error!("Node graph evaluation failed:\n{message}");
}
match target {
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}),
ExportTarget::Clipboard(id) => {
responses.add(ClipboardMessage::Rendered { id, svg: None });
if let Some(description) = failure {
let title = "Unable to copy as SVG".to_string();
responses.add(DialogMessage::DisplayDialogError { title, description });
}
}
}
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) { fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let ExportConfig { let ExportConfig {
file_type, file_type,
@@ -1179,6 +1201,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
} }
} }
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
apply_previews(network, previewed);
write_layer_paths(network, layers);
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
// O(layers * depth)
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
layers.iter().filter_map(source).collect()
}
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
let metadata = interface.document_metadata();
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
artboards if artboards == layers.len() => list!(Artboard),
_ => return None,
};
let mut network = interface.document_network().clone();
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
let mut below = NodeInput::type_default(stack, true);
let mut bounds = None;
for &layer in layers {
let mut node = network.nodes.get(&layer.to_node())?.clone();
*node.inputs.first_mut()? = below;
let copy = NodeId::new();
network.nodes.insert(copy, node);
below = NodeInput::node(copy, 0);
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
true => metadata.downstream_transform_to_document(layer).inverse(),
false => DAffine2::IDENTITY,
};
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
}
network.exports = vec![below];
Some((network, bounds?))
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform. /// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> { fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
@@ -1200,45 +1277,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None None
} }
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
// Re-export for usage by tests in other modules // Re-export for usage by tests in other modules
#[cfg(test)] #[cfg(test)]
pub use test::Instrumented; pub use test::Instrumented;
@@ -1273,14 +1311,17 @@ mod test {
network.inline_definitions().map_err(|error| error.to_string())?; network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network); let instrumented = Instrumented::new(&network);
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
self.sender self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed: Vec::new(), thumbnails,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -0,0 +1,51 @@
use super::{InspectResult, Observation, ObservedConnector};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use graph_craft::document::NodeId;
use graphene_std::list::{Item, List};
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
use graphene_std::{ContextOverrides, NodeParameter};
use std::collections::HashMap;
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
pub(super) fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
editor.dispatch(Message::Wake); editor.dispatch(Message::Wake);
} }
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops /// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// for one more update, so a first update clears those of the graph before it. /// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> { async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await; compile_and_run(editor).await;
compile_and_run(editor).await; compile_and_run(editor).await;
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout; use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi; use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::document::NodeId;
use graphene_std::application_io::{ApplicationIo, Texture}; use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient; use graphene_std::gradient::Gradient;
@@ -12,12 +12,11 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle}; use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; use graphene_std::renderer::Render;
use graphene_std::transform::{Footprint, RenderQuality}; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic}; use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content;
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc; use std::sync::Arc;
@@ -83,12 +82,9 @@ impl Thumbnails {
} }
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale. /// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) { pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
// O(layers * depth) let source_map = executor.tree().source_map();
let sources: HashMap<NodeId, NodeId> = layer_paths let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content // A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source)); let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
@@ -276,11 +272,11 @@ impl ThumbnailContent {
} }
} }
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out. /// The area the content covers once rendered, counting the effects drawn through maps and images.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox { fn content_bounds(&self) -> RenderBoundingBox {
match self { match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach // Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved), Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
// The clipping rectangles rather than the content, since the renderer clips content to them // The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards), Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY), Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +285,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio. /// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] { fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) { let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds, RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE], _ => [DVec2::ZERO, DVec2::ONE],
}; };
@@ -297,45 +293,6 @@ impl ThumbnailContent {
} }
} }
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic. /// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> { fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic { macro_rules! downcast_into_graphic {
@@ -2,6 +2,8 @@
import { getContext, onMount, onDestroy } from "svelte"; import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
import type { DragToggleListener } from "/src/managers/drag-toggle";
import { inspectorLayout } from "/src/stores/portfolio"; import { inspectorLayout } from "/src/stores/portfolio";
import { createAutoScroller } from "/src/utility-functions/auto-scroll"; import { createAutoScroller } from "/src/utility-functions/auto-scroll";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -23,7 +25,15 @@
let lastDragClientY = 0; let lastDragClientY = 0;
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY)); const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
// Everything one middle-button drag across the section headers paints is one history step
const dragToggleListener: DragToggleListener = {
groups: ["inspector-section-visibility"],
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
};
onMount(() => { onMount(() => {
createDragToggleManager(dragToggleListener);
addEventListener("pointermove", draggingPointerMove); addEventListener("pointermove", draggingPointerMove);
addEventListener("pointerup", draggingPointerUp); addEventListener("pointerup", draggingPointerUp);
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it // A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
@@ -36,6 +46,8 @@
}); });
onDestroy(() => { onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove); removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp); removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag); removeEventListener("pointercancel", abortDrag);
@@ -331,6 +331,7 @@
} }
const dragToggleListener: DragToggleListener = { const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => { activeGroupChanged: (group) => {
activeDragToggleGroup = group; activeDragToggleGroup = group;
}, },
@@ -342,6 +343,15 @@
editor.toggleNodeVisibilityLayerPanel(id); editor.toggleNodeVisibilityLayerPanel(id);
} }
// Middle-clicking one of the chain's node buttons toggles that node's visibility
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
if (e.button !== 1) return;
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
}
function toggleLayerLock(id: bigint) { function toggleLayerLock(id: bigint) {
editor.toggleLayerLock(id); editor.toggleLayerLock(id);
} }
@@ -1194,6 +1204,7 @@
on:pointerdown={(e) => layerPointerDown(e, listing)} on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)} on:click={(e) => selectLayerWithModifiers(e, listing)}
on:dblclick={(e) => chainIconsDoubleClick(e, listing)} on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
on:pointerenter={() => hoverRow(index)} on:pointerenter={() => hoverRow(index)}
on:pointerleave={() => (hoveredRowIndex = undefined)} on:pointerleave={() => (hoveredRowIndex = undefined)}
> >
@@ -1343,6 +1354,8 @@
data-chain-node={slot.nodeIndex} data-chain-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition} data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
/> />
{/if} {/if}
{/if} {/if}
@@ -1359,12 +1372,17 @@
: entry.chainExpanded : entry.chainExpanded
? "Stop listing this layer's chain one node per row." ? "Stop listing this layer's chain one node per row."
: "List this layer's chain one node per row, beneath the layer."} : "List this layer's chain one node per row, beneath the layer."}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
on:click={(e) => { on:click={(e) => {
// Without a chain to expand, a click selects the layer as it does elsewhere in the row // Without a chain to expand, a click selects the layer as it does elsewhere in the row
if (entry.chainNodes.length === 0) return; if (entry.chainNodes.length === 0) return;
e.stopPropagation(); e.stopPropagation();
editor.toggleLayerChainExpanded(listing.id); editor.toggleLayerChainExpanded(listing.id);
}} }}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
}}
> >
<IconLabel <IconLabel
icon={entry.iconName} icon={entry.iconName}
@@ -1395,10 +1413,15 @@
data-chain-row-node={slot.nodeIndex} data-chain-row-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition} data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
on:pointerdown={(e) => { on:pointerdown={(e) => {
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode); if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
}} }}
on:click={(e) => chainNodeClick(e, listing, chainNode.id)} on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
}}
on:dblclick={(e) => { on:dblclick={(e) => {
// Only the node's icon opens it in the graph // Only the node's icon opens it in the graph
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id); if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
@@ -41,6 +41,12 @@
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey; const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel); editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
} }
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
if (e.button !== 1 || widgetData.disabled) return;
editor.toggleNodeVisibilityInspector(widgetData.id);
}
</script> </script>
<!-- TODO: Implement collapsable sections with the Inspector system --> <!-- TODO: Implement collapsable sections with the Inspector system -->
@@ -76,7 +82,16 @@
{/if} {/if}
{/each} {/each}
{:else} {:else}
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}> <button
class="header"
class:expanded
class:expandable
data-inspector-reorder-handle={reorderable ? "" : undefined}
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
onclick={toggleExpandedWithModifiers}
onauxclick={toggleVisibilityWithMiddleClick}
>
<div <div
class="icon-slot" class="icon-slot"
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"} data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
+81 -25
View File
@@ -8,21 +8,30 @@
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain // The gesture only engages once the pointer crosses from the source into a different sibling, so plain
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling // clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
// the pointer enters whose state still matches the source's recorded starting state is also clicked. // the pointer enters whose state still matches the source's recorded starting state is also clicked.
//
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
// rather than a click. Their gesture engages on the press, which toggles the source at once.
export type DragToggleListener = { export type DragToggleListener = {
// The groups whose gestures this listener is told about
groups: string[];
// Given the group of the pressed button, and undefined once the press ends // Given the group of the pressed button, and undefined once the press ends
activeGroupChanged?: (activeGroup: string | undefined) => void; activeGroupChanged?: (activeGroup: string | undefined) => void;
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step // Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
engagedChanged?: (engaged: boolean) => void; engagedChanged?: (engaged: boolean) => void;
}; };
const MIDDLE_BUTTON = 1;
const listeners = new Set<DragToggleListener>(); const listeners = new Set<DragToggleListener>();
let activeGroup: string | undefined = undefined; let activeGroup: string | undefined = undefined;
let middleButtonGesture = false;
let source: HTMLElement | undefined = undefined; let source: HTMLElement | undefined = undefined;
let startingState: string | undefined = undefined; let startingState: string | undefined = undefined;
let visited = new WeakSet<Element>(); let visited = new WeakSet<Element>();
let engaged = false; let engaged = false;
let suppressNextClickFromSource: HTMLElement | undefined = undefined; let suppressNextClickFromSource: HTMLElement | undefined = undefined;
let suppressNextAuxClick = false;
export function createDragToggleManager(listener: DragToggleListener) { export function createDragToggleManager(listener: DragToggleListener) {
listeners.add(listener); listeners.add(listener);
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
window.addEventListener("blur", onPointerUp); window.addEventListener("blur", onPointerUp);
// Capture phase on click suppresses the natural source-click before the button's handler runs // Capture phase on click suppresses the natural source-click before the button's handler runs
window.addEventListener("click", onClickCapture, true); window.addEventListener("click", onClickCapture, true);
window.addEventListener("auxclick", onAuxClickCapture, true);
} }
} }
export function destroyDragToggleManager(listener: DragToggleListener) { export function destroyDragToggleManager(listener: DragToggleListener) {
// A consumer leaving mid-gesture still hears it end // A consumer leaving mid-gesture still hears it end
if (engaged) listener.engagedChanged?.(false); if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
listeners.delete(listener); listeners.delete(listener);
// Uninstall the window event listeners only once the last consumer leaves // Uninstall the window event listeners only once the last consumer leaves
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
window.removeEventListener("pointercancel", onPointerUp); window.removeEventListener("pointercancel", onPointerUp);
window.removeEventListener("blur", onPointerUp); window.removeEventListener("blur", onPointerUp);
window.removeEventListener("click", onClickCapture, true); window.removeEventListener("click", onClickCapture, true);
window.removeEventListener("auxclick", onAuxClickCapture, true);
activeGroup = undefined; activeGroup = undefined;
middleButtonGesture = false;
source = undefined; source = undefined;
startingState = undefined; startingState = undefined;
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
suppressNextClickFromSource = undefined; suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
} }
} }
function notifyActiveGroupChange(group: string | undefined) { function listenersOfGroup(group: string): DragToggleListener[] {
activeGroup = group; return Array.from(listeners).filter((listener) => listener.groups.includes(group));
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
} }
function findMember(target: EventTarget | undefined): HTMLElement | undefined { function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group;
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
}
function groupAttribute(middleButton: boolean): string {
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
}
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
if (!(target instanceof Element)) return undefined; if (!(target instanceof Element)) return undefined;
const found = target.closest("[data-drag-toggle-group]"); const found = target.closest(`[${groupAttribute(middleButton)}]`);
return found instanceof HTMLElement ? found : undefined; return found instanceof HTMLElement ? found : undefined;
} }
function onPointerDown(e: PointerEvent) { function memberState(member: HTMLElement): string | undefined {
if (e.button !== 0) return; return member.getAttribute("data-drag-toggle-state") || undefined;
suppressNextClickFromSource = undefined; }
const found = findMember(e.target || undefined); function toggle(member: HTMLElement) {
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
else member.click();
}
function engage() {
if (!activeGroup || !source) return;
engaged = true;
visited.add(source);
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
if (memberState(source) === startingState) toggle(source);
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON;
const found = findMember(e.target || undefined, middleButton);
if (!found) return; if (!found) return;
// Stop the event so sibling drag/select handlers on ancestors don't also engage // Stop the event so sibling drag/select handlers on ancestors don't also engage
e.stopPropagation(); e.stopPropagation();
middleButtonGesture = middleButton;
source = found; source = found;
startingState = found.getAttribute("data-drag-toggle-state") || undefined; startingState = memberState(found);
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined); notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
if (middleButton) engage();
} }
function onPointerMove(e: PointerEvent) { function onPointerMove(e: PointerEvent) {
if (!activeGroup || !source) return; if (!activeGroup || !source) return;
const member = findMember(e.target || undefined); const member = findMember(e.target || undefined, middleButtonGesture);
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return; if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger // Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
if (member === source || visited.has(member)) return; if (member === source || visited.has(member)) return;
// First crossing engages the drag and toggles the source as part of the operation // First crossing engages the drag and toggles the source as part of the operation
if (!engaged) { if (!engaged) engage();
engaged = true;
visited.add(source);
listeners.forEach((listener) => listener.engagedChanged?.(true));
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
}
// Toggle only peers still in the starting state, so we don't flip ones already at the target state // Toggle only peers still in the starting state, so we don't flip ones already at the target state
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return; if (memberState(member) !== startingState) return;
visited.add(member); visited.add(member);
member.click(); toggle(member);
} }
function onPointerUp(e: Event) { function onPointerUp(e: Event) {
if (!activeGroup) return; if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again // An engaged drag already toggled the source, so its release's click won't toggle it again
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source; if (engaged && source && e.type === "pointerup") {
if (middleButtonGesture) suppressNextAuxClick = true;
else suppressNextClickFromSource = source;
}
const wasEngaged = engaged; const wasEngaged = engaged;
middleButtonGesture = false;
source = undefined; source = undefined;
startingState = undefined; startingState = undefined;
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
notifyActiveGroupChange(undefined); notifyActiveGroupChange(undefined);
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false)); if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
} }
function onClickCapture(e: Event) { function onClickCapture(e: Event) {
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
suppressNextClickFromSource = undefined; suppressNextClickFromSource = undefined;
} }
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
function onAuxClickCapture(e: MouseEvent) {
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
suppressNextAuxClick = false;
e.stopPropagation();
e.preventDefault();
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
const carried = Array.from(listeners); const carried = Array.from(listeners);
@@ -360,15 +360,11 @@ impl NodeNetwork {
}; };
let value_node_id = gen_id(); let value_node_id = gen_id();
let merged_node_id = map_ids(id, value_node_id); let merged_node_id = map_ids(id, value_node_id);
let mut original_location = OriginalLocation { let original_location = OriginalLocation {
path: Some(path.to_vec()),
dependants: vec![vec![id]], dependants: vec![vec![id]],
..Default::default() ..Default::default()
}; };
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert( collection.insert(
merged_node_id, merged_node_id,
DocumentNode { DocumentNode {
@@ -63,7 +63,6 @@ fn flatten_add_expected() -> NodeNetwork {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)], inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation { original_location: OriginalLocation {
path: Some(vec![NodeId(4)]),
dependants: vec![vec![NodeId(10)]], dependants: vec![vec![NodeId(10)]],
..Default::default() ..Default::default()
}, },
+1 -1
View File
@@ -128,7 +128,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
impl CompiledDocument { impl CompiledDocument {
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> { pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| { let output = executor.insert(self.proto_network).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect(); let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n") messages.join("\n")
})?; })?;
+3 -3
View File
@@ -133,13 +133,13 @@ impl Viewer {
Err(error) => return log::error!("Compile failed: {error}"), Err(error) => return log::error!("Compile failed: {error}"),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
match executor.update(proto) { match executor.insert(proto) {
Ok((output, _)) => { Ok(output) => {
self.graph_runtime.update_sources(executor.sources()); self.graph_runtime.update_sources(executor.sources());
log::info!("Document compiled"); log::info!("Document compiled");
self.executor = Some((executor, output)); self.executor = Some((executor, output));
} }
Err((_, errors)) => { Err(errors) => {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect(); let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
log::error!("Executor creation failed: {}", messages.join("\n")); log::error!("Executor creation failed: {}", messages.join("\n"));
} }
@@ -18,7 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
preprocessor.preprocess(&mut network, &|_| None).unwrap(); preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network); let proto_network = compile(network);
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network.clone()).unwrap(); let output = executor.insert(proto_network.clone()).unwrap();
(executor, output, proto_network) (executor, output, proto_network)
} }
@@ -73,7 +73,7 @@ impl Session {
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle()); let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document"); self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network; let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor"); self.output = self.executor.insert(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig { let render_config = RenderConfig {
viewport: Footprint { viewport: Footprint {
@@ -16,7 +16,7 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
c.bench_function(name, |b| { c.bench_function(name, |b| {
b.iter_batched( b.iter_batched(
|| (executor.clone(), proto_network.clone()), || (executor.clone(), proto_network.clone()),
|(mut executor, network)| executor.update(std::hint::black_box(network)), |(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -36,7 +36,7 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let proto_network = compile(network); let proto_network = compile(network);
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap(); let output = executor.insert(proto_network).unwrap();
let footprint = Footprint::default(); let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint))); c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
@@ -13,7 +13,7 @@ fn update_executor(c: &mut Criterion) {
let (_, _, proto_network) = setup_network(name); let (_, _, proto_network) = setup_network(name);
(DynamicExecutor::default(), proto_network) (DynamicExecutor::default(), proto_network)
}, },
|(mut executor, network)| executor.update(std::hint::black_box(network)), |(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -15,7 +15,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor { pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup; let (mut executor, network) = setup;
let _ = black_box(executor.update(black_box(network))); let _ = black_box(executor.insert(black_box(network)));
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -19,8 +19,7 @@ pub struct DynamicExecutor {
typing_context: TypingContext, typing_context: TypingContext,
/// The outputs of the networks, kept alive by the executor as long as there are handles to them. /// The outputs of the networks, kept alive by the executor as long as there are handles to them.
outputs: Vec<Weak<NodeId>>, outputs: Vec<Weak<NodeId>>,
// Kept for one more update, so a node that comes back is reused type_deltas: TypeDeltaCollector,
orphaned_nodes: HashSet<NodeId>,
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@@ -38,7 +37,7 @@ impl Default for DynamicExecutor {
tree: Default::default(), tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY), typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
outputs: Vec::new(), outputs: Vec::new(),
orphaned_nodes: HashSet::new(), type_deltas: Default::default(),
} }
} }
} }
@@ -64,19 +63,37 @@ impl DynamicExecutor {
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible. /// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))] #[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn insert(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let (output, add) = self.insert_nodes(proto_network)?; let output = self.insert_nodes(proto_network)?;
let remove = self.free_orphaned_nodes(); self.free_orphaned_nodes();
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove })) Ok(output)
} }
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn replace(&mut self, output: OutputHandle, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let (output, add) = self.insert_nodes(proto_network)?; let inserted = self.insert_nodes(proto_network)?;
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() })) let Some(replaced) = Arc::into_inner(output.0) else { return Ok(inserted) };
let live: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
let mut pending = vec![replaced];
while let Some(node) = pending.pop() {
let Some((container, _, inputs)) = self.tree.nodes.get(&node) else { continue };
if Arc::strong_count(container) > 1 || live.contains(&node) {
continue;
}
pending.extend(inputs.iter());
if let Some(path) = self.tree.free_node(node) {
self.type_deltas.remove(path);
}
self.typing_context.remove_inference(node);
}
Ok(inserted)
} }
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn take_type_deltas(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
self.typing_context.update(&proto_network).map_err(|e| { self.type_deltas.take()
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
self.typing_context.update(&proto_network).inspect_err(|_| {
// If there is an error then get types that have been resolved before the error // If there is an error then get types that have been resolved before the error
let add = proto_network let add = proto_network
.nodes .nodes
@@ -94,11 +111,13 @@ impl DynamicExecutor {
) )
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e) self.type_deltas.add(add);
})?; })?;
let output = proto_network.output; let output = proto_network.output;
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let add = self.tree.update(proto_network, &self.typing_context)?;
self.outputs.retain(|output| output.strong_count() > 0); self.outputs.retain(|output| output.strong_count() > 0);
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output); let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
let output = held.unwrap_or_else(|| { let output = held.unwrap_or_else(|| {
@@ -107,11 +126,11 @@ impl DynamicExecutor {
output output
}); });
let add = self.document_node_types(add.into_iter()).collect(); self.type_deltas.add(self.tree.node_types(add.into_iter()));
Ok((OutputHandle(output), add)) Ok(OutputHandle(output))
} }
fn free_orphaned_nodes(&mut self) -> Vec<Path> { fn free_orphaned_nodes(&mut self) {
let mut kept = HashSet::new(); let mut kept = HashSet::new();
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect(); let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
while let Some(node) = pending.pop() { while let Some(node) = pending.pop() {
@@ -121,19 +140,14 @@ impl DynamicExecutor {
pending.extend(inputs.iter()); pending.extend(inputs.iter());
} }
} }
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect(); let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned); for node_id in orphaned {
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len())); let path = self.tree.free_node(node_id);
for node_id in old_to_remove { self.typing_context.remove_inference(node_id);
if self.orphaned_nodes.contains(&node_id) { if let Some(path) = path {
let path = self.tree.free_node(node_id); self.type_deltas.remove(path);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
remove.push(path);
}
} }
} }
remove
} }
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> { pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
@@ -153,7 +167,7 @@ impl DynamicExecutor {
} }
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a { pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.tree.source_map().get(&id).map(|(_, b)| (id, b.clone()))) self.tree.node_types(nodes)
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767 // TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node. // TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
} }
@@ -559,6 +573,39 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> { pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map &self.source_map
} }
pub fn node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.source_map().get(&id).map(|(_, b)| (id, b.clone())))
}
}
#[derive(Clone, Default)]
struct TypeDeltaCollector {
changes: HashMap<Path, Option<NodeTypes>>,
}
impl TypeDeltaCollector {
fn add(&mut self, types: impl IntoIterator<Item = (Path, NodeTypes)>) {
self.changes.extend(types.into_iter().map(|(path, types)| (path, Some(types))));
}
fn remove(&mut self, path: Path) {
self.changes.insert(path, None);
}
fn take(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
if self.changes.is_empty() {
return None;
}
let mut delta = ResolvedDocumentNodeTypesDelta::default();
for (path, types) in self.changes.drain() {
match types {
Some(types) => delta.add.push((path, types)),
None => delta.remove.push(path),
}
}
Some(delta)
}
} }
#[cfg(test)] #[cfg(test)]
@@ -876,7 +876,7 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
#[test] #[test]
fn a_trace_leads_to_the_node_that_raised_the_error() { fn a_trace_leads_to_the_node_that_raised_the_error() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap(); let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty()); assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]); assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
@@ -899,7 +899,7 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)], nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]); assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
} }
@@ -936,7 +936,7 @@ fn chained_fallbacks_both_reach_the_root() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
let context: Context = None; let context: Context = None;
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else { let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
@@ -966,7 +966,7 @@ fn an_error_after_a_fallback_keeps_both() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
let context: Context = None; let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else { let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -995,7 +995,7 @@ fn a_node_error_names_the_node_that_raised_it() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve"); let output = executor.insert(network).expect("The Throw Error nodes should resolve");
let context: Context = None; let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else { let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -1050,7 +1050,7 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The error handling nodes should resolve"); let output = executor.insert(network).expect("The error handling nodes should resolve");
(executor, output) (executor, output)
} }
@@ -1190,16 +1190,6 @@ fn source_network(node: u64) -> ProtoNetwork {
} }
} }
#[test]
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test] #[test]
fn networks_are_executed_side_by_side_by_their_handles() { fn networks_are_executed_side_by_side_by_their_handles() {
let network = |node: u64| ProtoNetwork { let network = |node: u64| ProtoNetwork {
@@ -1208,8 +1198,8 @@ fn networks_are_executed_side_by_side_by_their_handles() {
nodes: vec![value_node(node, TaggedValue::Number(node as f64))], nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(network(0)).unwrap(); let first = executor.insert(network(0)).unwrap();
let (second, _) = executor.update(network(1)).unwrap(); let second = executor.insert(network(1)).unwrap();
let context: Context = None; let context: Context = None;
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.))); assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
@@ -1219,9 +1209,9 @@ fn networks_are_executed_side_by_side_by_their_handles() {
#[test] #[test]
fn an_output_that_is_already_held_shares_its_handle() { fn an_output_that_is_already_held_shares_its_handle() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(source_network(0)).unwrap(); let first = executor.insert(source_network(0)).unwrap();
let (second, _) = executor.update(source_network(0)).unwrap(); let second = executor.insert(source_network(0)).unwrap();
let (other, _) = executor.update(source_network(1)).unwrap(); let other = executor.insert(source_network(1)).unwrap();
assert!(Arc::ptr_eq(&first.0, &second.0)); assert!(Arc::ptr_eq(&first.0, &second.0));
assert!(!Arc::ptr_eq(&first.0, &other.0)); assert!(!Arc::ptr_eq(&first.0, &other.0));
@@ -1230,28 +1220,123 @@ fn an_output_that_is_already_held_shares_its_handle() {
#[test] #[test]
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() { fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap(); let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some()); let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
for _ in 0..3 { for _ in 0..3 {
executor.update(source_network(2)).unwrap(); executor.insert(source_network(2)).unwrap();
} }
assert_eq!(kept(&executor), [true; 2]); assert_eq!(kept(&executor), [true; 2]);
drop(output); drop(output);
executor.update(source_network(2)).unwrap(); executor.insert(source_network(2)).unwrap();
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [false; 2]); assert_eq!(kept(&executor), [false; 2]);
} }
#[test] #[test]
fn a_source_is_listed_for_as_long_as_its_node_lives() { fn a_source_is_listed_for_as_long_as_its_node_lives() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap(); let output = executor.insert(source_network(0)).unwrap();
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
for _ in 0..3 { executor.insert(source_network(1)).unwrap();
executor.update(source_network(1)).unwrap(); assert!(listed(&executor));
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
drop(output);
executor.insert(source_network(1)).unwrap();
assert!(!listed(&executor));
}
fn changed_paths(executor: &mut DynamicExecutor) -> Option<[Vec<u64>; 2]> {
let changes = executor.take_type_deltas()?;
let added = changes.add.iter().map(|(path, _)| path[0].0);
let removed = changes.remove.iter().map(|path| path[0].0);
let mut paths = [added.collect::<Vec<_>>(), removed.collect()];
paths.iter_mut().for_each(|paths| paths.sort_unstable());
Some(paths)
}
#[test]
fn take_type_deltas_gives_the_paths_inserted_and_freed_since_the_last_take() {
let mut executor = DynamicExecutor::default();
let held = [executor.insert(source_network(0)).unwrap(), executor.insert(source_network(1)).unwrap()];
assert_eq!(changed_paths(&mut executor), Some([vec![0, 1], vec![]]));
assert_eq!(changed_paths(&mut executor), None);
drop(held);
executor.insert(source_network(2)).unwrap();
assert_eq!(changed_paths(&mut executor), Some([vec![2], vec![0, 1]]));
}
#[test]
fn a_path_freed_and_inserted_again_between_two_takes_is_given_with_its_types() {
let mut executor = DynamicExecutor::default();
executor.insert(source_network(0)).unwrap();
executor.take_type_deltas();
executor.insert(source_network(1)).unwrap();
executor.insert(source_network(0)).unwrap();
let path: Path = [NodeId(0)].into();
let types = executor.tree().source_map()[&path].1.clone();
assert_eq!(executor.take_type_deltas().unwrap().add, [(path, types)]);
}
#[test]
fn a_path_typed_before_a_type_error_is_given() {
let mut executor = DynamicExecutor::default();
executor.insert(bounding_box_network(TaggedValue::Number(1.))).unwrap_err();
assert_eq!(changed_paths(&mut executor), Some([vec![0], vec![]]));
}
#[test]
fn replace_frees_what_only_the_replaced_output_reached() {
let mut executor = DynamicExecutor::default();
let replaced = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
executor.replace(replaced, source_network(2)).unwrap();
for node in [NodeId(0), NodeId(1)] {
assert!(executor.tree().get(node).is_none());
assert!(executor.typing_context.type_of(node).is_none());
}
let delta = executor.take_type_deltas().unwrap();
let mut removed: Vec<_> = delta.remove.iter().map(|path| path.to_vec()).collect();
removed.sort();
assert_eq!(removed, [vec![NodeId(0)], vec![NodeId(1)]]);
assert_eq!(executor.tree().source_map().keys().map(|path| path.to_vec()).collect::<Vec<_>>(), [vec![NodeId(2)]]);
}
#[test]
fn replace_keeps_what_the_new_network_or_another_output_still_reaches() {
let content = TaggedValue::TypeDefault(item!(Vector));
let value_network = |(output, node)| ProtoNetwork {
inputs: vec![],
output,
nodes: vec![(output, node)],
};
let mut executor = DynamicExecutor::default();
let _document = executor.insert(value_network(value_node(0, content.clone()))).unwrap();
let replaced = executor.insert(offset_points_network(content)).unwrap();
executor.replace(replaced, value_network(value_node(1, TaggedValue::Number(10.)))).unwrap();
assert_eq!([0, 1, 2, 3].map(|node| executor.tree().get(NodeId(node)).is_some()), [true, true, false, false]);
}
#[test]
fn replace_frees_nothing_while_the_replaced_handle_is_held_elsewhere() {
let mut executor = DynamicExecutor::default();
let held = executor.insert(source_network(0)).unwrap();
executor.replace(held.clone(), source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test]
fn repeated_replacing_keeps_the_node_count_and_the_source_map_size_constant() {
let mut executor = DynamicExecutor::default();
let mut output = executor.insert(source_network(0)).unwrap();
for node in 1..=4 {
output = executor.replace(output, source_network(node)).unwrap();
assert_eq!([executor.tree().nodes.len(), executor.tree().source_map().len()], [1, 1]);
} }
} }
+1 -1
View File
@@ -49,6 +49,6 @@ mod tests {
let compiler = Compiler {}; let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated").network; let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err(); let _exec = DynamicExecutor::default().insert(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
} }
} }
@@ -155,14 +155,24 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
) )
}; };
} }
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
// which the new compiler selects by signature
macro_rules! also_under_own_identifier {
($module:ident, $row:expr) => {{
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
[row, own]
}};
}
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical // A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into` // ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
macro_rules! input_adapter_row { macro_rules! input_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => { (node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
@@ -254,7 +264,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new(); let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$( $(
entries.extend(input_adapter_node!(element: $element)); entries.extend(input_adapter_node!(element: $element));
entries.push(item_to_list_node!(element: $element)); entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
)* )*
entries entries
}}; }};
@@ -359,9 +369,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type // Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows { macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{ ($($element:ty),* $(,)?) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)* $(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
]; ]
.concat();
entries entries
}}; }};
} }
@@ -394,8 +405,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
($($element:ty),* $(,)?) => {{ ($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new(); let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$( $(
entries.push(bundle_node!(element: $element)); entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
entries.push(unbundle_node!(element: $element)); entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
)* )*
entries entries
}}; }};
@@ -455,10 +466,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element. // Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
macro_rules! embed_adapter_row { macro_rules! embed_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
} }
@@ -475,10 +487,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express // The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
macro_rules! convert_adapter_node { macro_rules! convert_adapter_node {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
} }
@@ -500,13 +513,19 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value // The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
macro_rules! attribute_value_node { macro_rules! attribute_value_node {
(Item<$element:ty>) => { (Item<$element:ty>) => {
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn) also_under_own_identifier!(
item_to_attribute_value,
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
}; };
(List<$element:ty>) => { (List<$element:ty>) => {
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn) also_under_own_identifier!(
list_to_attribute_value,
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
}; };
} }
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
attribute_value_node!(Item<f64>), attribute_value_node!(Item<f64>),
attribute_value_node!(Item<i64>), attribute_value_node!(Item<i64>),
attribute_value_node!(Item<bool>), attribute_value_node!(Item<bool>),
@@ -531,7 +550,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(List<Raster<GPU>>), attribute_value_node!(List<Raster<GPU>>),
attribute_value_node!(List<Graphic>), attribute_value_node!(List<Graphic>),
attribute_value_node!(List<Artboard>), attribute_value_node!(List<Artboard>),
]; ]
.concat();
node_types.extend(attribute_value_rows); node_types.extend(attribute_value_rows);
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item // Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
macro_rules! transform_list_node { macro_rules! transform_list_node {
+116 -25
View File
@@ -72,31 +72,32 @@ impl BlendMode {
] ]
} }
/// The subset of [`BlendMode::list()`] that is supported by SVG.
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
use BlendMode::*;
[
// Normal group
&[Normal],
// Darken group
&[Darken, Multiply, ColorBurn],
// Lighten group
&[Lighten, Screen, ColorDodge],
// Contrast group
&[Overlay, SoftLight, HardLight],
// Inversion group
&[Difference, Exclusion],
// Component group
&[Hue, Saturation, Color, Luminosity],
]
}
pub fn index_in_list(&self) -> Option<usize> { pub fn index_in_list(&self) -> Option<usize> {
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self) Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
} }
pub fn index_in_list_svg_subset(&self) -> Option<usize> { /// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self) /// The alpha-only utility modes, hidden from the list, draw layers normally.
pub fn reads_backdrop(&self) -> bool {
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
}
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
pub fn strength_moves_toward_neutral(&self) -> bool {
use BlendMode::*;
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
}
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
self.strength_moves_toward_neutral()
}
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
} }
/// Convert the enum to the CSS string for the blend mode. /// Convert the enum to the CSS string for the blend mode.
@@ -130,11 +131,14 @@ impl BlendMode {
} }
/// Renders the blend mode CSS style declaration. /// Renders the blend mode CSS style declaration.
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
pub fn render(&self) -> String { pub fn render(&self) -> String {
format!( format!(
r#" mix-blend-mode: {};"#, r#" mix-blend-mode: {};"#,
self.to_svg_style_name().unwrap_or_else(|| { self.to_svg_style_name().unwrap_or_else(|| {
log::warn!("Unsupported blend mode {self:?}"); if !self.reads_backdrop() {
log::warn!("Unsupported blend mode {self:?}");
}
"normal" "normal"
}) })
) )
@@ -156,7 +160,7 @@ impl Display for BlendMode {
BlendMode::Lighten => write!(f, "Lighten"), BlendMode::Lighten => write!(f, "Lighten"),
BlendMode::Screen => write!(f, "Screen"), BlendMode::Screen => write!(f, "Screen"),
BlendMode::ColorDodge => write!(f, "Color Dodge"), BlendMode::ColorDodge => write!(f, "Color Dodge"),
BlendMode::LinearDodge => write!(f, "Linear Dodge"), BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
BlendMode::LighterColor => write!(f, "Lighter Color"), BlendMode::LighterColor => write!(f, "Lighter Color"),
// Contrast group // Contrast group
BlendMode::Overlay => write!(f, "Overlay"), BlendMode::Overlay => write!(f, "Overlay"),
@@ -247,6 +251,30 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
} }
} }
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
}
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
let toward = |neutral: f32| {
let moved = |channel: f32| neutral + strength * (channel - neutral);
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
};
match blend_mode {
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
_ => apply_blend_mode(foreground, background, blend_mode),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -261,9 +289,13 @@ mod tests {
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}"); assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
} }
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source // Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
// Divide also turns any other white under a black source.
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
}
for source in [1., 1. - 1e-7, 1. + 2e-7] { for source in [1., 1. - 1e-7, 1. + 2e-7] {
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}"); assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
} }
for backdrop in [0., 1e-7, -1e-7] { for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}"); assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
@@ -339,6 +371,65 @@ mod tests {
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a()); assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
} }
#[test]
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
// Where the lumas tie, the backdrop stays, with the paint's alpha
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
}
#[test]
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
// At full strength, white past a sum of 1 and black short of it, even a level away
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
let half = hard_mix(backdrop, source, 128. / 255.);
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
}
}
#[test]
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
// The modes whose strength fades their blend take the paint as it is
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
assert_eq!(reading.len(), 10);
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
assert!(!BlendMode::Erase.reads_backdrop());
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
}
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
}
#[test] #[test]
fn source_over_weights_straight_colors_by_alpha() { fn source_over_weights_straight_colors_by_alpha() {
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5); let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
@@ -633,14 +633,20 @@ impl Color {
c_b + c_s - 1. c_b + c_s - 1.
} }
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha. /// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
#[inline(always)] #[inline(always)]
pub fn blend_darker_color(&self, other: Color) -> Color { pub fn blend_darker_color(&self, other: Color) -> Color {
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other }; let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
darker.with_alpha(other.alpha) darker.with_alpha(other.alpha)
} }
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
#[inline(always)]
fn blend_luma(&self) -> f32 {
luma_rec_601_rounded(self.red, self.green, self.blue)
}
/// Per-channel "Screen" blend. /// Per-channel "Screen" blend.
#[inline(always)] #[inline(always)]
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 { pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
@@ -653,10 +659,16 @@ impl Color {
c_s.max(c_b) c_s.max(c_b)
} }
/// Per-channel "Color Dodge" blend. /// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
#[inline(always)] #[inline(always)]
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 { pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) } if c_b.abs() <= BLEND_EDGE_TOLERANCE {
0.
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
1.
} else {
(c_b / (1. - c_s)).min(1.)
}
} }
/// Per-channel "Linear Dodge" (Add) blend. /// Per-channel "Linear Dodge" (Add) blend.
@@ -665,10 +677,10 @@ impl Color {
c_b + c_s c_b + c_s
} }
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha. /// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
#[inline(always)] #[inline(always)]
pub fn blend_lighter_color(&self, other: Color) -> Color { pub fn blend_lighter_color(&self, other: Color) -> Color {
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other }; let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
lighter.with_alpha(other.alpha) lighter.with_alpha(other.alpha)
} }
@@ -724,9 +736,15 @@ impl Color {
} }
} }
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5. /// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 { pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. } Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
}
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
(c_b - steepness * (1. - c_s)) / (1. - steepness)
} }
/// Per-channel "Difference" blend. /// Per-channel "Difference" blend.
+4 -4
View File
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
pub use graphene_hash; pub use graphene_hash;
pub use graphene_hash::CacheHash; pub use graphene_hash::CacheHash;
pub use list::{ pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
ATTR_TYPE, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
}; };
pub use memo::MemoHash; pub use memo::MemoHash;
pub use num_traits; pub use num_traits;
@@ -40,6 +40,9 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position /// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future. /// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame"; pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
/// Each row's transform maps the unit square onto that node's area in this item's local space.
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes). /// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
pub const ATTR_START: &str = "start"; pub const ATTR_START: &str = "start";
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes). /// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
@@ -29,6 +29,18 @@ pub struct NodeFlags {
pub forwards_input: bool, pub forwards_input: bool,
pub inject_scope: bool, pub inject_scope: bool,
pub asynchronous: bool, pub asynchronous: bool,
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
pub adapter: Option<AdapterKind>,
pub transient: bool,
}
/// How an adapter node changes the wire it is inserted on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdapterKind {
/// Converts the wire's element into another element type.
Conversion,
/// Changes the wire's rank, like raising an `Item` onto a `List`.
Rank,
} }
// Translation struct between macro and definition // Translation struct between macro and definition
+135 -25
View File
@@ -113,7 +113,36 @@ impl RuntimeInner {
} }
} }
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>); pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
struct SlotTable<T> {
slots: HashMap<u64, Slot<T>>,
/// The number of started evaluations, which orders them.
started: u64,
/// The value of the latest started evaluation that has landed, with its order.
latest: Option<(u64, T)>,
}
impl<T: Clone> SlotTable<T> {
fn start(&mut self) -> u64 {
self.started += 1;
self.started
}
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
if !superseded && let Some(value) = state.clone().value() {
self.latest = Some((order, value));
}
self.slots.insert(key, Slot::Ready(state));
}
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
}
}
enum Slot<T> { enum Slot<T> {
Ready(Poll<T>), Ready(Poll<T>),
@@ -130,7 +159,11 @@ impl<T> Drop for Slot<T> {
impl<T> Default for Slots<T> { impl<T> Default for Slots<T> {
fn default() -> Self { fn default() -> Self {
Self(Arc::default()) Self(Arc::new(Mutex::new(SlotTable {
slots: HashMap::new(),
started: 0,
latest: None,
})))
} }
} }
@@ -147,42 +180,46 @@ impl<T> std::fmt::Debug for Slots<T> {
} }
impl<T: Clone + WasmNotSend + 'static> Slots<T> { impl<T: Clone + WasmNotSend + 'static> Slots<T> {
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T> /// The landed state for `key`, or else starts its evaluation and returns its stand-in.
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
where where
F: Future<Output = Poll<T>> + WasmNotSend + 'static, F: Future<Output = Poll<T>> + WasmNotSend + 'static,
{ {
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { let order = {
Some(Slot::Ready(landed)) => return landed.clone(), let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial), match table.slots.get(&key) {
None => {} Some(Slot::Ready(landed)) => return landed.clone(),
} Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
None => table.start(),
}
};
// Fast path for futures that are ready immediately // Fast path for futures that are ready immediately
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd // TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
let mut future = Box::pin(future()); let mut future = Box::pin(future());
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) { if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone())); self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
return state; return state;
} }
let (handle, registration) = AbortHandle::new_pair(); let (handle, registration) = AbortHandle::new_pair();
let slots = Arc::downgrade(&self.0); let table = Arc::downgrade(&self.0);
runtime.spawn( runtime.spawn(
source, source,
Box::pin(async move { Box::pin(async move {
if let Ok(state) = Abortable::new(future, registration).await if let Ok(state) = Abortable::new(future, registration).await
&& let Some(slots) = slots.upgrade() && let Some(table) = table.upgrade()
{ {
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state)); table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
} }
}), }),
); );
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner); let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match slots.get(&key) { match table.slots.get(&key) {
Some(Slot::Ready(landed)) => landed.clone(), Some(Slot::Ready(landed)) => landed.clone(),
_ => { _ => {
slots.insert(key, Slot::Pending(handle)); table.slots.insert(key, Slot::Pending(handle));
placeholder.map_or(Poll::Pending, Poll::Partial) table.stand_in(placeholder, keep_previous)
} }
} }
} }
@@ -215,6 +252,13 @@ mod tests {
} }
count count
} }
fn drain_newest_first(&self) {
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
for mut task in tasks.into_iter().rev() {
while !poll_once(&mut task) {}
}
}
} }
struct BlockingSpawner; struct BlockingSpawner;
@@ -276,7 +320,7 @@ mod tests {
runtime.update_sources(&[SOURCE]); runtime.update_sources(&[SOURCE]);
let slots = Slots::default(); let slots = Slots::default();
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1)); assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(spawner.drain(), 0); assert_eq!(spawner.drain(), 0);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
@@ -297,11 +341,77 @@ mod tests {
Poll::Final(42u32) Poll::Final(42u32)
}; };
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0)); assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice"); assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42)); assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1)); assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
}
#[test]
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
assert_eq!(
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
Poll::Partial(0),
"nothing landed yet, so the placeholder stands in"
);
spawner.drain();
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
spawner.drain();
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
}
#[test]
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
spawner.drain_newest_first();
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
}
#[test]
fn a_fallback_response_stands_in_as_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
YieldOnce(false).await;
Poll::fallback(1, "failed")
});
spawner.drain();
let fetch = || async {
YieldOnce(false).await;
Poll::Final(2)
};
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
} }
#[test] #[test]
@@ -314,7 +424,7 @@ mod tests {
Poll::Final(42u32) Poll::Final(42u32)
}; };
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42)); assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]); assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
} }
@@ -328,11 +438,11 @@ mod tests {
Poll::Final(42u32) Poll::Final(42u32)
}; };
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
let clone = slots.clone(); let clone = slots.clone();
drop(slots); drop(slots);
assert_eq!(spawner.drain(), 1); assert_eq!(spawner.drain(), 1);
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42)); assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
} }
#[test] #[test]
@@ -350,7 +460,7 @@ mod tests {
} }
}; };
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
drop(slots); drop(slots);
assert_eq!(spawner.drain(), 1); assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed)); assert!(!finished.load(Ordering::Relaxed));
@@ -74,10 +74,14 @@ pub struct EffectLayers {
impl EffectLayers { impl EffectLayers {
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask. /// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
/// Content in a mode CSS lacks is drawn normally, so it's planned that way. /// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self { pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
let operations: Vec<EffectOperation> = effects.operations().collect(); let operations: Vec<EffectOperation> = effects.operations().collect();
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal }; let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
blend_mode
} else {
BlendMode::Normal
};
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer. // Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any. // A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
@@ -226,9 +230,20 @@ impl EffectLayers {
planned planned
} }
/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content. /// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
pub fn reads_backdrop(&self) -> bool { pub fn reads_backdrop(&self) -> bool {
self.fades_by_underlying || self.reads_around_backdrop() self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
}
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
let Some(content_layer) = self.content_layer() else { return false };
let blend_mode = self.layers[content_layer].blend_mode;
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
} }
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself. /// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
@@ -298,20 +313,30 @@ impl EffectLayers {
} }
} }
/// Whether any of the effects reads what lies beneath the content, like a background blur. /// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
pub fn effects_read_backdrop(effects: &Effects) -> bool { pub fn effects_read_backdrop(effects: &Effects) -> bool {
effects.operations().any(|operation| match &operation { effects.operations().any(|operation| match &operation {
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(), EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(), EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
_ => false, _ => {
!operation.changes_nothing()
&& pieces(0, &operation)
.iter()
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
}
}) })
} }
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image. /// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer, /// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves. /// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool { fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within); let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
_ if blend_mode.to_svg_style_name().is_some() => true,
PiecePlace::Beneath => blend_mode.reads_backdrop(),
PiecePlace::Within => blend_into_content,
_ => false,
};
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in) !is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
} }
@@ -467,7 +492,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
| EffectOperation::MinimumMaximum { .. } | EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. } | EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. } | EffectOperation::HighPass { .. }
| EffectOperation::AddNoise { .. } | EffectOperation::Speckle { .. }
| EffectOperation::Dissolve { .. } | EffectOperation::Dissolve { .. }
| EffectOperation::BlendIf(_) | EffectOperation::BlendIf(_)
| EffectOperation::Adjustment(_) => Vec::new(), | EffectOperation::Adjustment(_) => Vec::new(),
@@ -562,9 +587,11 @@ mod tests {
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true); let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]); assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too // Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true); let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]); assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]); let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0); assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2); assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
@@ -647,14 +674,11 @@ mod tests {
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]); assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
// One flattened for a mode CSS lacks covers it too // One flattened before an interior piece in a mode CSS lacks covers it too
let mut flattened_shadow = with_knockout(false); let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow { let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
*blend_mode = BlendMode::LinearBurn; assert_eq!(layers.flattened, 2);
} assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 1);
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
} }
#[test] #[test]
@@ -761,9 +785,14 @@ mod tests {
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2)); assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5)); assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]); let unmerged = Effects::from_operations([
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true); drop_shadow(RED, BlendMode::Multiply),
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3)); inner_shadow(RED, BlendMode::LinearBurn),
drop_shadow(RED, BlendMode::Multiply),
mask(),
]);
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
} }
#[test] #[test]
@@ -780,19 +809,23 @@ mod tests {
assert_eq!(layers.flattened, 2); assert_eq!(layers.flattened, 2);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]); assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]); // An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2); assert_eq!(layers.flattened, 2);
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
assert!(layers.reads_backdrop());
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens // A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]); let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2); assert_eq!(layers.flattened, 3);
assert_eq!(modes(&layers), [BlendMode::Normal]); assert_eq!(modes(&layers), [BlendMode::Normal]);
// Clipped content flattens everything // Clipped content flattens everything
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
assert_eq!(layers.flattened, 2); assert_eq!(layers.flattened, 3);
assert_eq!(parts(&layers), [[None]]); assert_eq!(parts(&layers), [[None]]);
} }
@@ -65,7 +65,7 @@ pub enum EffectKind {
/// Keeps how much each pixel differs from a blur of those around it, around middle gray. /// Keeps how much each pixel differs from a blur of those around it, around middle gray.
HighPass, HighPass,
/// Scatters random offsets across the colors, fixed in place on the content. /// Scatters random offsets across the colors, fixed in place on the content.
AddNoise, Speckle,
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque. /// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
Dissolve, Dissolve,
/// Smears the content along a line, as if it moved while being captured. /// Smears the content along a line, as if it moved while being captured.
@@ -139,7 +139,7 @@ impl std::fmt::Display for EffectKind {
Self::MinimumMaximum => "Minimum/Maximum", Self::MinimumMaximum => "Minimum/Maximum",
Self::Sharpen => "Sharpen", Self::Sharpen => "Sharpen",
Self::HighPass => "High Pass", Self::HighPass => "High Pass",
Self::AddNoise => "Add Noise", Self::Speckle => "Speckle",
Self::Dissolve => "Dissolve", Self::Dissolve => "Dissolve",
Self::MotionBlur => "Motion Blur", Self::MotionBlur => "Motion Blur",
Self::RadialBlur => "Radial Blur", Self::RadialBlur => "Radial Blur",
@@ -1099,7 +1099,7 @@ pub enum EffectOperation {
HighPass { HighPass {
radius: f64, radius: f64,
}, },
AddNoise { Speckle {
/// Percent of full brightness. /// Percent of full brightness.
amount: f64, amount: f64,
distribution: NoiseDistribution, distribution: NoiseDistribution,
@@ -1289,7 +1289,7 @@ impl EffectOperation {
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum, Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
Self::Sharpen { .. } => EffectKind::Sharpen, Self::Sharpen { .. } => EffectKind::Sharpen,
Self::HighPass { .. } => EffectKind::HighPass, Self::HighPass { .. } => EffectKind::HighPass,
Self::AddNoise { .. } => EffectKind::AddNoise, Self::Speckle { .. } => EffectKind::Speckle,
Self::Dissolve { .. } => EffectKind::Dissolve, Self::Dissolve { .. } => EffectKind::Dissolve,
Self::MotionBlur { .. } => EffectKind::MotionBlur, Self::MotionBlur { .. } => EffectKind::MotionBlur,
Self::RadialBlur { .. } => EffectKind::RadialBlur, Self::RadialBlur { .. } => EffectKind::RadialBlur,
@@ -1383,7 +1383,7 @@ impl EffectOperation {
Self::Feather { distance } => *distance <= 0., Self::Feather { distance } => *distance <= 0.,
Self::ConvolutionKernel { .. } => self.convolution().is_none(), Self::ConvolutionKernel { .. } => self.convolution().is_none(),
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false, Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
Self::AddNoise { amount, .. } => *amount <= 0., Self::Speckle { amount, .. } => *amount <= 0.,
// The four neighbors lie a fixed distance away, so only the blur needs a radius // The four neighbors lie a fixed distance away, so only the blur needs a radius
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.), Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
Self::MinimumMaximum { radius, .. } => *radius <= 0., Self::MinimumMaximum { radius, .. } => *radius <= 0.,
@@ -1423,7 +1423,7 @@ impl EffectOperation {
| Self::Outline { .. } | Self::Outline { .. }
| Self::BevelAndEmboss { .. } | Self::BevelAndEmboss { .. }
| Self::Feather { .. } => false, | Self::Feather { .. } => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false, Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
} }
} }
@@ -1491,7 +1491,7 @@ impl EffectOperation {
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1., Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds // Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0., Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0., Self::PaintOverlay { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
} }
} }
@@ -1578,7 +1578,7 @@ impl EffectOperation {
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite), Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius), Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite), Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
Self::AddNoise { amount, .. } => finite(amount), Self::Speckle { amount, .. } => finite(amount),
Self::Dissolve { opacity, .. } => finite(opacity), Self::Dissolve { opacity, .. } => finite(opacity),
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite), Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
Self::RadialBlur { amount, transform, .. } => { Self::RadialBlur { amount, transform, .. } => {
@@ -1754,7 +1754,7 @@ impl EffectOperation {
edges_only: false, edges_only: false,
}, },
EffectKind::HighPass => Self::HighPass { radius: 0. }, EffectKind::HighPass => Self::HighPass { radius: 0. },
EffectKind::AddNoise => Self::AddNoise { EffectKind::Speckle => Self::Speckle {
amount: 0., amount: 0.,
distribution: NoiseDistribution::default(), distribution: NoiseDistribution::default(),
monochromatic: false, monochromatic: false,
@@ -2100,7 +2100,7 @@ impl EffectOperation {
visitor.parameter("edges_only", edges_only, false); visitor.parameter("edges_only", edges_only, false);
} }
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.), Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
Self::AddNoise { Self::Speckle {
amount, amount,
distribution, distribution,
monochromatic, monochromatic,
@@ -2404,7 +2404,7 @@ mod tests {
threshold: 0., threshold: 0.,
edges_only: true, edges_only: true,
}, },
EffectOperation::AddNoise { EffectOperation::Speckle {
amount: 40., amount: 40.,
distribution: NoiseDistribution::Gaussian, distribution: NoiseDistribution::Gaussian,
monochromatic: true, monochromatic: true,
@@ -166,7 +166,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
| EffectOperation::MinimumMaximum { .. } | EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. } | EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. } | EffectOperation::HighPass { .. }
| EffectOperation::AddNoise { .. } | EffectOperation::Speckle { .. }
| EffectOperation::Dissolve { .. } | EffectOperation::Dissolve { .. }
) )
} }
@@ -178,7 +178,7 @@ pub fn reads_neighbors(operation: &EffectOperation) -> bool {
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other. /// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
pub fn is_random_field_filter(operation: &EffectOperation) -> bool { pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
matches!(operation, EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }) matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
} }
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view. /// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
@@ -277,7 +277,7 @@ pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
shifts shifts
} }
/// How the random offsets Add Noise gives the colors are spread. /// How the random offsets Speckle gives the colors are spread.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] #[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
@@ -296,7 +296,7 @@ pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated. /// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RandomField { pub enum RandomField {
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value. /// Speckle's offset for each color, or for Gaussian noise its first uniform value.
NoiseOffsets, NoiseOffsets,
/// Gaussian noise's second uniform value for each color, its angle. /// Gaussian noise's second uniform value for each color, its angle.
NoiseAngles, NoiseAngles,
@@ -320,7 +320,7 @@ impl RandomField {
} }
} }
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway. /// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 { pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
let deviations = match distribution { let deviations = match distribution {
NoiseDistribution::Uniform => 1., NoiseDistribution::Uniform => 1.,
@@ -1743,7 +1743,7 @@ impl EffectOperation {
| Self::MinimumMaximum { .. } | Self::MinimumMaximum { .. }
| Self::Sharpen { .. } | Self::Sharpen { .. }
| Self::HighPass { .. } | Self::HighPass { .. }
| Self::AddNoise { .. } | Self::Speckle { .. }
| Self::Dissolve { .. } | Self::Dissolve { .. }
| Self::BackgroundBlur { .. } | Self::BackgroundBlur { .. }
| Self::BlendIf(_) | Self::BlendIf(_)
@@ -27,12 +27,12 @@ pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation:
match *operation { match *operation {
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels), EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels), EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
EffectOperation::AddNoise { EffectOperation::Speckle {
amount, amount,
distribution, distribution,
monochromatic, monochromatic,
seed, seed,
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect), } => speckle(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect), EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
_ => plane, _ => plane,
} }
@@ -511,7 +511,7 @@ fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDist
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped. /// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel). /// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> { pub fn speckle(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
let sampling = FieldSampling::new(pixels_to_effect); let sampling = FieldSampling::new(pixels_to_effect);
let extent = noise_extent(amount, distribution) as f32; let extent = noise_extent(amount, distribution) as f32;
let scale = (amount * sampling.deviation_scale) as f32; let scale = (amount * sampling.deviation_scale) as f32;
@@ -849,7 +849,7 @@ mod tests {
let amount = 0.2; let amount = 0.2;
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3 // Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY); let uniform = speckle(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
let (mean, deviation, correlation) = offset_statistics(&uniform); let (mean, deviation, correlation) = offset_statistics(&uniform);
for channel in 0..3 { for channel in 0..3 {
assert!( assert!(
@@ -861,21 +861,21 @@ mod tests {
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.)); assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
// Gaussian noise deviates by the amount, cut off at its limit // Gaussian noise deviates by the amount, cut off at its limit
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY); let gaussian = speckle(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
let (_, deviation, _) = offset_statistics(&gaussian); let (_, deviation, _) = offset_statistics(&gaussian);
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}"); assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise // Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY); let monochromatic = speckle(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY); let reseeded = speckle(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
assert_ne!(reseeded.data[..64], uniform.data[..64]); assert_ne!(reseeded.data[..64], uniform.data[..64]);
} }
#[test] #[test]
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() { fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]); let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect); let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| speckle(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
// A plane placed three cells right and five down holds the same noise at the same cells // A plane placed three cells right and five down holds the same noise at the same cells
let placed = noise(&gray(16), DAffine2::IDENTITY); let placed = noise(&gray(16), DAffine2::IDENTITY);
@@ -1,8 +1,10 @@
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend. //! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
//! The modes CSS lacks blend normally, since layers only ever take the others. //! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
use crate::effect_kernels::Plane; use crate::effect_kernels::Plane;
use core_types::blending::BlendMode; use core_types::Color;
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
use core_types::color::BLEND_EDGE_TOLERANCE;
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height). /// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> { pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
@@ -11,6 +13,20 @@ pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode:
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop. /// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] { pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
}
/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop
/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it.
pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] {
match blend_mode.fill_moves_layer_toward_neutral() {
true => blend_pixel_at_strength(content, backdrop, blend_mode, fill),
false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode),
}
}
/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives.
fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] {
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]); let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
if source_alpha <= 0. { if source_alpha <= 0. {
return backdrop; return backdrop;
@@ -21,14 +37,18 @@ pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode)
false => [0.; 3], false => [0.; 3],
}; };
let (source_color, backdrop_color) = (straight(source), straight(backdrop)); let (source_color, backdrop_color) = (straight(source), straight(backdrop));
let blended = blend(backdrop_color, source_color, blend_mode); let blended = match strength < 1. {
true => blend_at_strength(backdrop_color, source_color, blend_mode, strength),
false => blend(backdrop_color, source_color, blend_mode),
};
let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength);
let mut result = [0.; 4]; let mut result = [0.; 4];
for channel in 0..3 { for channel in 0..3 {
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel]; let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel]; result[channel] = shown * mixed + (1. - shown) * backdrop[channel];
} }
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha); result[3] = shown + backdrop_alpha * (1. - shown);
result result
} }
@@ -39,10 +59,22 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)), BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
BlendMode::Color => set_luminosity(source, luminosity(backdrop)), BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)), BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode),
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)), _ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
} }
} }
/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]).
fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] {
if !blend_mode.strength_moves_toward_neutral() {
return blend(backdrop, source, blend_mode);
}
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength);
[blended.r(), blended.g(), blended.b()]
}
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own. /// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 { fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 { let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
@@ -56,8 +88,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
BlendMode::Overlay => hard_light(source, backdrop), BlendMode::Overlay => hard_light(source, backdrop),
BlendMode::Darken => backdrop.min(source), BlendMode::Darken => backdrop.min(source),
BlendMode::Lighten => backdrop.max(source), BlendMode::Lighten => backdrop.max(source),
BlendMode::ColorDodge if backdrop <= 0. => 0., BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
BlendMode::ColorDodge if source >= 1. => 1., BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.), BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
BlendMode::ColorBurn if backdrop >= 1. => 1., BlendMode::ColorBurn if backdrop >= 1. => 1.,
BlendMode::ColorBurn if source <= 0. => 0., BlendMode::ColorBurn if source <= 0. => 0.,
@@ -142,6 +174,195 @@ mod tests {
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6); assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
} }
/// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors.
fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] {
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
let color_burn = |b: f32, s: f32| {
if b >= 1. {
1.
} else if s <= 0. {
0.
} else {
1. - ((1. - b) / s).min(1.)
}
};
let color_dodge = |b: f32, s: f32| {
if b <= 0. {
0.
} else if s >= 1. {
1.
} else {
(b / (1. - s)).min(1.)
}
};
let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.));
match blend_mode {
BlendMode::ColorBurn => channels(&color_burn),
BlendMode::ColorDodge => channels(&color_dodge),
BlendMode::LinearBurn => channels(&|b, s| b + s - 1.),
BlendMode::LinearDodge => channels(&|b, s| b + s),
BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }),
BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.),
BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }),
BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)),
BlendMode::Subtract => channels(&|b, s| b - s),
BlendMode::Divide => channels(&|b, s| {
if b <= 0. {
0.
} else if s <= 0. {
1.
} else {
b / s
}
}),
BlendMode::DarkerColor => {
if luma(source) < luma(backdrop) {
source
} else {
backdrop
}
}
BlendMode::LighterColor => {
if luma(source) > luma(backdrop) {
source
} else {
backdrop
}
}
_ => panic!("{blend_mode} blends natively"),
}
}
/// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties.
const PAIRS: [([f32; 3], [f32; 3]); 4] = [
([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]),
([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]),
([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]),
([0., 1., 0.3], [0.6, 0.15, 0.8]),
];
#[test]
fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() {
for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) {
for (backdrop, source) in PAIRS {
let expected = reference_formula(blend_mode, backdrop, source);
let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.];
// Over an opaque backdrop, the source takes the formula
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
assert!(
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
"{blend_mode}: {blended:?} rather than {expected:?}"
);
// Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do
let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5];
let blended = blend_pixel(opaque(source), half, blend_mode);
for channel in 0..3 {
let mixed = 0.5 * source[channel] + 0.5 * expected[channel];
assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}");
}
}
}
}
#[test]
fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() {
let fill = 0.5;
let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
for (backdrop, source) in PAIRS {
let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill);
let expected = match blend_mode {
// The paint at full strength once moved halfway toward black, white, or middle gray
BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)),
BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))),
BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))),
// A ramp a fill of half makes `clamp(2b - 1 + s)`
BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)),
// Halfway from the backdrop to the blend
_ => {
let full = reference_formula(blend_mode, backdrop, source);
[0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill)
}
};
assert!(
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
"{blend_mode}: {blended:?} rather than {expected:?}"
);
assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop");
}
}
// Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes
let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill);
assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}");
}
#[test]
fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() {
let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5);
let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha];
let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| {
source.map(|channel| match blend_mode {
BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel,
BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel),
_ => 0.5 + fill * (channel - 0.5),
})
};
let modes = [
BlendMode::ColorDodge,
BlendMode::ColorBurn,
BlendMode::LinearDodge,
BlendMode::LinearBurn,
BlendMode::VividLight,
BlendMode::LinearLight,
];
for blend_mode in modes {
for (backdrop, source) in PAIRS {
for alpha in [1., 0.5] {
for fill in [0., 0.3, 1.] {
// Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop
let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill));
let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]);
let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill);
assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}");
// Over nothing, the fill fades the content as it is
let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill);
assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}");
}
for backdrop_alpha in [0.25, 0.5, 0.75] {
let beneath = premultiplied(backdrop, backdrop_alpha);
// No fill leaves a partly covering backdrop as it is, alpha included
let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.);
assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}");
// A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers
let blend = reference_formula(blend_mode, backdrop, source);
let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]);
let expected = [0, 1, 2]
.map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel])
.into_iter()
.chain([alpha + (1. - alpha) * backdrop_alpha])
.collect::<Vec<f32>>();
let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.);
assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}");
}
}
}
}
// An opaque layer at no fill over half alpha leaves that alpha
let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.);
assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}");
}
#[test] #[test]
fn the_luminosity_of_black_over_any_gray_is_black() { fn the_luminosity_of_black_over_any_gray_is_black() {
for level in 0..=255 { for level in 0..=255 {
@@ -728,7 +728,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
| EffectOperation::MinimumMaximum { .. } | EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. } | EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. } | EffectOperation::HighPass { .. }
| EffectOperation::AddNoise { .. } | EffectOperation::Speckle { .. }
| EffectOperation::Dissolve { .. } => { | EffectOperation::Dissolve { .. } => {
merge_beneath(&mut full, &mut filled, &mut beneath); merge_beneath(&mut full, &mut filled, &mut beneath);
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result // A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result
@@ -1727,7 +1727,7 @@ mod tests {
#[test] #[test]
fn random_fields_move_and_scale_with_the_content_after_them() { fn random_fields_move_and_scale_with_the_content_after_them() {
let noise = EffectOperation::AddNoise { let noise = EffectOperation::Speckle {
amount: 30., amount: 30.,
distribution: graphic_types::NoiseDistribution::Uniform, distribution: graphic_types::NoiseDistribution::Uniform,
monochromatic: false, monochromatic: false,
@@ -4,6 +4,7 @@ pub mod render_ext;
mod renderer; mod renderer;
mod svg_backdrop; mod svg_backdrop;
mod svg_blend_if; mod svg_blend_if;
mod svg_layer_blend;
pub mod to_peniko; pub mod to_peniko;
pub mod vello_scene_builder; pub mod vello_scene_builder;
File diff suppressed because it is too large. Load diff
@@ -96,10 +96,10 @@ impl SvgFilterPrimitives {
match *operation { match *operation {
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives // The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)), EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image), EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum), EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either // Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }), EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }), EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
_ => image.to_string(), _ => image.to_string(),
} }
@@ -124,7 +124,7 @@ impl SvgFilterPrimitives {
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(), Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
None => matches!( None => matches!(
operation, operation,
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. }
), ),
} }
} }
@@ -275,9 +275,9 @@ impl SvgFilterPrimitives {
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "") self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
} }
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`. /// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `speckle`.
/// Until the map is resolved, its middle gray offsets nothing. /// Until the map is resolved, its middle gray offsets nothing.
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String { fn speckle(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
let colors = self.opaque_colors(image); let colors = self.opaque_colors(image);
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255))); let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent); let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
@@ -719,8 +719,8 @@ mod tests {
#[test] #[test]
fn random_fields_come_from_the_gpu_combined_with_the_live_content() { fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage // Speckle adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
let noise = EffectOperation::AddNoise { let noise = EffectOperation::Speckle {
amount: 40., amount: 40.,
distribution: NoiseDistribution::Uniform, distribution: NoiseDistribution::Uniform,
monochromatic: false, monochromatic: false,
@@ -760,13 +760,13 @@ mod tests {
use core_types::list::{ATTR_EFFECTS, List}; use core_types::list::{ATTR_EFFECTS, List};
use core_types::transform::Footprint; use core_types::transform::Footprint;
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it // A color with Speckle after Levels draws through a filter over the view, with the noise's map and the Levels within it
let levels = graphic_types::Adjustment::Exposure { let levels = graphic_types::Adjustment::Exposure {
exposure: 1., exposure: 1.,
offset: 0., offset: 0.,
gamma_correction: 1., gamma_correction: 1.,
}; };
let noise = EffectOperation::AddNoise { let noise = EffectOperation::Speckle {
amount: 20., amount: 20.,
distribution: NoiseDistribution::Uniform, distribution: NoiseDistribution::Uniform,
monochromatic: false, monochromatic: false,
@@ -800,7 +800,7 @@ mod tests {
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view // A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color }); let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let noise = EffectOperation::AddNoise { let noise = EffectOperation::Speckle {
amount: 20., amount: 20.,
distribution: NoiseDistribution::Uniform, distribution: NoiseDistribution::Uniform,
monochromatic: false, monochromatic: false,
@@ -134,17 +134,9 @@ impl SvgRender {
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does. /// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out. /// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
/// The image is embedded `for_mask`, which draws no canvas. /// The image is embedded `for_mask`, since a mask can't render canvases.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> { pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() { let root = self.backdrop_root()?;
return None;
}
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
if root == 0 && self.open_groups.clip {
return None;
}
// The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content // The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content
let root_group = &self.open_groups.groups[root]; let root_group = &self.open_groups.groups[root];
@@ -152,8 +144,9 @@ impl SvgRender {
let clip = root_group.clip_path.clone().zip(root_group.user_to_document); let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document); let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
// A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers // In the viewport, images draw to canvases in `<foreignObject>` elements, which a mask can't render, so a mask reads the GPU's image of what lies beneath instead, as later readers do
let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params)); let draws_canvases = self.draws_canvases_since(root, render_params);
let images = holds_backdrop || (for_mask && draws_canvases);
// An image needs the outline of the root's clip, if it has one, to cut what it holds by // An image needs the outline of the root's clip, if it has one, to cut what it holds by
let image_clip = match images && self.images_replace_markup(render_params) { let image_clip = match images && self.images_replace_markup(render_params) {
@@ -167,7 +160,7 @@ impl SvgRender {
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps // Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
let image = images && image_clip.is_some(); let image = images && image_clip.is_some();
let copies = match (images, image_clip) { let copies = match (images, image_clip) {
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false), (false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas() || draws_canvases, false),
(true, Some(clip)) => { (true, Some(clip)) => {
let image_params = RenderParams { let image_params = RenderParams {
embeds_images: render_params.embeds_images || for_mask, embeds_images: render_params.embeds_images || for_mask,
@@ -194,11 +187,42 @@ impl SvgRender {
Some(BackdropCopy { markup, image }) Some(BackdropCopy { markup, image })
} }
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root). /// The group isolating the content drawn next from what lies beneath it, its backdrop root, as an index of the open groups, or `None` if it reads nothing beneath.
fn backdrop_root(&self) -> Option<usize> {
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
return None;
}
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
(root > 0 || !self.open_groups.clip).then_some(root)
}
/// Whether anything is drawn beneath the content drawn next for [`Self::backdrop_copy`] to show, as markup it copies or content it has the GPU draw again.
/// O(segments drawn since the backdrop root).
pub(crate) fn draws_beneath(&self) -> bool {
let Some(root) = self.backdrop_root() else { return false };
(root..self.open_groups.groups.len()).any(|level| {
let group = &self.open_groups.groups[level];
let markup = &self.svg[group.content_start..self.level_content_end(level)];
let copied = group.user_to_document.is_some() && markup.iter().any(|segment| segment.as_str().contains('<'));
copied || group.drawn.iter().any(|drawn| drawn.count > 0)
})
}
/// Where the markup drawn directly inside the open group at `level` ends among the render's segments, at the tag of the group open inside it, if any.
fn level_content_end(&self, level: usize) -> usize {
self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start)
}
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
/// even where the content reading it embeds its own images. O(segments drawn since the root).
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool { fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
let start = self.open_groups.groups[root].content_start; let start = self.open_groups.groups[root].content_start;
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str()); let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas) in_viewport && self.svg[start..].iter().any(draws_canvas)
} }
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none. /// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
@@ -212,8 +236,7 @@ impl SvgRender {
let mut copies = Vec::new(); let mut copies = Vec::new();
for level in (root..=current).rev() { for level in (root..=current).rev() {
let group = &self.open_groups.groups[level]; let group = &self.open_groups.groups[level];
let start = group.content_start; let (start, end) = (group.content_start, self.level_content_end(level));
let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start);
let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<')); let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<'));
let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue }; let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue };
@@ -271,6 +294,7 @@ impl SvgRender {
} }
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]). /// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
#[derive(Clone)]
pub(crate) struct BackdropCopy { pub(crate) struct BackdropCopy {
pub markup: String, pub markup: String,
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn. /// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
@@ -49,7 +49,7 @@ pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full. /// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for. /// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
fn with_unreadable_covered(markup: &str, key: &str) -> String { pub(crate) fn with_unreadable_covered(markup: &str, key: &str) -> String {
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key) with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
} }
@@ -0,0 +1,571 @@
//! Layers in the blend modes `mix-blend-mode` lacks, or below a full fill moving them toward neutral in Color Dodge and Color Burn, built all natively from what SVG composites,
//! over a copy of what lies beneath (see [`SvgRender::backdrop_copy`]).
//! The layer's alpha, times [`layer_fill_shown`] where its fill moves it toward neutral, shows an opaque result: the layer made opaque, and over it the blend, shown by the alpha of what lies beneath,
//! as the W3C's general formula mixes them. The blend draws the layer, recolored and made opaque, over an opaque copy of what lies beneath, where `s` is the layer moved toward neutral by its fill:
//! - Linear Burn, Subtract: Lighten by `x`, then Difference by `x`, which leaves `max(0, b - x)` exactly, for `x` of `1 - s` or `s`.
//! - Linear Dodge: that over the inverted copy, inverted back. Linear Light: Linear Burn by `2s`, then Linear Dodge by `2s - 1`.
//! - Hard Mix: at full strength, the copy where it and the layer sum to white exactly, and white where they sum past it, each where Color Dodge reaches white.
//! Below it, Linear Burn by `q (1 - s)`, stretched by `1 / (1 - q)`.
//! - Divide: Color Dodge by the inverted layer. Pin Light: Darken by `2s`, then Lighten by `2s - 1`. Vivid Light: Color Burn by `2s`, then Color Dodge by `2s - 1`.
//! - Darker Color, Lighter Color: the layer over the copy, masked to where Luminosity moves the copy's color down (or up) by a level or more.
//! - Color Dodge, Color Burn: themselves by `s`.
use crate::renderer::{RenderParams, SvgRender, SvgSegment};
use crate::svg_backdrop::BackdropCopy;
use crate::svg_blend_if::with_unreadable_covered;
use core_types::blending::{BlendMode, layer_fill_shown};
use core_types::uuid::generate_uuid;
use glam::DVec2;
use std::fmt::Write;
/// A layer blending by a mode `mix-blend-mode` lacks, with what it reads to blend onto what lies beneath.
pub(crate) struct SvgLayerBlend {
blend_mode: BlendMode,
/// The copy of what lies beneath, taken before any of the item is drawn, or `None` with nothing beneath.
copy: Option<BackdropCopy>,
/// The region of the current user space the layer covers, which the blend's filters and masks cover too.
region: [DVec2; 2],
/// The fill moving the layer toward the mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), or 1 where the layer is faded by its fill already.
fill: f64,
}
impl SvgLayerBlend {
/// Copies what lies beneath the `region` of the current user space, before any of the layer is drawn, for it to blend onto by the mode.
pub(crate) fn new(render: &mut SvgRender, render_params: &RenderParams, blend_mode: BlendMode, region: [DVec2; 2], fill: f64) -> Self {
Self {
blend_mode,
copy: render.backdrop_copy(render_params, region, 0., true),
region,
fill,
}
}
/// The blend of another layer of the same item by its own `blend_mode` at full strength, onto the same copy of what lies beneath.
pub(crate) fn with_mode(&self, blend_mode: BlendMode) -> Self {
Self {
blend_mode,
copy: self.copy.clone(),
region: self.region,
fill: 1.,
}
}
/// Whether the layer blends onto what lies beneath, rather than over nothing.
pub(crate) fn blends(&self) -> bool {
self.copy.is_some() && recipe(self.blend_mode, self.fill).is_some()
}
/// Whether the blend moves the layer toward the mode's neutral color by a fill below full, which the layer itself then leaves out.
pub(crate) fn moves_by_fill(&self) -> bool {
self.fill < 1.
}
}
/// A map of each straight color channel, `scale × channel + offset`, clamped to 0 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Recolor {
scale: f64,
offset: f64,
}
impl Recolor {
const IDENTITY: Self = Self { scale: 1., offset: 0. };
const INVERT: Self = Self { scale: -1., offset: 1. };
}
/// One step building a mode SVG lacks: the layer recolored and made opaque, then drawn by a native mode.
#[derive(Clone, Copy, Debug)]
struct BlendStep {
recolor: Recolor,
blend_mode: BlendMode,
}
/// A stage of steps over its base (the copy of what lies beneath, or the stage before), recolored, whose result it then recolors by `stretch`.
#[derive(Clone, Debug)]
struct BlendStage {
base: Recolor,
steps: Vec<BlendStep>,
stretch: Recolor,
}
/// How SVG builds a mode it lacks over an opaque copy of what lies beneath.
#[derive(Clone, Debug)]
enum BlendRecipe {
Stages(Vec<BlendStage>),
/// Hard Mix at full strength: the copy where it and the layer sum to white exactly, and white where they sum past it.
HardMixThreshold,
/// The layer's whole color where its luma is lower than that of what lies beneath, or higher if `lighter`.
Pick {
lighter: bool,
},
}
/// The recipe for a mode SVG lacks at the `fill` moving the layer's color toward neutral where the mode does that, or `None` for a mode SVG has at it.
fn recipe(blend_mode: BlendMode, fill: f64) -> Option<BlendRecipe> {
use BlendMode::*;
let step = |scale: f64, offset: f64, blend_mode: BlendMode| BlendStep {
recolor: Recolor { scale, offset },
blend_mode,
};
// Lightening by `x`, then the difference from it, leaves `max(0, b - x)` in whole levels
let burn_by = |scale: f64, offset: f64| vec![step(scale, offset, Lighten), step(scale, offset, Difference)];
let stage = |base: Recolor, steps: Vec<BlendStep>, stretch: Recolor| BlendStage { base, steps, stretch };
let (identity, invert) = (Recolor::IDENTITY, Recolor::INVERT);
let steepness = 255. * fill / 256.;
let stages = match blend_mode {
LinearBurn => vec![stage(identity, burn_by(-fill, fill), identity)],
Subtract => vec![stage(identity, burn_by(1., 0.), identity)],
LinearDodge => vec![stage(invert, burn_by(fill, 0.), invert)],
LinearLight => vec![stage(identity, burn_by(-2. * fill, fill), identity), stage(invert, burn_by(2. * fill, -fill), invert)],
HardMix if fill >= 1. => return Some(BlendRecipe::HardMixThreshold),
HardMix => vec![stage(
identity,
burn_by(-steepness, steepness),
Recolor {
scale: 1. / (1. - steepness),
offset: 0.,
},
)],
Divide => vec![stage(identity, vec![step(-1., 1., ColorDodge)], identity)],
ColorDodge if fill < 1. => vec![stage(identity, vec![step(fill, 0., ColorDodge)], identity)],
ColorBurn if fill < 1. => vec![stage(identity, vec![step(fill, 1. - fill, ColorBurn)], identity)],
PinLight => vec![stage(identity, vec![step(2., 0., Darken), step(2., -1., Lighten)], identity)],
VividLight => vec![stage(identity, vec![step(2. * fill, 1. - fill, ColorBurn), step(2. * fill, -fill, ColorDodge)], identity)],
DarkerColor => return Some(BlendRecipe::Pick { lighter: false }),
LighterColor => return Some(BlendRecipe::Pick { lighter: true }),
_ => return None,
};
Some(BlendRecipe::Stages(stages))
}
/// The filters and masks one blended layer writes into the render's defs, each within the layer's region.
struct BlendDefs<'a> {
defs: &'a mut String,
region: String,
uuid: u64,
recolors: Vec<(Recolor, String)>,
}
impl BlendDefs<'_> {
/// Writes a def named `name` with the `tag`, the `attributes` past its ID, and the `children`, returning a reference to it.
fn write(&mut self, name: &str, tag: &str, attributes: &str, children: &str) -> String {
let id = format!("layer-blend-{name}-{}", self.uuid);
write!(self.defs, r#"<{tag} id="{id}" {attributes} {}>{children}</{tag}>"#, self.region).unwrap();
format!("url(#{id})")
}
/// A filter named `name` of the `primitives` on gamma-encoded colors.
fn filter(&mut self, name: &str, primitives: &str) -> String {
self.write(name, "filter", r#"filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB""#, primitives)
}
/// A mask named `name` showing what the `markup` covers, by its alpha.
fn mask(&mut self, name: &str, markup: &str) -> String {
self.write(name, "mask", r#"mask-type="alpha" maskUnits="userSpaceOnUse""#, markup)
}
/// A filter making what it draws opaque in its straight color, recolored, written once for each recoloring.
fn recolor(&mut self, recolor: Recolor) -> String {
if let Some((_, reference)) = self.recolors.iter().find(|(written, _)| *written == recolor) {
return reference.clone();
}
let Recolor { scale, offset } = recolor;
let name = format!("recolor-{}", self.recolors.len());
let reference = self.filter(
&name,
&format!(r#"<feColorMatrix type="matrix" values="{scale} 0 0 0 {offset} 0 {scale} 0 0 {offset} 0 0 {scale} 0 {offset} 0 0 0 0 1" />"#),
);
self.recolors.push((recolor, reference.clone()));
reference
}
}
/// What a blended layer draws around it, with its defs written.
struct BlendGroups {
/// The attributes of each group around the layer made opaque and the blend over it, outermost first.
around: Vec<Vec<(&'static str, String)>>,
/// The filter making the layer opaque, beneath the blend.
opaque: String,
/// The ID the layer's own group takes, for copies of it to reference.
layer_id: String,
/// The blend's markup, drawn over the layer made opaque, which copies of what lies beneath leave out so they never nest.
blended: String,
}
/// Writes the defs of the `blend` of a layer at `opacity` and returns what it draws around the layer, or `None` with nothing beneath to blend onto.
fn blend_groups(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32) -> Option<BlendGroups> {
let (Some(copy), Some(recipe)) = (&blend.copy, recipe(blend.blend_mode, blend.fill)) else {
return None;
};
let uuid = generate_uuid();
let layer_id = format!("layer-blend-layer-{uuid}");
let [min, max] = blend.region;
let mut defs = BlendDefs {
defs: &mut render.svg_defs,
region: format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y),
uuid,
recolors: Vec::new(),
};
// Copies of the layer reference it, and masks read what lies beneath from an image or a copy covering what they can't draw
let layer = format!(r##"<use href="#{layer_id}" />"##);
let beneath_in_mask = if copy.image { copy.markup.clone() } else { with_unreadable_covered(&copy.markup, "#000000") };
let opaque = defs.recolor(Recolor::IDENTITY);
let drawn = |filter: &str, blend_mode: BlendMode, markup: &str| format!(r#"<g filter="{filter}" style="{}">{markup}</g>"#, blend_mode.render().trim());
let blend_markup = match recipe {
// Each stage's steps blend over its base alone, within a group recoloring what they leave
BlendRecipe::Stages(stages) => {
let mut result = copy.markup.clone();
for stage in stages {
let base = format!(r#"<g filter="{}">{result}</g>"#, defs.recolor(stage.base));
let steps: String = stage.steps.iter().map(|step| drawn(&defs.recolor(step.recolor), step.blend_mode, &layer)).collect();
result = format!(r#"<g filter="{}">{base}{steps}</g>"#, defs.recolor(stage.stretch));
}
result
}
// Color Dodge reaches white exactly where the layer and the copy sum to white or past it, or past it alone for the layer a level darker
BlendRecipe::HardMixThreshold => {
let white = defs.filter("white", r#"<feComponentTransfer><feFuncR type="linear" slope="255" intercept="-254" /><feFuncG type="linear" slope="255" intercept="-254" /><feFuncB type="linear" slope="255" intercept="-254" /></feComponentTransfer>"#);
let mut reaches_white = |offset: f64| {
format!(
r#"<g filter="{opaque}">{}</g>{}"#,
copy.markup,
drawn(&defs.recolor(Recolor { scale: 1., offset }), BlendMode::ColorDodge, &layer)
)
};
let (sums_to_white, sums_past_white) = (reaches_white(0.), reaches_white(-1. / 255.));
format!(
r#"<g filter="{opaque}">{}</g><g filter="{white}" style="mix-blend-mode: multiply;">{sums_to_white}</g><g filter="{white}" style="mix-blend-mode: lighten;">{sums_past_white}</g>"#,
copy.markup
)
}
// Luminosity moves the copy's color by the layer's luma less its own, which the change in any channel shows the direction of
BlendRecipe::Pick { lighter } => {
let any_channel = defs.filter("any-channel", r#"<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0" />"#);
let toward = if lighter { BlendMode::Lighten } else { BlendMode::Darken };
let moved = format!(
r#"<g filter="{any_channel}"><g filter="{opaque}">{beneath_in_mask}</g>{}{}{}</g>"#,
drawn(&opaque, BlendMode::Luminosity, &layer),
drawn(&opaque, toward, &beneath_in_mask),
drawn(&opaque, BlendMode::Difference, &beneath_in_mask)
);
let picked = defs.mask("picked", &moved);
format!(r#"<g filter="{opaque}">{}</g><g filter="{opaque}" mask="{picked}">{layer}</g>"#, copy.markup)
}
};
// The blend shows by the alpha of what lies beneath, and the whole by the layer's own alpha, at its opacity
let beneath = defs.mask("beneath", &beneath_in_mask);
let blended = format!(r#"<g mask="{beneath}">{blend_markup}</g>"#);
let mut outer = vec![("mask", defs.mask("shown", &layer))];
if opacity < 1. {
outer.push(("opacity", opacity.to_string()));
}
let mut around = vec![outer];
// A fill moving the layer toward neutral shows it by how much lies beneath, by a table of each level of alpha there
if blend.fill < 1. {
let table: Vec<String> = (0..=255).map(|level| format!("{:.5}", layer_fill_shown(level as f32 / 255., blend.fill as f32))).collect();
let weight = defs.filter(
"fill-weight",
&format!(r#"<feComponentTransfer><feFuncA type="table" tableValues="{}" /></feComponentTransfer>"#, table.join(" ")),
);
around.push(vec![("mask", defs.mask("fill-shown", &format!(r#"<g filter="{weight}">{beneath_in_mask}</g>"#)))]);
}
Some(BlendGroups { around, opaque, layer_id, blended })
}
/// Draws the layer `draw_layer` draws, blended by the mode onto what lies beneath it and faded by `opacity`.
pub(crate) fn draw_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, draw_layer: impl FnOnce(&mut SvgRender)) {
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
let opacity = opacity as f64 * blend.fill;
return render.parent_tag(
"g",
|attributes| {
if opacity < 1. {
attributes.push("opacity", opacity.to_string());
}
},
draw_layer,
);
};
nest_groups(render, &around, |render| {
render.parent_tag(
"g",
|attributes| attributes.push("filter", opaque),
|render| render.parent_tag("g", |attributes| attributes.push("id", layer_id), draw_layer),
);
render.leaf_node(SvgSegment::Backdrop(blended));
});
}
/// Wraps the markup drawn since the segment at `start`, an image of the layer the GPU renders, in what [`draw_blended_layer`] draws around a layer. Returns whether it blends.
pub(crate) fn wrap_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, start: usize) -> bool {
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
return false;
};
let opening = |attributes: &Vec<(&'static str, String)>| format!("<g{}>", attributes.iter().map(|(name, value)| format!(r#" {name}="{value}""#)).collect::<String>());
let mut opened: String = around.iter().map(opening).collect();
write!(opened, r#"<g filter="{opaque}"><g id="{layer_id}">"#).unwrap();
render.svg.insert(start, opened.into());
render.svg.push("</g></g>".into());
render.svg.push(SvgSegment::Backdrop(blended));
render.svg.push("</g>".repeat(around.len()).into());
true
}
/// Opens a group of each of the `groups`' attributes, outermost first, around what `inner` draws.
fn nest_groups(render: &mut SvgRender, groups: &[Vec<(&'static str, String)>], inner: impl FnOnce(&mut SvgRender)) {
let Some((attributes, nested)) = groups.split_first() else { return inner(render) };
render.parent_tag(
"g",
|tag| attributes.iter().for_each(|(name, value)| tag.push(*name, value.clone())),
|render| nest_groups(render, nested, inner),
);
}
#[cfg(test)]
mod tests {
use super::*;
use raster_kernels::layer_blending::{blend_layer_pixel, blend_pixel};
/// The modes SVG builds from native compositing.
const MODES: [BlendMode; 10] = [
BlendMode::LinearBurn,
BlendMode::DarkerColor,
BlendMode::LinearDodge,
BlendMode::LighterColor,
BlendMode::VividLight,
BlendMode::LinearLight,
BlendMode::PinLight,
BlendMode::HardMix,
BlendMode::Subtract,
BlendMode::Divide,
];
/// The modes SVG has, which it builds from native compositing too below a full fill moving the layer toward neutral.
const BELOW_FULL_FILL: [BlendMode; 2] = [BlendMode::ColorDodge, BlendMode::ColorBurn];
/// A value as the 8-bit buffers browsers hold the results of filters and groups in keep it.
fn quantized(value: f64) -> f64 {
(value.clamp(0., 1.) * 255.).round() / 255.
}
/// The opaque color an opaque `source` composites natively by the mode onto an opaque `backdrop`, by the W3C's formula, held in 8 bits.
fn native(blend_mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
[0, 1, 2].map(|channel| quantized(blended[channel] as f64))
}
/// A color recolored, held in 8 bits.
fn recolored(recolor: Recolor, color: [f64; 3]) -> [f64; 3] {
color.map(|channel| quantized(recolor.scale * channel + recolor.offset))
}
/// The opaque color the `recipe` builds from an opaque `layer` over an opaque `backdrop`, compositing natively by the W3C's formulas, each result held in 8 bits.
fn emulated(recipe: &BlendRecipe, backdrop: [f64; 3], layer: [f64; 3]) -> [f64; 3] {
match recipe {
BlendRecipe::Stages(stages) => {
let mut result = backdrop;
for stage in stages {
result = recolored(stage.base, result);
for step in &stage.steps {
result = native(step.blend_mode, result, recolored(step.recolor, layer));
}
result = recolored(stage.stretch, result);
}
result
}
BlendRecipe::HardMixThreshold => {
let reaches_white = |offset: f64| native(BlendMode::ColorDodge, backdrop, recolored(Recolor { scale: 1., offset }, layer)).map(|channel| quantized(255. * channel - 254.));
let at_white = native(BlendMode::Multiply, backdrop, reaches_white(0.));
native(BlendMode::Lighten, at_white, reaches_white(-1. / 255.))
}
BlendRecipe::Pick { lighter } => {
let moved = native(BlendMode::Luminosity, backdrop, layer);
let toward = native(if *lighter { BlendMode::Lighten } else { BlendMode::Darken }, moved, backdrop);
let change = native(BlendMode::Difference, toward, backdrop);
let layer_wins = change.iter().sum::<f64>() * 255. >= 1.;
if layer_wins { layer } else { backdrop }
}
}
}
/// Colors on the 8-bit grid, which a render's inputs lie on.
fn levels(colors: &[[u8; 3]]) -> Vec<[f64; 3]> {
colors.iter().map(|color| color.map(|level| level as f64 / 255.)).collect()
}
/// How many levels the recipe's result may stray from the CPU's at a `fill` below full, where the layer's recolored channels round to whole levels:
/// none at full strength, which leaves them whole, a level otherwise, and on Hard Mix's ramp half a level stretched by `1 / (1 - steepness)`, more past a level.
fn tolerance(blend_mode: BlendMode, fill: f64) -> f64 {
match (fill < 1., blend_mode) {
(false, _) => 0.5,
(true, BlendMode::HardMix) => 1. + 0.5 / (1. - 255. * fill / 256.),
// Burning and dodging by a nearly black or white layer stretch its rounding most, by up to a fifth across these colors
(true, BlendMode::VividLight | BlendMode::ColorDodge | BlendMode::ColorBurn) => 3.,
(true, _) => 1.,
}
}
#[test]
fn recipes_build_each_mode_from_native_compositing_at_full_strength_exactly() {
// Every level of a gray backdrop under every level of a gray layer, and a spread of colors
let grays: Vec<[f64; 3]> = (0..=255).map(|level| [level as f64 / 255.; 3]).collect();
let colors = levels(&[
[0, 0, 0],
[255, 255, 255],
[204, 51, 128],
[30, 200, 90],
[128, 128, 128],
[250, 180, 20],
[64, 96, 230],
[127, 129, 140],
]);
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
for blend_mode in MODES.into_iter().filter(|blend_mode| !matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor)) {
let recipe = recipe(blend_mode, 1.).expect("SVG lacks the mode");
for (backdrops, layers) in [(&grays, &grays), (&colors, &colors)] {
for &backdrop in backdrops {
for &layer in layers {
let svg = emulated(&recipe, backdrop, layer);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
for channel in 0..3 {
assert!(
(svg[channel] - cpu[channel] as f64).abs() * 255. <= 0.5 + 1e-4,
"{blend_mode} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
);
}
}
}
}
}
}
#[test]
fn recipes_build_each_mode_from_native_compositing_below_full_strength_within_their_rounding() {
let colors = levels(&[
[0, 0, 0],
[255, 255, 255],
[204, 51, 128],
[30, 200, 90],
[128, 128, 128],
[250, 180, 20],
[64, 96, 230],
[127, 129, 140],
]);
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
for blend_mode in MODES.into_iter().filter(BlendMode::fill_moves_layer_toward_neutral).chain(BELOW_FULL_FILL) {
for fill in [0.8, 0.6, 0.25, 0.] {
let recipe = recipe(blend_mode, fill).expect("SVG lacks the mode");
for &backdrop in &colors {
for &layer in &colors {
let svg = emulated(&recipe, backdrop, layer);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, fill as f32);
for channel in 0..3 {
let difference = (svg[channel] - cpu[channel] as f64).abs() * 255.;
assert!(
difference <= tolerance(blend_mode, fill),
"{blend_mode} at fill {fill} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
);
}
}
}
}
}
}
#[test]
fn darker_and_lighter_color_pick_as_on_the_cpu_but_may_keep_the_backdrop_within_half_a_level_of_luma() {
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
let luma = |color: [f64; 3]| 255. * (0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]);
// Pairs of colors around ties of luma, by a fraction of a level or a level or more, with channels at black and white where Luminosity clips
let colors = levels(&[
[0, 0, 255],
[0, 48, 0],
[0, 47, 0],
[0, 49, 0],
[255, 0, 0],
[0, 130, 0],
[10, 120, 40],
[128, 128, 128],
[100, 140, 140],
[255, 255, 255],
[0, 0, 0],
[255, 254, 255],
]);
for lighter in [false, true] {
let blend_mode = if lighter { BlendMode::LighterColor } else { BlendMode::DarkerColor };
for &backdrop in &colors {
for &layer in &colors {
let svg = emulated(&BlendRecipe::Pick { lighter }, backdrop, layer);
let difference = luma(layer) - luma(backdrop);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
let cpu = [cpu[0] as f64, cpu[1] as f64, cpu[2] as f64];
// It picks what the CPU picks, or within half a level of a tie, where Luminosity may move no channel a level, it may keep the backdrop, as at a tie
let near_tie = difference.abs() < 0.5;
assert!(svg == cpu.map(quantized) || (near_tie && svg == backdrop), "{blend_mode} of {layer:?} over {backdrop:?} picks {svg:?}");
}
}
}
// Blue's luma lies just under green's, so Darker Color keeps the blue backdrop
let (blue, green) = ([0., 0., 1.], [0., 48. / 255., 0.]);
assert_eq!(emulated(&BlendRecipe::Pick { lighter: false }, blue, green), blue);
}
#[test]
fn layers_blend_by_the_alpha_beneath_and_their_own_as_on_the_cpu() {
let (backdrop, layer) = ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]);
// Color Dodge and Color Burn blend so only below a full fill
let cases = [(1., 0.5, 1., 1.), (0.5, 1., 0.6, 1.), (0.75, 0.25, 0.4, 0.7), (1., 0., 0.5, 1.), (1., 0.5, 0., 1.)];
let modes_and_cases = MODES.into_iter().chain(BELOW_FULL_FILL).flat_map(|blend_mode| cases.map(|case| (blend_mode, case)));
for (blend_mode, (layer_alpha, backdrop_alpha, fill, opacity)) in modes_and_cases.filter(|(blend_mode, (_, _, fill, _))| *fill < 1. || blend_mode.reads_backdrop()) {
// Only a fill moving the layer toward neutral reaches the blend, which shows it by the alpha beneath, and the layer is otherwise already faded by it
let moves = blend_mode.fill_moves_layer_toward_neutral();
let blend_fill = if moves { fill } else { 1. };
let drawn_alpha = if moves { layer_alpha } else { layer_alpha * fill };
let blend = emulated(&recipe(blend_mode, blend_fill).unwrap(), backdrop, layer);
// The layer made opaque, the blend over it by the alpha beneath, all shown by the layer's alpha, its fill's weight, and its opacity over what lies beneath
let shown = opacity * drawn_alpha * layer_fill_shown(backdrop_alpha as f32, blend_fill as f32) as f64;
let svg: Vec<f64> = (0..3)
.map(|channel| shown * (backdrop_alpha * blend[channel] + (1. - backdrop_alpha) * layer[channel]) + (1. - shown) * backdrop_alpha * backdrop[channel])
.chain([shown + (1. - shown) * backdrop_alpha])
.collect();
// The CPU blends the full-strength content by the fill, then the opacity mixes from what lies beneath to that
let premultiplied = |color: [f64; 3], alpha: f64| [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha].map(|channel| channel as f32);
let beneath = premultiplied(backdrop, backdrop_alpha);
let blended = blend_layer_pixel(premultiplied(layer, layer_alpha), beneath, blend_mode, fill as f32);
for channel in 0..4 {
let cpu = beneath[channel] as f64 + (blended[channel] - beneath[channel]) as f64 * opacity;
assert!(
(svg[channel] - cpu).abs() * 255. <= 2.,
"{blend_mode} at layer alpha {layer_alpha}, alpha beneath {backdrop_alpha}, fill {fill}, and opacity {opacity}: {svg:?} in SVG against {cpu} in channel {channel} on the CPU"
);
}
}
}
#[test]
fn modes_svg_has_take_no_recipe() {
for blend_mode in BlendMode::list().into_iter().flatten() {
assert_eq!(recipe(*blend_mode, 1.).is_some(), blend_mode.reads_backdrop(), "{blend_mode}");
}
}
}
@@ -42,7 +42,7 @@ impl BlendModeExt for BlendMode {
BlendMode::Saturation => peniko::Mix::Saturation, BlendMode::Saturation => peniko::Mix::Saturation,
BlendMode::Color => peniko::Mix::Color, BlendMode::Color => peniko::Mix::Color,
BlendMode::Luminosity => peniko::Mix::Luminosity, BlendMode::Luminosity => peniko::Mix::Luminosity,
// Like SVG, the modes that layers can't blend by fall back to normal // Vello lacks the rest, so they draw normally, and layers in those reading what lies beneath blend in an effects group (see `BlendMode::reads_backdrop`)
_ => peniko::Mix::Normal, _ => peniko::Mix::Normal,
} }
} }
@@ -612,7 +612,7 @@ impl<'a> VelloSceneBuilder<'a> {
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it. // What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much. // Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable(); let reads_backdrop = (layers.reads_backdrop() || layers.content_reads_backdrop(fill)) && capture.is_none() && bounds.is_some() && self.backdrop_readable();
if reads_backdrop && layers.reads_around_backdrop() { if reads_backdrop && layers.reads_around_backdrop() {
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch // A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing()); let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
@@ -3,7 +3,6 @@ use crate::vector::flatten::WorkingVector;
use crate::vector::misc::{BezierHandles, HandleId, HandleType}; use crate::vector::misc::{BezierHandles, HandleId, HandleType};
use crate::vector::path::{CurveType, Path, curve_types_of}; use crate::vector::path::{CurveType, Path, curve_types_of};
use core_types::list::{ATTR_ID, List}; use core_types::list::{ATTR_ID, List};
use core_types::uuid::generate_uuid;
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::DVec2; use glam::DVec2;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
@@ -1086,16 +1085,49 @@ impl VectorModification {
} }
} }
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order, // Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present. impl graphene_hash::CacheHash for PointModification {
// This will not actually lead to a cache invalidation in most cases due to the fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
// graph inputs being wrapped in a `MemoHash` wrapper. self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.delta).cache_hash(state);
}
}
impl graphene_hash::CacheHash for SegmentModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.start_point).cache_hash(state);
sorted_map(&self.end_point).cache_hash(state);
sorted_map(&self.handle_primary).cache_hash(state);
sorted_map(&self.handle_end).cache_hash(state);
}
}
impl graphene_hash::CacheHash for VectorModification { impl graphene_hash::CacheHash for VectorModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) { fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&generate_uuid(), state); self.points.cache_hash(state);
self.segments.cache_hash(state);
sorted_set(&self.add_g1_continuous).cache_hash(state);
sorted_set(&self.remove_g1_continuous).cache_hash(state);
sorted_set(&self.path_breaks).cache_hash(state);
sorted_set(&self.turned_on_load).cache_hash(state);
} }
} }
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
let mut items: Vec<_> = set.iter().collect();
items.sort_unstable();
items
}
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_unstable_by_key(|&(key, _)| key);
entries
}
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples? // TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs) /// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
@@ -1263,6 +1295,23 @@ mod tests {
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}") format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
} }
fn cache_hash(modification: &VectorModification) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
std::hash::Hasher::finish(&hasher)
}
#[test]
fn equal_modifications_hash_equally() {
let (vector, paths) = mixed_geometry();
let first = VectorModification::create_from_vector(&vector, &paths);
let second = VectorModification::create_from_vector(&vector, &paths);
assert_eq!(cache_hash(&first), cache_hash(&first));
assert_eq!(cache_hash(&first), cache_hash(&second));
}
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath. /// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
fn mixed_geometry() -> (Vector, List<Path>) { fn mixed_geometry() -> (Vector, List<Path>) {
let mut bezpath = BezPath::new(); let mut bezpath = BezPath::new();
@@ -84,9 +84,7 @@ impl WgpuExecutor {
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array()); let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner); let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
self.inner self.inner.vello_renderer.render(self, &mut canvas, draw, view, size, &texture)?;
.vello_renderer
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
Ok(texture) Ok(texture)
} }
@@ -95,7 +93,7 @@ impl WgpuExecutor {
pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> { pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> {
let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32)); let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32));
self.inner.vello_renderer.render_scene(canvas, &self.context().device, &self.context().queue, scene, &texture); self.inner.vello_renderer.render_scene(self, canvas, scene, &texture);
Ok(texture) Ok(texture)
} }
@@ -165,7 +163,11 @@ impl WgpuExecutor {
} }
pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture { pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture {
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size, format) self.request_texture_with_mips(size, format, 1)
}
pub fn request_texture_with_mips(&self, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
self.inner.texture_cache.lock().unwrap().request_texture(self.context(), size, format, mip_level_count)
} }
pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer { pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
@@ -1,3 +1,4 @@
use crate::WgpuContext;
use glam::UVec2; use glam::UVec2;
use raster_types::Texture; use raster_types::Texture;
use std::collections::VecDeque; use std::collections::VecDeque;
@@ -16,24 +17,23 @@ impl TextureCache {
} }
} }
pub fn request_texture(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> Texture { pub fn request_texture(&mut self, context: &WgpuContext, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
let size = size.max(UVec2::ONE); let size = size.max(UVec2::ONE);
if let Some(pos) = self if let Some(pos) = self.textures.iter().position(|texture| {
.textures UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && texture.mip_level_count() == mip_level_count && !texture.is_shared() && !texture.is_weakly_shared()
.iter() }) {
.position(|texture| UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && !texture.is_shared() && !texture.is_weakly_shared())
{
let entry = self.textures.remove(pos).unwrap(); let entry = self.textures.remove(pos).unwrap();
let texture = entry.clone(); let texture = entry.clone();
self.textures.push_back(entry); self.textures.push_back(entry);
return texture; return texture;
} }
let incoming_bytes = size.x as u64 * size.y as u64 * format.block_copy_size(None).unwrap_or(4) as u64; self.evict_until_fits(memory_size_estimate(size, format, mip_level_count));
self.evict_until_fits(incoming_bytes);
let texture: Texture = device let usage = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT;
let texture: Texture = context
.device
.create_texture(&wgpu::TextureDescriptor { .create_texture(&wgpu::TextureDescriptor {
label: Some(&format!("cached_{}x{}", size.x, size.y)), label: Some(&format!("cached_{}x{}", size.x, size.y)),
size: wgpu::Extent3d { size: wgpu::Extent3d {
@@ -41,11 +41,11 @@ impl TextureCache {
height: size.y, height: size.y,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}, },
mip_level_count: 1, mip_level_count,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format, format,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, usage: usage & context.adapter.get_texture_format_features(format).allowed_usages,
view_formats: &[], view_formats: &[],
}) })
.into(); .into();
@@ -83,12 +83,20 @@ impl TextureCache {
} }
} }
fn memory_size_estimate(size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> u64 {
let texel_bytes = format.block_copy_size(None).unwrap_or(4) as u64;
(0..mip_level_count)
.map(|level| (size >> level).max(UVec2::ONE))
.map(|level_size| level_size.x as u64 * level_size.y as u64 * texel_bytes)
.sum()
}
trait TextureMemoryCostEstimateExt { trait TextureMemoryCostEstimateExt {
fn memory_size_estimate(&self) -> u64; fn memory_size_estimate(&self) -> u64;
} }
impl TextureMemoryCostEstimateExt for wgpu::Texture { impl TextureMemoryCostEstimateExt for wgpu::Texture {
fn memory_size_estimate(&self) -> u64 { fn memory_size_estimate(&self) -> u64 {
self.width() as u64 * self.height() as u64 * self.format().block_copy_size(None).unwrap_or(4) as u64 memory_size_estimate(UVec2::new(self.width(), self.height()), self.format(), self.mip_level_count())
} }
} }
@@ -2,10 +2,13 @@
//! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their //! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their
//! settings from a texture, so changing those recompiles nothing. //! settings from a texture, so changing those recompiles nothing.
use crate::WgpuExecutor;
use crate::vello_effects::{WORKING_FORMAT, pass_pipeline}; use crate::vello_effects::{WORKING_FORMAT, pass_pipeline};
use core_types::graphene_hash::CacheHash; use core_types::graphene_hash::CacheHash;
use glam::UVec2;
use graphic_types::Adjustment; use graphic_types::Adjustment;
use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants}; use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants};
use raster_types::{Texture, TextureWeakRef};
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::HashMap; use std::collections::HashMap;
use std::ops::Range; use std::ops::Range;
@@ -22,11 +25,8 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL
/// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart. /// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart.
const MAX_CACHED_RUNS: usize = 8; const MAX_CACHED_RUNS: usize = 8;
/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first. /// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default,
const TABLE_CACHE_BYTES: u64 = 256 << 20; /// which an upload passes through.
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer
/// wgpu allocates by default, which an upload passes through.
const MAX_TABLE_TEXELS: usize = 1 << 23; const MAX_TABLE_TEXELS: usize = 1 << 23;
/// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing. /// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing.
@@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg
} }
/// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too. /// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too.
fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option<wgpu::Texture> { fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option<Texture> {
let max_dimension = device.limits().max_texture_dimension_2d as usize; let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize;
let width = texels.len().clamp(1, max_dimension); let width = texels.len().clamp(1, max_dimension);
let height = texels.len().div_ceil(width).max(1); let height = texels.len().div_ceil(width).max(1);
if height > max_dimension { if height > max_dimension {
return None; return None;
} }
let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32)); let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| { let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| {
let texture_rows = wgpu::TexelCopyTextureInfo { let texture_rows = wgpu::TexelCopyTextureInfo {
texture: &texture, texture: &texture,
@@ -397,12 +397,12 @@ pub(crate) struct PreparedPass {
/// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count, /// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count,
/// or `None` if any holds more than the GPU can read. /// or `None` if any holds more than the GPU can read.
fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, wgpu::Texture)>> { fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, Texture)>> {
(pass_steps(steps.kinds()).into_iter()) (pass_steps(steps.kinds()).into_iter())
.map(|pass| { .map(|pass| {
let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]); let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]);
let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect(); let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect();
upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture)) upload_texels(executor, queue, &texels).map(|texture| (shader, texture))
}) })
.collect() .collect()
} }
@@ -419,15 +419,14 @@ pub(crate) struct AdjustmentUploads {
struct CachedRun { struct CachedRun {
hash: u64, hash: u64,
steps: AdjustmentSteps, steps: AdjustmentSteps,
passes: Option<Vec<(AdjustmentShader, wgpu::Texture)>>, passes: Option<Vec<(AdjustmentShader, TextureWeakRef)>>,
last_used: u64, last_used: u64,
} }
/// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled. /// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled.
struct CachedTables { struct CachedTables {
key: u64, key: u64,
uploaded: Option<wgpu::Texture>, uploaded: Option<TextureWeakRef>,
bytes: u64,
last_used: u64, last_used: u64,
} }
@@ -438,70 +437,95 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 {
std::hash::Hasher::finish(&hasher) std::hash::Hasher::finish(&hasher)
} }
fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> {
passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect()
}
impl AdjustmentUploads { impl AdjustmentUploads {
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color /// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`.
/// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart. /// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec<PreparedPass> { pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec<Texture>) -> Vec<PreparedPass> {
let hash = adjustment_run_hash(run); let hash = adjustment_run_hash(run);
let mut uploaded = None;
let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| { let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| {
let steps = AdjustmentSteps::encode(run); let steps = AdjustmentSteps::encode(run);
let passes = upload_passes(device, queue, &steps); uploaded = upload_passes(executor, queue, &steps);
if passes.is_none() { if uploaded.is_none() {
log::error!("Adjustments hold more settings than the GPU can read, so they're left out"); log::error!("Adjustments hold more settings than the GPU can read, so they're left out");
} }
self.runs.push(CachedRun { self.runs.push(CachedRun {
hash, hash,
steps, steps,
passes, passes: uploaded.as_deref().map(downgrade_passes),
last_used: render_count, last_used: render_count,
}); });
self.runs.len() - 1 self.runs.len() - 1
}); });
let cached_run = &mut self.runs[index]; let cached_run = &mut self.runs[index];
cached_run.last_used = render_count; cached_run.last_used = render_count;
let Some(passes) = cached_run.passes.clone() else { return Vec::new() }; let Some(cached_passes) = &cached_run.passes else { return Vec::new() };
let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect();
let passes = match uploaded.or(parked) {
Some(passes) => passes,
None => {
let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() };
cached_run.passes = Some(downgrade_passes(&passes));
passes
}
};
if passes.is_empty() { if passes.is_empty() {
return Vec::new(); return Vec::new();
} }
let tables = match cached_run.steps.table_key() { let tables = match cached_run.steps.table_key() {
Some(key) => { Some(key) => {
let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| { let index = self.tables.iter().position(|cached| cached.key == key);
// As many texels as one texture holds and one upload carries let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade));
let limits = device.limits(); let tables = match parked {
let max_dimension = limits.max_texture_dimension_2d as usize; // Failed to upload
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize; Some(None) => return Vec::new(),
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded)); // Parked
Some(Some(Some(tables))) => Some(tables),
// Not parked
Some(Some(None)) | None => {
// As many texels as one texture holds and one upload carries
let limits = executor.context().device.limits();
let max_dimension = limits.max_texture_dimension_2d as usize;
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels); let uploaded = upload_texels(executor, queue, &texels);
if uploaded.is_none() { if uploaded.is_none() {
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out"); log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
}
let cached = CachedTables {
key,
uploaded: uploaded.as_ref().map(Texture::downgrade),
last_used: render_count,
};
match index {
Some(index) => self.tables[index] = cached,
None => self.tables.push(cached),
}
uploaded
} }
};
self.tables.push(CachedTables { let Some(tables) = tables else { return Vec::new() };
key, if let Some(index) = index {
bytes: uploaded self.tables[index].last_used = render_count;
.as_ref() }
.map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64), Some(tables)
uploaded,
last_used: render_count,
});
self.tables.len() - 1
});
let cached_tables = &mut self.tables[index];
cached_tables.last_used = render_count;
let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() };
Some(uploaded)
} }
None => None, None => None,
}; };
held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone()));
(passes.into_iter()) (passes.into_iter())
.map(|(shader, steps)| PreparedPass { .map(|(shader, steps)| PreparedPass {
shader, shader,
steps, steps: (*steps).clone(),
tables: tables.clone(), tables: tables.as_ref().map(|tables| (**tables).clone()),
}) })
.collect() .collect()
} }
@@ -513,13 +537,7 @@ impl AdjustmentUploads {
let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count(); let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count();
self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS)); self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS));
// Tables are kept within a byte budget instead, since one can take up hundreds of megabytes self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some()));
self.tables.sort_by_key(|cached| Reverse(cached.last_used));
let mut kept_bytes = 0;
self.tables.retain(|cached| {
kept_bytes += cached.bytes;
cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES
});
} }
#[cfg(test)] #[cfg(test)]
@@ -1630,7 +1630,11 @@ fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
return max(c_s, c_b); return max(c_s, c_b);
} }
// A black backdrop stays black, and any other turns white under a white source, as the W3C formula orders them
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 { fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if abs(c_b) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE { if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.; return 1.;
} }
@@ -1726,7 +1730,8 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
return blend_pin_light(c_b, c_s); return blend_pin_light(c_b, c_s);
} }
case BLEND_HARD_MIX: { case BLEND_HARD_MIX: {
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5); // A ramp a 256th wide around where the channels sum to 1, matching `blend_hard_mix`
return (c_b - 255. / 256. * (1. - c_s)) * 256.;
} }
case BLEND_DIFFERENCE: { case BLEND_DIFFERENCE: {
return abs(c_b - c_s); return abs(c_b - c_s);
@@ -1751,11 +1756,11 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> { fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> {
switch mode { switch mode {
case BLEND_DARKER_COLOR: { case BLEND_DARKER_COLOR: {
let background_is_darker = (background.r + background.g + background.b) / 3. <= (foreground.r + foreground.g + foreground.b) / 3.; let background_is_darker = luma_rec_601_rounded(background.rgb) <= luma_rec_601_rounded(foreground.rgb);
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a); return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a);
} }
case BLEND_LIGHTER_COLOR: { case BLEND_LIGHTER_COLOR: {
let background_is_lighter = (background.r + background.g + background.b) / 3. >= (foreground.r + foreground.g + foreground.b) / 3.; let background_is_lighter = luma_rec_601_rounded(background.rgb) >= luma_rec_601_rounded(foreground.rgb);
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a); return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a);
} }
case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: { case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: {
@@ -1,5 +1,6 @@
//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back. //! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back.
use crate::WgpuExecutor;
use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass}; use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass};
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use core_types::Color; use core_types::Color;
@@ -14,6 +15,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique}; use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes}; use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
use raster_kernels::resample_kernels::MotionBlurShear; use raster_kernels::resample_kernels::MotionBlurShear;
use raster_types::Texture;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Mutex, PoisonError}; use std::sync::{Mutex, PoisonError};
use vello_gpu::kurbo::Affine; use vello_gpu::kurbo::Affine;
@@ -21,6 +23,7 @@ use wgpu::util::DeviceExt;
mod blend_if; mod blend_if;
mod filters; mod filters;
mod layer_blend;
mod masks; mod masks;
mod resample; mod resample;
mod styles; mod styles;
@@ -49,9 +52,6 @@ const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
const PARAMETER_TAPS: usize = 81; const PARAMETER_TAPS: usize = 81;
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2)); const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
/// How many renders a pooled texture survives unused before it is freed.
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
/// The shader's parameters, laid out to match its `Parameters` struct. /// The shader's parameters, laid out to match its `Parameters` struct.
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)] #[derive(Clone, Copy, Pod, Zeroable)]
@@ -167,7 +167,7 @@ impl EffectPasses {
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects"); log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
} }
// The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers // The filters', resampling, styles', masks', Blend If's, and layer blending's passes live in files of their own, sharing this one's bindings and helpers
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("vello_effects.wgsl"), label: Some("vello_effects.wgsl"),
source: wgpu::ShaderSource::Wgsl( source: wgpu::ShaderSource::Wgsl(
@@ -179,7 +179,8 @@ impl EffectPasses {
include_str!("vello_warp.wgsl"), include_str!("vello_warp.wgsl"),
include_str!("vello_styles.wgsl"), include_str!("vello_styles.wgsl"),
include_str!("vello_masks.wgsl"), include_str!("vello_masks.wgsl"),
include_str!("vello_blend_if.wgsl") include_str!("vello_blend_if.wgsl"),
include_str!("vello_layer_blend.wgsl")
) )
.into(), .into(),
), ),
@@ -263,7 +264,8 @@ impl EffectPasses {
.clone() .clone()
} }
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by. /// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by
/// (normal for one in a mode Vello's layers lack, which comes back blended onto the `backdrop` already).
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers. /// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
/// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own. /// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own.
/// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content. /// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content.
@@ -272,7 +274,7 @@ impl EffectPasses {
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
pub(crate) fn apply( pub(crate) fn apply(
&self, &self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
textures: &mut EffectTextures, textures: &mut EffectTextures,
content: &wgpu::Texture, content: &wgpu::Texture,
@@ -286,8 +288,10 @@ impl EffectPasses {
backdrop: Option<(&wgpu::Texture, Affine)>, backdrop: Option<(&wgpu::Texture, Affine)>,
capture: Option<EffectCapture>, capture: Option<EffectCapture>,
) -> Vec<(wgpu::Texture, BlendMode)> { ) -> Vec<(wgpu::Texture, BlendMode)> {
let device = &executor.context().device;
let mut recorder = PassRecorder { let mut recorder = PassRecorder {
passes: self, passes: self,
executor,
device, device,
queue, queue,
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }), encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }),
@@ -297,6 +301,16 @@ impl EffectPasses {
let lengths_to_pixels = effect_to_pixels.matrix2; let lengths_to_pixels = effect_to_pixels.matrix2;
let length_scale = lengths_to_pixels.determinant().abs().sqrt(); let length_scale = lengths_to_pixels.determinant().abs().sqrt();
// A fill moving the content toward its layer mode's neutral color leaves the content at full strength, for its layer to blend by that fill.
// Color Dodge and Color Burn layers blend so only where they read what lies beneath (see `EffectLayers::content_reads_backdrop`), and with nothing to read, natively.
let content_mode = layers.content_layer().map(|layer| layers.layers[layer].blend_mode);
let natively_otherwise = content_mode.is_some_and(|blend_mode| !blend_mode.reads_backdrop());
let content_blends_onto_backdrop = layers.content_reads_backdrop(fill) && !(natively_otherwise && backdrop.is_none());
let (fill, blend_fill) = match content_blends_onto_backdrop && content_mode.is_some_and(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()) {
true => (1., fill),
false => (fill, 1.),
};
// The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it // The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it
let mut full: Option<wgpu::Texture> = None; let mut full: Option<wgpu::Texture> = None;
// The content faded by the fill, which shows in the result // The content faded by the fill, which shows in the result
@@ -832,7 +846,7 @@ impl EffectPasses {
| EffectOperation::MinimumMaximum { .. } | EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. } | EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. } | EffectOperation::HighPass { .. }
| EffectOperation::AddNoise { .. } | EffectOperation::Speckle { .. }
| EffectOperation::Dissolve { .. } => { | EffectOperation::Dissolve { .. } => {
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take()); recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
let captured_plane = capture.filter(|capture| capture.index == index).map(|capture| capture.plane); let captured_plane = capture.filter(|capture| capture.index == index).map(|capture| capture.plane);
@@ -999,7 +1013,7 @@ impl EffectPasses {
// The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it // The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it
let full_is_read = filled.is_none() || position + run.len() < operations.len(); let full_is_read = filled.is_none() || position + run.len() < operations.len();
let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run); let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run);
// Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing // Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing
for (index, prepared) in prepared_passes.iter().enumerate() { for (index, prepared) in prepared_passes.iter().enumerate() {
@@ -1130,7 +1144,7 @@ impl EffectPasses {
// Each layer stacks its parts in order: what lies beneath the content, then the content with what lies within it // Each layer stacks its parts in order: what lies beneath the content, then the content with what lies within it
let mut content_image = Some(content_image); let mut content_image = Some(content_image);
let mut results = Vec::new(); let (mut results, mut content_result) = (Vec::new(), None);
for (index, layer) in layers.layers.iter().enumerate() { for (index, layer) in layers.layers.iter().enumerate() {
let holds_content = Some(index) == content_layer; let holds_content = Some(index) == content_layer;
let mut stack = if holds_content { beneath.take() } else { None }; let mut stack = if holds_content { beneath.take() } else { None };
@@ -1199,9 +1213,16 @@ impl EffectPasses {
let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default()); let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default());
recorder.replace(&mut result, faded); recorder.replace(&mut result, faded);
} }
if holds_content {
content_result = Some(results.len());
}
results.push((result, layer.blend_mode)); results.push((result, layer.blend_mode));
} }
// A layer in a mode Vello's layers lack blends onto what lies beneath here, before the Blend Ifs fade the blended layer
let content_result = content_result.filter(|_| content_blends_onto_backdrop);
recorder.blend_onto_backdrop(backdrop, blend_fill, content_result, &mut results);
// Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them // Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them
let underlying = underlying_ranges(&every_operation); let underlying = underlying_ranges(&every_operation);
if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) { if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) {
@@ -1223,7 +1244,7 @@ impl EffectPasses {
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
pub(crate) fn adjust_image( pub(crate) fn adjust_image(
&self, &self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
textures: &mut EffectTextures, textures: &mut EffectTextures,
image: &wgpu::Texture, image: &wgpu::Texture,
@@ -1232,8 +1253,10 @@ impl EffectPasses {
target: &wgpu::Texture, target: &wgpu::Texture,
) { ) {
let size = UVec2::new(image.width(), image.height()); let size = UVec2::new(image.width(), image.height());
let device = &executor.context().device;
let mut recorder = PassRecorder { let mut recorder = PassRecorder {
passes: self, passes: self,
executor,
device, device,
queue, queue,
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -1265,19 +1288,20 @@ impl EffectPasses {
} }
chained.into_iter().for_each(|texture| recorder.textures.release(texture)); chained.into_iter().for_each(|texture| recorder.textures.release(texture));
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target); self.record_mipmaps(executor, &mut recorder.encoder, recorder.textures, target);
queue.submit([recorder.encoder.finish()]); queue.submit([recorder.encoder.finish()]);
} }
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image. /// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read. /// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) { pub(crate) fn record_mipmaps(&self, executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
let device = &executor.context().device;
let format = texture.format(); let format = texture.format();
let mut above: Option<wgpu::Texture> = None; let mut above: Option<wgpu::Texture> = None;
for index in 1..texture.mip_level_count() { for index in 1..texture.mip_level_count() {
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE); let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
let level = textures.acquire(device, level_size, format); let level = textures.acquire(executor, level_size, format);
// The first level reads the top one through a view of every level // The first level reads the top one through a view of every level
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default()); let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
@@ -1430,6 +1454,7 @@ fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
/// Records the passes of one effects group, whose images all share one size. /// Records the passes of one effects group, whose images all share one size.
struct PassRecorder<'a> { struct PassRecorder<'a> {
passes: &'a EffectPasses, passes: &'a EffectPasses,
executor: &'a WgpuExecutor,
device: &'a wgpu::Device, device: &'a wgpu::Device,
queue: &'a wgpu::Queue, queue: &'a wgpu::Queue,
encoder: wgpu::CommandEncoder, encoder: wgpu::CommandEncoder,
@@ -1450,7 +1475,7 @@ impl PassRecorder<'_> {
content: Option<&wgpu::Texture>, content: Option<&wgpu::Texture>,
parameters: Parameters, parameters: Parameters,
) -> wgpu::Texture { ) -> wgpu::Texture {
let target = self.textures.acquire(self.device, size, format); let target = self.textures.acquire(self.executor, size, format);
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
let (source, secondary, content) = (view(source), secondary.map(view), content.map(view)); let (source, secondary, content) = (view(source), secondary.map(view), content.map(view));
@@ -1598,7 +1623,7 @@ impl PassRecorder<'_> {
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> { fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?; let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect(); let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples)); let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
let parameters = Parameters { let parameters = Parameters {
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)], values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
@@ -1653,27 +1678,17 @@ impl PassRecorder<'_> {
let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES) let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES)
.map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.))) .map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.)))
.collect(); .collect();
self.row_texture("vello_effects_contour", COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples)) self.row_texture(COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
} }
/// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples. /// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples.
/// It's made fresh rather than pooled, since its upload runs ahead of the passes recorded before it that a pooled texture may still serve. fn row_texture(&mut self, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
fn row_texture(&mut self, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
let extent = wgpu::Extent3d { let extent = wgpu::Extent3d {
width, width,
height: 1, height: 1,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}; };
let texture = self.device.create_texture(&wgpu::TextureDescriptor { let texture = self.executor.request_texture_with_format(UVec2::new(width, 1), format);
label: Some(label),
size: extent,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.queue.write_texture( self.queue.write_texture(
wgpu::TexelCopyTextureInfo { wgpu::TexelCopyTextureInfo {
texture: &texture, texture: &texture,
@@ -1689,7 +1704,9 @@ impl PassRecorder<'_> {
}, },
extent, extent,
); );
texture let row = (*texture).clone();
self.textures.held.push(texture);
row
} }
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it. /// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
@@ -1898,7 +1915,7 @@ impl PassRecorder<'_> {
/// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass, /// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass,
/// in the `encodings` of its source and result. /// in the `encodings` of its source and result.
fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture { fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture {
let target = self.textures.acquire(self.device, self.size, format); let target = self.textures.acquire(self.executor, self.size, format);
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
self.adjust_into(&view(&target), format, &view(image), prepared, encodings); self.adjust_into(&view(&target), format, &view(image), prepared, encodings);
@@ -1994,11 +2011,11 @@ impl PassRecorder<'_> {
} }
} }
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes. /// Textures for the effect passes and the content they work on, taken from the texture pool and held until the render ends.
#[derive(Default)] #[derive(Default)]
pub(crate) struct EffectTextures { pub(crate) struct EffectTextures {
/// Each unused texture with the render it was last used in. held: Vec<Texture>,
free: Vec<(wgpu::Texture, u64)>, released: Vec<wgpu::Texture>,
/// The uploads of recent runs of adjustments. /// The uploads of recent runs of adjustments.
adjustments: AdjustmentUploads, adjustments: AdjustmentUploads,
render_count: u64, render_count: u64,
@@ -2009,43 +2026,32 @@ pub(crate) struct EffectTextures {
impl EffectTextures { impl EffectTextures {
/// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it. /// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it.
pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> { pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
self.adjustments.prepare(device, queue, run, self.render_count) self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held)
} }
pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture { pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
let size = size.max(UVec2::ONE); let size = size.max(UVec2::ONE);
let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format; let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format;
if let Some(index) = self.free.iter().position(|(texture, _)| matches(texture)) { if let Some(index) = self.released.iter().position(matches) {
return self.free.swap_remove(index).0; return self.released.swap_remove(index);
} }
device.create_texture(&wgpu::TextureDescriptor { let texture = executor.request_texture_with_format(size, format);
label: Some("vello_effects_texture"), let acquired = (*texture).clone();
size: wgpu::Extent3d { self.held.push(texture);
width: size.x, acquired
height: size.y,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
} }
/// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them. /// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them.
pub(crate) fn release(&mut self, texture: wgpu::Texture) { pub(crate) fn release(&mut self, texture: wgpu::Texture) {
self.free.push((texture, self.render_count)); self.released.push(texture);
} }
/// Frees the textures no recent render has used.
pub(crate) fn finish_render(&mut self) { pub(crate) fn finish_render(&mut self) {
let render_count = self.render_count; self.released.clear();
self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT); self.held.clear();
self.adjustments.finish_render(render_count); self.adjustments.finish_render(self.render_count);
self.render_count += 1; self.render_count += 1;
} }
@@ -2088,7 +2094,10 @@ mod tests {
use core_types::list::Item; use core_types::list::Item;
use graphic_types::vector_types::Gradient; use graphic_types::vector_types::Gradient;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2126,12 +2135,12 @@ mod tests {
let effects = Effects::from_operations(operations); let effects = Effects::from_operations(operations);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let apply = |textures: &mut EffectTextures, effects: &Effects| { let apply = |textures: &mut EffectTextures, effects: &Effects| {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
}; };
let draw = |textures: &mut EffectTextures| { let draw = |textures: &mut EffectTextures| {
@@ -2153,7 +2162,7 @@ mod tests {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let effects = Effects::from_operations(operations); let effects = Effects::from_operations(operations);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone() textures.drawn_passes.clone()
}; };
@@ -2184,7 +2193,10 @@ mod tests {
fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() { fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() {
use graphic_types::effects::EffectKind; use graphic_types::effects::EffectKind;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2192,12 +2204,12 @@ mod tests {
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]); let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let mut drawn = |layered: bool| { let mut drawn = |layered: bool| {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone() textures.drawn_passes.clone()
}; };
@@ -2208,7 +2220,10 @@ mod tests {
fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() { fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() {
use graphic_types::effects::EffectKind; use graphic_types::effects::EffectKind;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2216,10 +2231,10 @@ mod tests {
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]); let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count(); let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
@@ -2228,7 +2243,10 @@ mod tests {
#[test] #[test]
fn a_table_stays_uploaded_while_the_settings_beside_it_change() { fn a_table_stays_uploaded_while_the_settings_beside_it_change() {
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let queue = context.queue.lock(); let queue = context.queue.lock();
let lookup = Adjustment::ColorLookup { let lookup = Adjustment::ColorLookup {
@@ -2238,7 +2256,7 @@ mod tests {
let prepare = |textures: &mut EffectTextures, posterize_levels| { let prepare = |textures: &mut EffectTextures, posterize_levels| {
let posterize = Adjustment::Posterize { levels: posterize_levels }; let posterize = Adjustment::Posterize { levels: posterize_levels };
// Color Lookup's pass and then Posterize's, which share the run's tables // Color Lookup's pass and then Posterize's, which share the run's tables
let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]); let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]);
prepared.pop().map(|prepared| (prepared.steps, prepared.tables)) prepared.pop().map(|prepared| (prepared.steps, prepared.tables))
}; };
@@ -2250,11 +2268,13 @@ mod tests {
panic!("The run reads its table") panic!("The run reads its table")
}; };
assert!(first_steps == again_steps && first_table == again_table); assert!(first_steps == again_steps && first_table == again_table);
let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") };
assert!(other_steps != first_steps);
for levels in 5..20 { for levels in 5..20 {
let Some((steps, Some(table))) = prepare(&mut textures, levels) else { let Some((_, Some(table))) = prepare(&mut textures, levels) else {
panic!("The run reads its table") panic!("The run reads its table")
}; };
assert!(steps != first_steps && table == first_table); assert!(table == first_table);
textures.finish_render(); textures.finish_render();
} }
@@ -431,14 +431,13 @@ fn composite_beneath(@builtin(position) position: vec4<f32>) -> @location(0) vec
// The paint mixed with the backdrop by a blend mode besides the component ones, numbered in the order `BlendMode` declares them // The paint mixed with the backdrop by a blend mode besides the component ones, numbered in the order `BlendMode` declares them
fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> { fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
let average = vec3<f32>(1. / 3.);
switch mode { switch mode {
// Darker Color and Lighter Color keep whichever whole color has the lower or higher mean // Darker Color and Lighter Color keep whichever whole color has the lower or higher luma, the backdrop where they tie
case 5u: { case 5u: {
return select(paint, backdrop, dot(backdrop, average) <= dot(paint, average)); return select(paint, backdrop, luma(backdrop) <= luma(paint));
} }
case 10u: { case 10u: {
return select(paint, backdrop, dot(backdrop, average) >= dot(paint, average)); return select(paint, backdrop, luma(backdrop) >= luma(paint));
} }
default: { default: {
return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode)); return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode));
@@ -504,7 +503,7 @@ fn blend_channel(backdrop: f32, paint: f32, mode: u32) -> f32 {
result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5); result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5);
} }
case 17u: { case 17u: {
result = select(1., 0., linear_light(backdrop, paint) < 0.5); result = hard_mix(backdrop, paint, 1.);
} }
// Difference, Exclusion, Subtract, Divide // Difference, Exclusion, Subtract, Divide
case 18u: { case 18u: {
@@ -545,7 +544,11 @@ fn color_burn(backdrop: f32, paint: f32) -> f32 {
return 1. - min((1. - backdrop) / paint, 1.); return 1. - min((1. - backdrop) / paint, 1.);
} }
// A black backdrop stays black, and any other turns white under white paint, as the W3C formula orders them
fn color_dodge(backdrop: f32, paint: f32) -> f32 { fn color_dodge(backdrop: f32, paint: f32) -> f32 {
if abs(backdrop) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(paint - 1.) <= BLEND_EDGE_TOLERANCE { if abs(paint - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.; return 1.;
} }
@@ -568,6 +571,12 @@ fn linear_light(backdrop: f32, paint: f32) -> f32 {
return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5); return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5);
} }
// Hard Mix of a paint at `strength`, unclamped, whose ramp steepens to a 256th wide at full strength, matching the CPU's `blend_hard_mix_at_strength`
fn hard_mix(backdrop: f32, paint: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
return (backdrop - steepness * (1. - paint)) / (1. - steepness);
}
// Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them // Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them
fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> { fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
switch mode { switch mode {
@@ -50,7 +50,7 @@ pub(super) fn field_parameters(sampling: &FieldSampling, first_seed: u32, second
fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Option<(&'static str, &'static str, Parameters)> { fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Option<(&'static str, &'static str, Parameters)> {
let sampling = FieldSampling::new(effect_to_pixels.inverse()); let sampling = FieldSampling::new(effect_to_pixels.inverse());
match *operation { match *operation {
EffectOperation::AddNoise { EffectOperation::Speckle {
amount, amount,
distribution, distribution,
monochromatic, monochromatic,
@@ -67,7 +67,7 @@ fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Opti
], ],
..field_parameters(&sampling, RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed)) ..field_parameters(&sampling, RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed))
}; };
Some(("noise_map", "add_noise", parameters)) Some(("speckle_map", "speckle", parameters))
} }
EffectOperation::Dissolve { opacity, seed } => { EffectOperation::Dissolve { opacity, seed } => {
let parameters = Parameters { let parameters = Parameters {
@@ -412,7 +412,7 @@ fn sample_offset(column: u32, row: u32) -> vec2<f32> {
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw; return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
} }
// The offsets Add Noise gives a texel's colors, matching the CPU's `add_noise`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1, // The offsets Speckle gives a texel's colors, matching the CPU's `speckle`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
// scaled by `values.x` and kept within `values.y` either way // scaled by `values.x` and kept within `values.y` either way
fn noise_offsets(position: vec2<f32>) -> vec3<f32> { fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
let counts = sample_counts(); let counts = sample_counts();
@@ -439,15 +439,15 @@ fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
return clamp(noise * parameters.values.x, vec3<f32>(-parameters.values.y), vec3<f32>(parameters.values.y)); return clamp(noise * parameters.values.x, vec3<f32>(-parameters.values.y), vec3<f32>(parameters.values.y));
} }
// The offsets Add Noise gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors // The offsets Speckle gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
@fragment @fragment
fn noise_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> { fn speckle_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(0.5 + noise_offsets(position.xy) / (2. * parameters.values.y), 1.); return vec4<f32>(0.5 + noise_offsets(position.xy) / (2. * parameters.values.y), 1.);
} }
// Each straight color offset by noise and clamped, with the coverage kept // Each straight color offset by noise and clamped, with the coverage kept
@fragment @fragment
fn add_noise(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> { fn speckle(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let color = textureLoad(source, vec2<i32>(position.xy), 0); let color = textureLoad(source, vec2<i32>(position.xy), 0);
if color.a <= 0. { if color.a <= 0. {
return vec4<f32>(0.); return vec4<f32>(0.);
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more