From a679ae8649e4539cbaca35b7e25e36ba5c80c0df Mon Sep 17 00:00:00 2001 From: VimYoung Date: Tue, 13 Oct 2026 00:15:24 +0530 Subject: [PATCH 01/15] Add: Palette tab in Window --- editor/src/dispatcher.rs | 1 + .../messages/menu_bar/menu_bar_message_handler.rs | 7 +++++++ editor/src/messages/portfolio/utility_types.rs | 5 ++++- .../portfolio/workspace/workspace_message.rs | 1 + .../workspace/workspace_message_handler.rs | 15 +++++++++++++++ 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 991d347b196..ca9fcaf3695 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -307,6 +307,7 @@ impl Dispatcher { menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data); menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers); menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector); + menu_bar_message_handler.palette_panel_open = layout.is_panel_present(PanelType::Palette); menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity; menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open; menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences; diff --git a/editor/src/messages/menu_bar/menu_bar_message_handler.rs b/editor/src/messages/menu_bar/menu_bar_message_handler.rs index d118f58621f..e53d9c97177 100644 --- a/editor/src/messages/menu_bar/menu_bar_message_handler.rs +++ b/editor/src/messages/menu_bar/menu_bar_message_handler.rs @@ -26,6 +26,7 @@ pub struct MenuBarMessageHandler { pub data_panel_open: bool, pub layers_panel_open: bool, pub inspector_open: bool, + pub palette_panel_open: bool, pub focus_document: bool, } @@ -681,6 +682,12 @@ impl LayoutHolder for MenuBarMessageHandler { .tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleLayersPanelOpen)) .on_commit(|_| WorkspaceMessage::ToggleLayersPanelOpen.into()) .disabled(self.focus_document), + MenuListEntry::new("Palette") + .label("Palette") + .icon(if self.palette_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" }) + .tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::TogglePalettePanelOpen)) + .on_commit(|_| WorkspaceMessage::TogglePalettePanelOpen.into()) + .disabled(self.focus_document), MenuListEntry::new("Data") .label("Data") .icon(if self.data_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" }) diff --git a/editor/src/messages/portfolio/utility_types.rs b/editor/src/messages/portfolio/utility_types.rs index 4205e182cf7..d1660ef4bd6 100644 --- a/editor/src/messages/portfolio/utility_types.rs +++ b/editor/src/messages/portfolio/utility_types.rs @@ -12,6 +12,7 @@ pub enum PanelType { #[serde(alias = "Properties")] Inspector, Data, + Palette, } impl From for PanelType { @@ -22,6 +23,8 @@ impl From for PanelType { "Layers" => PanelType::Layers, "Inspector" | "Properties" => PanelType::Inspector, "Data" => PanelType::Data, + // TODO: Determine why it is not producing space betwen color and Palette + "Palette" => PanelType::Palette, _ => panic!("Unknown panel type: {value}"), } } @@ -29,7 +32,7 @@ impl From for PanelType { impl PanelType { pub fn non_document_panels() -> &'static [PanelType] { - &[PanelType::Layers, PanelType::Inspector, PanelType::Data] + &[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Palette] } } diff --git a/editor/src/messages/portfolio/workspace/workspace_message.rs b/editor/src/messages/portfolio/workspace/workspace_message.rs index 21e8a3f9b76..55012cf3027 100644 --- a/editor/src/messages/portfolio/workspace/workspace_message.rs +++ b/editor/src/messages/portfolio/workspace/workspace_message.rs @@ -33,6 +33,7 @@ pub enum WorkspaceMessage { ToggleDataPanelOpen, ToggleInspectorOpen, ToggleLayersPanelOpen, + TogglePalettePanelOpen, UpdatePanelsLayout, ResetWorkspaceLayout, SetPanelGroupSizes { diff --git a/editor/src/messages/portfolio/workspace/workspace_message_handler.rs b/editor/src/messages/portfolio/workspace/workspace_message_handler.rs index d7785ffa31b..1b5e05711d7 100644 --- a/editor/src/messages/portfolio/workspace/workspace_message_handler.rs +++ b/editor/src/messages/portfolio/workspace/workspace_message_handler.rs @@ -275,6 +275,14 @@ impl MessageHandler for WorkspaceMess let panel_type = PanelType::Data; self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses); } + WorkspaceMessage::TogglePalettePanelOpen => { + if self.panel_layout.focus_document { + return; + } + + let panel_type = PanelType::Palette; + self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses); + } WorkspaceMessage::UpdatePanelsLayout => { let panel_layout = match self.panel_layout.focus_document { true => self.panel_layout.document_only_layout(), @@ -391,6 +399,8 @@ impl WorkspaceMessageHandler { PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar], PanelType::Data => &[LayoutTarget::DataPanel, LayoutTarget::DataPanelContext, LayoutTarget::DataPanelPath], PanelType::Document | PanelType::Welcome => return, + // TODO: Fix the destroy process properly + PanelType::Palette => return, }; for &layout_target in targets { @@ -416,6 +426,11 @@ impl WorkspaceMessageHandler { PanelType::Data => { // The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here } + PanelType::Palette => { + // TODO: Add update functionality if a connected node with palette + // triggers a color change event, that should be reflected back + // in the palette panel + } PanelType::Document | PanelType::Welcome => { // Re-send the welcome screen buttons layout to repopulate after a remount if has_no_documents { From 32fbfcde46a69fc87e964ff1230c5bc68b23264d Mon Sep 17 00:00:00 2001 From: VimYoung Date: Sun, 25 Oct 2026 12:26:07 +0530 Subject: [PATCH 02/15] Add: Necessary wiring for palette messages --- .../layout/utility_types/layout_widget.rs | 4 ++++ .../portfolio/document/document_message.rs | 3 +++ .../document/document_message_handler.rs | 8 +++++++ editor/src/messages/portfolio/document/mod.rs | 1 + .../portfolio/document/palette/mod.rs | 7 ++++++ .../document/palette/palette_message.rs | 7 ++++++ .../palette/palette_message_handler.rs | 23 +++++++++++++++++++ .../portfolio/portfolio_message_handler.rs | 2 ++ 8 files changed, 55 insertions(+) create mode 100644 editor/src/messages/portfolio/document/palette/mod.rs create mode 100644 editor/src/messages/portfolio/document/palette/palette_message.rs create mode 100644 editor/src/messages/portfolio/document/palette/palette_message_handler.rs diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 1a7cc8de694..0ad9d897123 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -70,6 +70,10 @@ define_layout_target!( LayersPanelBottomRightBar, /// Blending options at the top of the Layers panel. LayersPanelControlLeftBar, + /// Adding palette, naming/editing the palette + PalettePanelBottomRightBar, + /// Showcasing currently focused active palette + PalettePanelBottomLeftBar, /// The dropdown menu at the very top of the application: File, Edit, etc. MenuBar, /// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons. diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index c5660d5618a..f43bd8ca8b3 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -5,6 +5,7 @@ use super::utility_types::misc::{GroupFolderType, SnappingState}; use crate::messages::input_mapper::utility_types::keyboard::Key; use crate::messages::portfolio::document::data_panel::DataPanelMessage; use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType}; +use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate}; @@ -39,6 +40,8 @@ pub enum DocumentMessage { #[child] DataPanel(DataPanelMessage), #[child] + Palette(PaletteMessage), + #[child] Resource(ResourceMessage), // Messages diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 3cbdd8831b2..56ae8ccf075 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -21,6 +21,8 @@ use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay, overlay_options}; use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot}; +use crate::messages::portfolio::document::palette::PaletteMessageHandler; +use crate::messages::portfolio::document::palette::palette_message_handler::PaletteMessageContext; use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier}; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector}; @@ -67,6 +69,7 @@ pub struct DocumentMessageContext<'a> { pub data_panel_open: bool, pub layers_panel_open: bool, pub inspector_open: bool, + pub palette_open: bool, pub viewport: &'a ViewportMessageHandler, pub resource_storage: &'a ResourceStorageMessageHandler, pub fonts: &'a FontsMessageHandler, @@ -100,6 +103,8 @@ pub struct DocumentMessageHandler { pub inspector_message_handler: InspectorMessageHandler, #[serde(skip)] pub data_panel_message_handler: DataPanelMessageHandler, + #[serde(skip)] + pub palette_message_handler: PaletteMessageHandler, // ============================================ // Fields that are saved in the document format @@ -207,6 +212,7 @@ impl Default for DocumentMessageHandler { overlays_message_handler: OverlaysMessageHandler::default(), inspector_message_handler: InspectorMessageHandler::default(), data_panel_message_handler: DataPanelMessageHandler::default(), + palette_message_handler: PaletteMessageHandler::default(), // ============================================ // Fields that are saved in the document format // ============================================ @@ -261,6 +267,7 @@ impl MessageHandler> for DocumentMes data_panel_open, layers_panel_open, inspector_open, + palette_open, resource_storage, fonts, } = context; @@ -313,6 +320,7 @@ impl MessageHandler> for DocumentMes }, ); } + DocumentMessage::Palette(message) => self.palette_message_handler.process_message(message, responses, PaletteMessageContext { palette_open }), DocumentMessage::NodeGraph(message) => { self.node_graph_handler.process_message( message, diff --git a/editor/src/messages/portfolio/document/mod.rs b/editor/src/messages/portfolio/document/mod.rs index a3318acbc7f..4d430a93cb8 100644 --- a/editor/src/messages/portfolio/document/mod.rs +++ b/editor/src/messages/portfolio/document/mod.rs @@ -11,6 +11,7 @@ pub mod inspector; pub mod navigation; pub mod node_graph; pub mod overlays; +pub mod palette; pub mod resource; pub mod utility_types; diff --git a/editor/src/messages/portfolio/document/palette/mod.rs b/editor/src/messages/portfolio/document/palette/mod.rs new file mode 100644 index 00000000000..d148fb8aa02 --- /dev/null +++ b/editor/src/messages/portfolio/document/palette/mod.rs @@ -0,0 +1,7 @@ +mod palette_message; +pub mod palette_message_handler; + +#[doc(inline)] +pub use palette_message::PaletteMessage; +#[doc(inline)] +pub use palette_message_handler::PaletteMessageHandler; diff --git a/editor/src/messages/portfolio/document/palette/palette_message.rs b/editor/src/messages/portfolio/document/palette/palette_message.rs new file mode 100644 index 00000000000..ec7ef5276bf --- /dev/null +++ b/editor/src/messages/portfolio/document/palette/palette_message.rs @@ -0,0 +1,7 @@ +use crate::messages::prelude::*; + +#[impl_message(Message, DocumentMessage, Palette)] +#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub enum PaletteMessage { + UploadPalette, +} diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs new file mode 100644 index 00000000000..74aca42586a --- /dev/null +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -0,0 +1,23 @@ +use crate::messages::portfolio::document::palette::PaletteMessage; +use crate::messages::prelude::*; + +#[derive(ExtractField)] +pub struct PaletteMessageContext { + pub palette_open: bool, +} + +#[derive(Debug, Clone, Default, ExtractField)] +pub struct PaletteMessageHandler {} + +#[message_handler_data] +impl MessageHandler for PaletteMessageHandler { + fn process_message(&mut self, message: PaletteMessage, responses: &mut VecDeque, context: PaletteMessageContext) { + match message { + PaletteMessage::UploadPalette => todo!(), + } + } + + fn actions(&self) -> ActionList { + actions!(PaletteMessage;) + } +} diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index c518e5cb7a6..db4a9d54925 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -103,6 +103,7 @@ impl MessageHandler> for Portfolio data_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Data) && !self.workspace.panel_layout.focus_document, layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document, inspector_open: self.workspace.panel_layout.is_panel_visible(PanelType::Inspector) && !self.workspace.panel_layout.focus_document, + palette_open: self.workspace.panel_layout.is_panel_visible(PanelType::Palette) && !self.workspace.panel_layout.focus_document, }; document.process_message(message, responses, document_inputs); refresh_transaction_edited_nodes(document, true, responses); @@ -206,6 +207,7 @@ impl MessageHandler> for Portfolio data_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Data) && !self.workspace.panel_layout.focus_document, layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document, inspector_open: self.workspace.panel_layout.is_panel_visible(PanelType::Inspector) && !self.workspace.panel_layout.focus_document, + palette_open: self.workspace.panel_layout.is_panel_visible(PanelType::Palette) && !self.workspace.panel_layout.focus_document, }; document.process_message(message, responses, document_inputs); refresh_transaction_edited_nodes(document, self.active_document_id == Some(document_id), responses); From e775d1812e6822715add812ca0b7fe5af6288658 Mon Sep 17 00:00:00 2001 From: VimYoung Date: Mon, 26 Oct 2026 16:17:55 +0530 Subject: [PATCH 03/15] Add: (Broken) Wiring for showing frontend in the Palette tab --- .../layout/utility_types/layout_widget.rs | 2 + .../document/document_message_handler.rs | 1 + .../document/palette/palette_message.rs | 3 +- .../palette/palette_message_handler.rs | 44 +++- .../workspace/workspace_message_handler.rs | 5 +- frontend/src/components/panels/Palette.svelte | 241 ++++++++++++++++++ frontend/src/components/window/Panel.svelte | 2 + frontend/src/stores/portfolio.ts | 4 + 8 files changed, 297 insertions(+), 5 deletions(-) create mode 100644 frontend/src/components/panels/Palette.svelte diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 0ad9d897123..8186331d0a4 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -70,6 +70,8 @@ define_layout_target!( LayersPanelBottomRightBar, /// Blending options at the top of the Layers panel. LayersPanelControlLeftBar, + // Main Palette section for editing, adding colors and using palettes. + Palette, /// Adding palette, naming/editing the palette PalettePanelBottomRightBar, /// Showcasing currently focused active palette diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 56ae8ccf075..e3cc1e69e00 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -1505,6 +1505,7 @@ impl MessageHandler> for DocumentMes PanelType::Layers => self.selection_network_path = vec![], _ => {} } + responses.add(PaletteMessage::Refresh); responses.add(InspectorMessage::Refresh); responses.add(NodeGraphMessage::UpdateLayerPanel); responses.add(NodeGraphMessage::UpdateInSelectedNetwork); diff --git a/editor/src/messages/portfolio/document/palette/palette_message.rs b/editor/src/messages/portfolio/document/palette/palette_message.rs index ec7ef5276bf..f5aa00b4c27 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message.rs @@ -3,5 +3,6 @@ use crate::messages::prelude::*; #[impl_message(Message, DocumentMessage, Palette)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum PaletteMessage { - UploadPalette, + Refresh, + Upload, } diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index 74aca42586a..882abb48775 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -1,3 +1,6 @@ +use graphene_std::vector::style::FillChoice; + +use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::prelude::*; @@ -12,8 +15,19 @@ pub struct PaletteMessageHandler {} #[message_handler_data] impl MessageHandler for PaletteMessageHandler { fn process_message(&mut self, message: PaletteMessage, responses: &mut VecDeque, context: PaletteMessageContext) { + let PaletteMessageContext { palette_open } = context; match message { - PaletteMessage::UploadPalette => todo!(), + PaletteMessage::Refresh => { + if !palette_open { + return; + } + + // TODO: Attach strings for selected active color/palette + // Make use of context for getting info if there exists an + // active attached color from a palette. + PaletteMessageHandler::refresh_palette(palette_open, responses); + } + PaletteMessage::Upload => todo!(), } } @@ -21,3 +35,31 @@ impl MessageHandler for PaletteMessageHan actions!(PaletteMessage;) } } + +impl PaletteMessageHandler { + pub fn refresh_palette(palette_panel_open: bool, responses: &mut VecDeque) { + if !palette_panel_open { + return; + } + + let widgets = vec![ + LayoutGroup::row(vec![TextLabel::new("Khaki Palette").multiline(true).center_align(false).widget_instance()]), + LayoutGroup::table( + vec![vec![ + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + ColorInput::new(FillChoice::None).widget_instance(), + ColorInput::new(FillChoice::None).widget_instance(), + ColorInput::new(FillChoice::None).widget_instance(), + ColorInput::new(FillChoice::None).widget_instance(), + ColorInput::new(FillChoice::None).widget_instance(), + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + ]], + true, + ), + ]; + responses.add(LayoutMessage::SendLayout { + layout: Layout(widgets), + layout_target: LayoutTarget::Palette, + }); + } +} diff --git a/editor/src/messages/portfolio/workspace/workspace_message_handler.rs b/editor/src/messages/portfolio/workspace/workspace_message_handler.rs index 1b5e05711d7..19375210200 100644 --- a/editor/src/messages/portfolio/workspace/workspace_message_handler.rs +++ b/editor/src/messages/portfolio/workspace/workspace_message_handler.rs @@ -1,4 +1,5 @@ use crate::messages::layout::utility_types::layout_widget::LayoutTarget; +use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::portfolio::persistent_state::PersistentStateMessage; use crate::messages::portfolio::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout}; use crate::messages::prelude::*; @@ -427,9 +428,7 @@ impl WorkspaceMessageHandler { // The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here } PanelType::Palette => { - // TODO: Add update functionality if a connected node with palette - // triggers a color change event, that should be reflected back - // in the palette panel + responses.add(PaletteMessage::Refresh); } PanelType::Document | PanelType::Welcome => { // Re-send the welcome screen buttons layout to repopulate after a remount diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte new file mode 100644 index 00000000000..9f84a897328 --- /dev/null +++ b/frontend/src/components/panels/Palette.svelte @@ -0,0 +1,241 @@ + + + + + + {#if dragging && insertMarker} +
+ {/if} +
+
+ + diff --git a/frontend/src/components/window/Panel.svelte b/frontend/src/components/window/Panel.svelte index c6ed042aece..c17359f3490 100644 --- a/frontend/src/components/window/Panel.svelte +++ b/frontend/src/components/window/Panel.svelte @@ -6,6 +6,7 @@ import Document from "/src/components/panels/Document.svelte"; import Inspector from "/src/components/panels/Inspector.svelte"; import Layers from "/src/components/panels/Layers.svelte"; + import Palette from "/src/components/panels/Palette.svelte"; import Welcome from "/src/components/panels/Welcome.svelte"; import IconButton from "/src/components/widgets/buttons/IconButton.svelte"; import TextLabel from "/src/components/widgets/labels/TextLabel.svelte"; @@ -19,6 +20,7 @@ Layers, Inspector, Data, + Palette, }; const BUTTON_LEFT = 0; const BUTTON_MIDDLE = 1; diff --git a/frontend/src/stores/portfolio.ts b/frontend/src/stores/portfolio.ts index 59f5ad4ddaf..2542f72ffb2 100644 --- a/frontend/src/stores/portfolio.ts +++ b/frontend/src/stores/portfolio.ts @@ -39,6 +39,7 @@ const { subscribe, update } = store; export const welcomeScreenButtonsLayout = persistedLayout("welcomeScreenButtonsLayout"); export const inspectorLayout = persistedLayout("inspectorLayout"); +export const paletteLayout = persistedLayout("paletteLayout"); export const dataPanelLayout = persistedLayout("dataPanelLayout"); export const dataPanelContextLayout = persistedLayout("dataPanelContextLayout"); export const dataPanelPathLayout = persistedLayout("dataPanelPathLayout"); @@ -144,6 +145,8 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor: subscriptions.subscribeLayoutUpdate("DataPanelPath", (data) => { patchLayout(dataPanelPathLayout, data); + subscriptions.subscribeLayoutUpdate("Palette", (data) => { + patchLayout(paletteLayout, data); }); subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => { @@ -206,6 +209,7 @@ export function destroyPortfolioStore() { subscriptions.unsubscribeFrontendMessage("UpdateWorkspacePanelLayout"); subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons"); subscriptions.unsubscribeLayoutUpdate("Inspector"); + subscriptions.unsubscribeLayoutUpdate("Palette"); subscriptions.unsubscribeLayoutUpdate("DataPanel"); subscriptions.unsubscribeLayoutUpdate("DataPanelContext"); subscriptions.unsubscribeLayoutUpdate("DataPanelPath"); From 1c3bcb159edaefc11857fe38b7b3f5c013df2f32 Mon Sep 17 00:00:00 2001 From: VimYoung Date: Wed, 28 Oct 2026 11:48:26 +0530 Subject: [PATCH 04/15] Fix: Minor name change and import resolution --- editor/src/dispatcher.rs | 2 +- editor/src/messages/menu_bar/menu_bar_message_handler.rs | 4 ++-- .../messages/portfolio/document/document_message_handler.rs | 2 +- .../portfolio/document/palette/palette_message_handler.rs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index ca9fcaf3695..f8c6a3dfdad 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -307,7 +307,7 @@ impl Dispatcher { menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data); menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers); menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector); - menu_bar_message_handler.palette_panel_open = layout.is_panel_present(PanelType::Palette); + menu_bar_message_handler.palette_open = layout.is_panel_present(PanelType::Palette); menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity; menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open; menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences; diff --git a/editor/src/messages/menu_bar/menu_bar_message_handler.rs b/editor/src/messages/menu_bar/menu_bar_message_handler.rs index e53d9c97177..c3ff6523559 100644 --- a/editor/src/messages/menu_bar/menu_bar_message_handler.rs +++ b/editor/src/messages/menu_bar/menu_bar_message_handler.rs @@ -26,7 +26,7 @@ pub struct MenuBarMessageHandler { pub data_panel_open: bool, pub layers_panel_open: bool, pub inspector_open: bool, - pub palette_panel_open: bool, + pub palette_open: bool, pub focus_document: bool, } @@ -684,7 +684,7 @@ impl LayoutHolder for MenuBarMessageHandler { .disabled(self.focus_document), MenuListEntry::new("Palette") .label("Palette") - .icon(if self.palette_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" }) + .icon(if self.palette_open { "CheckboxChecked" } else { "CheckboxUnchecked" }) .tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::TogglePalettePanelOpen)) .on_commit(|_| WorkspaceMessage::TogglePalettePanelOpen.into()) .disabled(self.focus_document), diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index e3cc1e69e00..ecd51485082 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -21,8 +21,8 @@ use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay, overlay_options}; use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot}; -use crate::messages::portfolio::document::palette::PaletteMessageHandler; use crate::messages::portfolio::document::palette::palette_message_handler::PaletteMessageContext; +use crate::messages::portfolio::document::palette::{PaletteMessage, PaletteMessageHandler}; use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier}; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector}; diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index 882abb48775..fee0c6d2c40 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -37,8 +37,8 @@ impl MessageHandler for PaletteMessageHan } impl PaletteMessageHandler { - pub fn refresh_palette(palette_panel_open: bool, responses: &mut VecDeque) { - if !palette_panel_open { + pub fn refresh_palette(palette_open: bool, responses: &mut VecDeque) { + if !palette_open { return; } From a3db3fa3c7501d3b3e8fa2959f485a57b4efd97e Mon Sep 17 00:00:00 2001 From: VimYoung Date: Sun, 1 Nov 2026 18:09:55 +0530 Subject: [PATCH 05/15] Add: Default palettes in case no palette is attached; early UI mockup addition --- .../palette/palette_message_handler.rs | 75 +++++++++++++------ .../portfolio/portfolio_message_handler.rs | 5 ++ frontend/src/components/panels/Palette.svelte | 12 +-- frontend/src/stores/portfolio.ts | 2 + 4 files changed, 63 insertions(+), 31 deletions(-) diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index fee0c6d2c40..b9141d50ae1 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -1,9 +1,45 @@ +use graphene_std::color::SRGBA8; use graphene_std::vector::style::FillChoice; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::prelude::*; +pub const DEFAULT_PALETTES: [(&str, u32, &[SRGBA8]); 2] = [ + ( + "Warm Landscape", + 5, + &[ + SRGBA8::new_opaque(0x26, 0x46, 0x53), + SRGBA8::new_opaque(0x2A, 0x9D, 0x8F), + SRGBA8::new_opaque(0xE9, 0xC4, 0x6A), + SRGBA8::new_opaque(0xF4, 0xA2, 0x61), + SRGBA8::new_opaque(0xE7, 0x6F, 0x51), + SRGBA8::new_opaque(0xD6, 0x28, 0x28), + SRGBA8::new_opaque(0x00, 0x30, 0x49), + SRGBA8::new_opaque(0xF7, 0x7F, 0x00), + SRGBA8::new_opaque(0xFC, 0xBF, 0x49), + SRGBA8::new_opaque(0xEA, 0xE2, 0xB7), + ], + ), + ( + "Nordic Frost", + 3, + &[ + SRGBA8::new_opaque(0x2E, 0x34, 0x40), + SRGBA8::new_opaque(0x3B, 0x42, 0x52), + SRGBA8::new_opaque(0x43, 0x4C, 0x5E), + SRGBA8::new_opaque(0x4C, 0x56, 0x6A), + SRGBA8::new_opaque(0xD8, 0xDE, 0xE9), + SRGBA8::new_opaque(0xE5, 0xE9, 0xF0), + SRGBA8::new_opaque(0xEC, 0xEF, 0xF4), + SRGBA8::new_opaque(0x88, 0xC0, 0xD0), + SRGBA8::new_opaque(0x81, 0xA1, 0xC1), + SRGBA8::new_opaque(0x5E, 0x81, 0xAC), + ], + ), +]; + #[derive(ExtractField)] pub struct PaletteMessageContext { pub palette_open: bool, @@ -22,10 +58,7 @@ impl MessageHandler for PaletteMessageHan return; } - // TODO: Attach strings for selected active color/palette - // Make use of context for getting info if there exists an - // active attached color from a palette. - PaletteMessageHandler::refresh_palette(palette_open, responses); + PaletteMessageHandler::refresh_palette(responses); } PaletteMessage::Upload => todo!(), } @@ -37,26 +70,24 @@ impl MessageHandler for PaletteMessageHan } impl PaletteMessageHandler { - pub fn refresh_palette(palette_open: bool, responses: &mut VecDeque) { - if !palette_open { - return; + pub fn refresh_palette(responses: &mut VecDeque) { + // TODO: Add Conditional to load palette from the open document's interface + // If none is present or it is a new document load the Default. + let mut widgets = Vec::new(); + + for &(name, columns, colors) in &DEFAULT_PALETTES { + widgets.push(LayoutGroup::row(vec![TextLabel::new(name).bold(true).widget_instance()])); + + let mut table_rows = Vec::new(); + for chunk in colors.chunks(columns as usize) { + let row = chunk.iter().map(|&color| ColorInput::new(FillChoice::Solid(color)).widget_instance()).collect(); + table_rows.push(row); + } + + widgets.push(LayoutGroup::table(table_rows, false)); + widgets.push(LayoutGroup::row(vec![Separator::new(SeparatorStyle::Section).widget_instance()])); } - let widgets = vec![ - LayoutGroup::row(vec![TextLabel::new("Khaki Palette").multiline(true).center_align(false).widget_instance()]), - LayoutGroup::table( - vec![vec![ - Separator::new(SeparatorStyle::Unrelated).widget_instance(), - ColorInput::new(FillChoice::None).widget_instance(), - ColorInput::new(FillChoice::None).widget_instance(), - ColorInput::new(FillChoice::None).widget_instance(), - ColorInput::new(FillChoice::None).widget_instance(), - ColorInput::new(FillChoice::None).widget_instance(), - Separator::new(SeparatorStyle::Unrelated).widget_instance(), - ]], - true, - ), - ]; responses.add(LayoutMessage::SendLayout { layout: Layout(widgets), layout_target: LayoutTarget::Palette, diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index 70ce3cd428e..3762b79685d 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -13,6 +13,7 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::DocumentMessageContext; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::node_graph::document_node_definitions; +use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::portfolio::document_storage_io::{ DocumentStoreHandle, attach_container, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, open_storage, remove_stored_document, }; @@ -1228,6 +1229,10 @@ impl PortfolioMessageHandler { responses.add(ToolMessage::DeactivateTools); } + if self.workspace.panel_layout.is_panel_visible(PanelType::Palette) { + responses.add(PaletteMessage::Refresh) + } + // TODO: Remove this and find a way to fix the issue where creating a new document when the node graph is open causes the transform in the new document to be incorrect responses.add(DocumentMessage::GraphViewOverlay { open: false }); if is_new_document { diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte index 9f84a897328..25d04cb2e8c 100644 --- a/frontend/src/components/panels/Palette.svelte +++ b/frontend/src/components/panels/Palette.svelte @@ -9,6 +9,7 @@ import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; const _editor = getContext("editor"); + const portfolio = getContext("palette"); let sectionsCol: LayoutCol | undefined; @@ -16,8 +17,6 @@ type DragState = { nodeId: bigint; startX: number; startY: number; active: boolean }; let dragState: DragState | undefined = undefined; let dragging = false; - let fromIndex: number | undefined = undefined; - let insertIndex: number | undefined = undefined; let insertMarker: { top: number; left: number; width: number } | undefined = undefined; let justFinishedDrag = false; // Used to suppress the click event that follows a drag release (which would otherwise toggle a section) @@ -94,7 +93,6 @@ dragState.active = true; dragging = true; - fromIndex = reorderableSections().findIndex((section) => section.getAttribute("data-node-id") === String(dragState?.nodeId)); } lastDragClientY = e.clientY; @@ -108,7 +106,6 @@ const container = sectionsCol?.div(); const sections = reorderableSections(); if (!container || sections.length === 0) { - insertIndex = undefined; insertMarker = undefined; return; } @@ -143,7 +140,6 @@ // Spanning the sections, which a layer's frame around them indents const firstRect = sections[0].getBoundingClientRect(); - insertIndex = index; insertMarker = { top: toContentOffset(markerViewportY), left: firstRect.left - containerRect.left, width: firstRect.width }; } @@ -182,14 +178,13 @@ autoScroller.stop(); dragState = undefined; dragging = false; - fromIndex = undefined; - insertIndex = undefined; insertMarker = undefined; } + {#if dragging && insertMarker}
@@ -201,11 +196,11 @@ .palette { height: 100%; flex: 1 1 100%; + margin: 0.5rem; .sections { flex: 1 1 100%; position: relative; - padding-top: 4px; // While dragging a section, disable pointer events (which inherit down to the sections) so the drop doesn't toggle a section's expansion, and prevent text selection &.dragging { @@ -215,7 +210,6 @@ // Used as a placeholder for empty assist widgets .separator.section.horizontal { - margin: 0; margin-left: 24px; div { diff --git a/frontend/src/stores/portfolio.ts b/frontend/src/stores/portfolio.ts index 2542f72ffb2..11e49caa436 100644 --- a/frontend/src/stores/portfolio.ts +++ b/frontend/src/stores/portfolio.ts @@ -145,6 +145,8 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor: subscriptions.subscribeLayoutUpdate("DataPanelPath", (data) => { patchLayout(dataPanelPathLayout, data); + }); + subscriptions.subscribeLayoutUpdate("Palette", (data) => { patchLayout(paletteLayout, data); }); From 1a7231887440303be374acb613d4a9d0260ab19a Mon Sep 17 00:00:00 2001 From: VimYoung Date: Mon, 2 Nov 2026 11:15:46 +0530 Subject: [PATCH 06/15] Add: Appropriate data structure representation for Palette and Swatch --- .../document/palette/palette_message.rs | 7 +- .../palette/palette_message_handler.rs | 148 +++++++++++++++--- 2 files changed, 134 insertions(+), 21 deletions(-) diff --git a/editor/src/messages/portfolio/document/palette/palette_message.rs b/editor/src/messages/portfolio/document/palette/palette_message.rs index f5aa00b4c27..8fdbc3832ed 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message.rs @@ -1,8 +1,13 @@ use crate::messages::prelude::*; +use graphene_std::color::SRGBA8; #[impl_message(Message, DocumentMessage, Palette)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum PaletteMessage { + ActivePaletteChanged { id: u64 }, + PaletteNameChange { id: u64, name: String }, + AddColor { color: SRGBA8 }, + DeleteColor { swatch_id: u64 }, Refresh, - Upload, + UploadFromFile, } diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index b9141d50ae1..239a25c52b7 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -1,10 +1,14 @@ -use graphene_std::color::SRGBA8; +use crate::application::generate_uuid; use graphene_std::vector::style::FillChoice; +use graphene_std::{Color, color::SRGBA8}; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::prelude::*; +use serde::{Deserialize, Serialize}; +// TODO: Ig this should be imported from some preloaded assets file after the +// implementation of import from file feature. pub const DEFAULT_PALETTES: [(&str, u32, &[SRGBA8]); 2] = [ ( "Warm Landscape", @@ -40,13 +44,86 @@ pub const DEFAULT_PALETTES: [(&str, u32, &[SRGBA8]); 2] = [ ), ]; +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +pub struct PaletteId(pub u64); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +pub struct SwatchId(pub u64); + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +pub struct ColorSwatch { + pub id: SwatchId, + pub name: String, + pub color: Color, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +pub struct Palette { + pub id: PaletteId, + pub name: String, + // Palette specification where it can be 0 or None in which case the UI will flow + // the palettes accordingly + pub columns: Option, + pub grid: Vec>, + pub swatches: HashMap, +} + #[derive(ExtractField)] pub struct PaletteMessageContext { pub palette_open: bool, } -#[derive(Debug, Clone, Default, ExtractField)] -pub struct PaletteMessageHandler {} +#[derive(Debug, Clone, ExtractField)] +pub struct PaletteMessageHandler { + // At any moment in time at least one palette should be open in the palette section + pub active_palette: PaletteId, + pub order: Vec, + pub palettes: HashMap, +} + +impl Default for PaletteMessageHandler { + fn default() -> Self { + let mut palettes = HashMap::new(); + let mut order = Vec::new(); + for &(name, columns, colors) in &DEFAULT_PALETTES { + let mut grid = Vec::new(); + let mut swatches = HashMap::new(); + for color in colors { + let id = SwatchId { 0: generate_uuid() }; + grid.push(Some(id)); + swatches.insert( + id, + ColorSwatch { + id, + name: "Some Color".to_string(), + color: (*color).into(), + }, + ); + } + let palette_id = PaletteId { 0: generate_uuid() }; + order.push(palette_id); + palettes.insert( + palette_id, + Palette { + id: PaletteId { 0: generate_uuid() }, + name: name.to_string(), + columns: Some(columns), + grid, + swatches, + }, + ); + } + Self { + active_palette: order[0], + order, + palettes, + } + } +} #[message_handler_data] impl MessageHandler for PaletteMessageHandler { @@ -58,9 +135,13 @@ impl MessageHandler for PaletteMessageHan return; } - PaletteMessageHandler::refresh_palette(responses); + self.refresh_palette(responses); } - PaletteMessage::Upload => todo!(), + PaletteMessage::UploadFromFile => todo!(), + PaletteMessage::ActivePaletteChanged { id } => todo!(), + PaletteMessage::PaletteNameChange { id, name } => todo!(), + PaletteMessage::AddColor { color } => todo!(), + PaletteMessage::DeleteColor { swatch_id } => todo!(), } } @@ -70,27 +151,54 @@ impl MessageHandler for PaletteMessageHan } impl PaletteMessageHandler { - pub fn refresh_palette(responses: &mut VecDeque) { + pub fn refresh_palette(&self, responses: &mut VecDeque) { // TODO: Add Conditional to load palette from the open document's interface // If none is present or it is a new document load the Default. - let mut widgets = Vec::new(); + if true { + let mut widgets = Vec::new(); - for &(name, columns, colors) in &DEFAULT_PALETTES { - widgets.push(LayoutGroup::row(vec![TextLabel::new(name).bold(true).widget_instance()])); + for palette_id in self.order.iter() { + let Palette { id: _, name, columns, grid, swatches } = self.palettes.get(palette_id).unwrap(); + widgets.push(LayoutGroup::row(vec![TextLabel::new(name).bold(true).widget_instance()])); + + let mut table_rows = Vec::new(); + if let Some(columns) = columns { + for chunk in grid.chunks(*columns as usize) { + let row = chunk + .iter() + .map(|&id| { + if let Some(swatch_id) = id { + let swatch = swatches.get(&swatch_id).unwrap(); + ColorInput::new(FillChoice::Solid(swatch.color.into())) + .narrow(true) + .tooltip_label(swatch.name.clone()) + .widget_instance() + // .on_update(|input: &ColorInput| { + // let ramp = input.value.as_gradient().cloned().unwrap_or_default(); + // GradientToolMessage::UpdateRamp { ramp }.into() + // }) + // .on_commit(|_| DocumentMessage::AddTransaction.into()) + } else { + ColorInput::new(FillChoice::None).widget_instance() + } + }) + .collect(); + table_rows.push(row); + } + } else { + //TODO: Manage the case when the column size is not determined + } - let mut table_rows = Vec::new(); - for chunk in colors.chunks(columns as usize) { - let row = chunk.iter().map(|&color| ColorInput::new(FillChoice::Solid(color)).widget_instance()).collect(); - table_rows.push(row); + widgets.push(LayoutGroup::table(table_rows, false)); + widgets.push(LayoutGroup::row(vec![Separator::new(SeparatorStyle::Section).widget_instance()])); } - widgets.push(LayoutGroup::table(table_rows, false)); - widgets.push(LayoutGroup::row(vec![Separator::new(SeparatorStyle::Section).widget_instance()])); + responses.add(LayoutMessage::SendLayout { + layout: Layout(widgets), + layout_target: LayoutTarget::Palette, + }); + } else { + // TODO: Add attached palettes instead } - - responses.add(LayoutMessage::SendLayout { - layout: Layout(widgets), - layout_target: LayoutTarget::Palette, - }); } } From 1352c058a144edf6b597d5ceab8fd622c57466f1 Mon Sep 17 00:00:00 2001 From: VimYoung Date: Mon, 2 Nov 2026 21:09:42 +0530 Subject: [PATCH 07/15] Add: Bottom Bar for Palette Added --- .../portfolio/document/palette/palette_message_handler.rs | 5 +++++ frontend/src/components/panels/Palette.svelte | 3 +++ frontend/src/stores/portfolio.ts | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index 239a25c52b7..7213c9772f1 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -192,11 +192,16 @@ impl PaletteMessageHandler { widgets.push(LayoutGroup::table(table_rows, false)); widgets.push(LayoutGroup::row(vec![Separator::new(SeparatorStyle::Section).widget_instance()])); } + let left_bottom_bar = LayoutGroup::row(vec![TextLabel::new("Hello").widget_instance()]); responses.add(LayoutMessage::SendLayout { layout: Layout(widgets), layout_target: LayoutTarget::Palette, }); + responses.add(LayoutMessage::SendLayout { + layout: Layout(vec![left_bottom_bar]), + layout_target: LayoutTarget::PalettePanelBottomLeftBar, + }); } else { // TODO: Add attached palettes instead } diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte index 25d04cb2e8c..32b60cdd71e 100644 --- a/frontend/src/components/panels/Palette.svelte +++ b/frontend/src/components/panels/Palette.svelte @@ -190,6 +190,9 @@
{/if}
+ + +
diff --git a/frontend/src/components/panels/Data.svelte b/frontend/src/components/panels/Data.svelte index 92a9fc3b135..9aa281d6881 100644 --- a/frontend/src/components/panels/Data.svelte +++ b/frontend/src/components/panels/Data.svelte @@ -1,8 +1,12 @@ @@ -15,7 +19,7 @@ - + editor.setDataPanelRowsInView(start, end)} /> @@ -38,6 +42,11 @@ .context > :first-child { margin-left: auto; } + + // Without any context to show, the path has the whole width + .context:not(:has(.widget-span)) { + display: none; + } } // Within the scrolling area, so the table's gutter can reach its edges without overflowing diff --git a/frontend/src/components/panels/Document.svelte b/frontend/src/components/panels/Document.svelte index 16753fa1428..6dc83a972a4 100644 --- a/frontend/src/components/panels/Document.svelte +++ b/frontend/src/components/panels/Document.svelte @@ -5,6 +5,7 @@ import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutRow from "/src/components/layout/LayoutRow.svelte"; import Graph from "/src/components/views/Graph.svelte"; + import RemoteCursor from "/src/components/views/RemoteCursor.svelte"; import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte"; import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte"; import TextLabel from "/src/components/widgets/labels/TextLabel.svelte"; @@ -14,7 +15,6 @@ import type { SubscriptionsRouter } from "/src/subscriptions-router"; import type { MessageBody } from "/src/subscriptions-router"; import { fillChoiceColor, createSRgba8, sRgba8FromCSS } from "/src/utility-functions/colors"; - import { pasteFile } from "/src/utility-functions/files"; import { cleanupInputField } from "/src/utility-functions/input"; import { textInputCleanup } from "/src/utility-functions/keyboard-entry"; import { rasterizeSVGCanvas } from "/src/utility-functions/rasterization"; @@ -30,6 +30,7 @@ const editor = getContext("editor"); const appWindow = getContext("appWindow"); const document = getContext("document"); + const remoteCursors = document.remoteCursorsStore; // Interactive text editing let textInput: undefined | HTMLDivElement = undefined; @@ -88,7 +89,6 @@ let canvasWidth: number | undefined = undefined; let canvasHeight: number | undefined = undefined; - let devicePixelRatio: number | undefined; let removeUpdatePixelRatio: (() => void) | undefined; let viewportResizeObserver: ResizeObserver | undefined; let cleanupViewportResizeObserver: (() => void) | undefined; @@ -102,13 +102,6 @@ $: canvasWidthCSS = canvasWidthRoundedToEven ? `${canvasWidthRoundedToEven}px` : "100%"; $: canvasHeightCSS = canvasHeightRoundedToEven ? `${canvasHeightRoundedToEven}px` : "100%"; - $: canvasWidthScaled = canvasWidth && devicePixelRatio && Math.floor(canvasWidth * devicePixelRatio); - $: canvasHeightScaled = canvasHeight && devicePixelRatio && Math.floor(canvasHeight * devicePixelRatio); - - // Used to set the canvas rendering dimensions. - $: canvasWidthScaledRoundedToEven = canvasWidthScaled && (canvasWidthScaled % 2 === 1 ? canvasWidthScaled + 1 : canvasWidthScaled); - $: canvasHeightScaledRoundedToEven = canvasHeightScaled && (canvasHeightScaled % 2 === 1 ? canvasHeightScaled + 1 : canvasHeightScaled); - $: toolShelfTotalToolsAndSeparators = ((layoutGroup) => { if (!layoutGroup || !("Row" in layoutGroup)) return undefined; @@ -148,7 +141,7 @@ e.preventDefault(); - Array.from(e.dataTransfer.items).forEach(async (item) => await pasteFile(item, editor, mouse)); + editor.ingest(e.dataTransfer, mouse?.[0], mouse?.[1]); } function panCanvasX(newValue: number) { @@ -453,7 +446,6 @@ canvasWidth = Math.ceil(parseFloat(getComputedStyle(viewport).width)); canvasHeight = Math.ceil(parseFloat(getComputedStyle(viewport).height)); - devicePixelRatio = window.devicePixelRatio || 1; viewportBounds = viewport.getBoundingClientRect(); // Resize the rulers @@ -713,6 +705,9 @@ bind:this={viewport} data-viewport > + {#each $remoteCursors as cursor} + + {/each} {#if !$appWindow.viewportHolePunch} {@html artworkSvg} @@ -723,17 +718,6 @@
{/if} - {#if !$appWindow.viewportHolePunch} - - - {/if} {#if isWeb && $document.renderStatus === "Rendering"} Initializing Renderer… {/if} @@ -954,8 +938,7 @@ overflow: hidden; .artwork, - .text-input, - .overlays { + .text-input { position: absolute; top: 0; // Fallback values if JS hasn't set these to integers yet diff --git a/frontend/src/components/panels/History.svelte b/frontend/src/components/panels/History.svelte new file mode 100644 index 00000000000..42caeefaa98 --- /dev/null +++ b/frontend/src/components/panels/History.svelte @@ -0,0 +1,427 @@ + + + + {#if $history.following} + + Viewing a branch + editor.followHistoryBranch(undefined)} /> + + {/if} + + {#each $history.progress as row, index} + +
+ + + {#if $history.collaborating}{/if} +
+ {row.label || (row.open ? "In Progress" : "Waiting to Enter History")} + + {#if $history.collaborating}{authorLabel(row)} ·{/if} + {count(row.ops, "change", "changes")} + {#if $history.collaborating}· {row.open ? "in progress" : "not yet in history"}{/if} + + {#if pendingHead && index === 0} + Current + {/if} +
+
+ {/each} + {#each $history.rows as row (row.id)} +
+ {#if row.deltas > 1} + + {:else} + + {/if} + {#if $history.collaborating || !row.mine}{/if} +
+ {#if renamingId === row.id} + (renamingId = undefined)}> + commitName(row.id, detail)} /> + + {:else} + {row.label} + {/if} + + {#if $history.collaborating || !row.mine}{authorLabel(row)} ·{/if} + {#if row.time}{when(row.time, now)} ·{/if} + {count(row.deltas, "change", "changes")} + + {#if row.tags.length > 0 || taggingId === row.id || (row.head && !pendingHead) || row.undone || row.abandoned} + + {#if row.head && !pendingHead}Current{/if} + {#if row.undone}Undone{/if} + {#if row.abandoned}Branch{/if} + {#each row.tags as tag (tag)} + {tag} + {/each} + {#if taggingId === row.id} + (taggingId = undefined)}> + commitTag(row.id, detail)} /> + + {/if} + + {/if} + {#if row.branches.length > 0} + + {#each row.branches as branch (branch.id)} + + {/each} + + {/if} +
+ + + + {#if row.undone || row.abandoned} + editor.bringBackHistoryInteraction(row.id)} + /> + {:else} + {#if !row.head} + editor.goBackToHistoryInteraction(row.id)} + /> + {/if} + editor.removeHistoryInteraction(row.id)} + /> + {/if} + +
+ {#if row.expanded} + {#each row.details as delta (delta.id)} +
+ + +
+ {delta.label} + + {#if $history.collaborating || !delta.mine}{delta.author}{/if} + {#if delta.time && when(delta.time, now) !== when(row.time, now)}{$history.collaborating || !delta.mine ? "· " : ""}{when(delta.time, now)}{/if} + +
+
+ {/each} + {/if} + {/each} + {#if $history.more} +
+ editor.loadMoreHistory()} /> +
+ {/if} + {#if $portfolio.documents.length > 0 && $history.rows.length === 0 && $history.progress.length === 0} + Nothing in the history yet. + {/if} +
+
+ + diff --git a/frontend/src/components/panels/Layers.svelte b/frontend/src/components/panels/Layers.svelte index 02cb6accd01..935c5fc6e36 100644 --- a/frontend/src/components/panels/Layers.svelte +++ b/frontend/src/components/panels/Layers.svelte @@ -13,7 +13,6 @@ import type { PortfolioStore } from "/src/stores/portfolio"; import type { TooltipStore } from "/src/stores/tooltip"; import { createAutoScroller, speedWhileAimingAt } from "/src/utility-functions/auto-scroll"; - import { pasteFile } from "/src/utility-functions/files"; import { targetIsTextField } from "/src/utility-functions/input"; import { operatingSystem } from "/src/utility-functions/platform"; import type { EditorWrapper, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry, LayerStructureEntry } from "/wrapper/pkg/graphite_wasm_wrapper"; @@ -1091,7 +1090,7 @@ e.preventDefault(); - Array.from(e.dataTransfer.items).forEach(async (item) => await pasteFile(item, editor, undefined, insertParentId, insertIndex)); + editor.ingest(e.dataTransfer, undefined, undefined, insertParentId, insertIndex); draggingData = undefined; fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined; diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte index 6b8d6eb4a25..11388b4a56d 100644 --- a/frontend/src/components/panels/Palette.svelte +++ b/frontend/src/components/panels/Palette.svelte @@ -10,7 +10,6 @@ import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; const _editor = getContext("editor"); - const portfolio = getContext("palette"); let sectionsCol: LayoutCol | undefined; @@ -58,11 +57,14 @@ function editPaletteName(e: MouseEvent) { const target = e.target instanceof Element ? e.target : undefined; + // eslint-disable-next-line graphite/require-data-selectors const label = target?.closest(".widget-span.row:has(> .text-label + .text-input + .text-button) > .text-label"); const row = label?.parentElement; if (!label || !row) return; + // eslint-disable-next-line graphite/require-data-selectors const field = row.querySelector(":scope > .text-input"); if (!field || !row) return; + // eslint-disable-next-line graphite/require-data-selectors const input = field.querySelector("input"); if (!input) return; @@ -73,10 +75,13 @@ input.select(); } - function finishPaletteNameEdit(target: EventTarget | null) { + function finishPaletteNameEdit(target: EventTarget | undefined) { const element = target instanceof Element ? target : undefined; + // eslint-disable-next-line graphite/require-data-selectors const row = element?.closest(".widget-span.row.palette-name-editing"); + // eslint-disable-next-line graphite/require-data-selectors const field = row?.querySelector(":scope > .text-input"); + // eslint-disable-next-line graphite/require-data-selectors const input = field?.querySelector("input"); if (!row || !field || !input) return; @@ -85,8 +90,9 @@ input.disabled = true; } - function paletteNameKeyDown(e: KeyboardEvent) { - if (e.key === "Enter") finishPaletteNameEdit(e.target); + function paletteNameKeyDown(e: CustomEvent) { + const key = e.detail?.key; + if (key === "Enter") finishPaletteNameEdit(e.target instanceof Element ? e.target : undefined); } function reorderableSections(): Element[] { @@ -224,7 +230,7 @@ bind:this={sectionsCol} on:pointerdown={sectionPointerDown} on:dblclick={editPaletteName} - on:focusout={(e) => finishPaletteNameEdit(e.target)} + on:focusout={(e) => finishPaletteNameEdit(e.target ?? undefined)} on:keydown={paletteNameKeyDown} > @@ -393,42 +399,6 @@ &:not(:has(*)) { display: none; } - - // While dragging, buttons are grayed out unless they accept the kind of item being dragged - &.layer-drag-active, - &.chain-node-drag-active { - .icon-button, - .popover-button { - pointer-events: none; - background: none; - - svg { - fill: var(--color-8-uppergray); - } - } - } - - // Dropped items become the selection before the button acts, so a button disabled for the current selection still accepts them - &.layer-drag-active .icon-button[data-drag-droppable~="layers"], - &.chain-node-drag-active .icon-button[data-drag-droppable~="chain-nodes"] { - pointer-events: auto; - - svg { - fill: var(--color-e-nearwhite); - } - - &:hover { - background: var(--color-e-nearwhite); - - svg { - fill: var(--color-2-mildblack); - } - } - } - } - - .text-button { - flex-basis: 0; } } diff --git a/frontend/src/components/panels/Welcome.svelte b/frontend/src/components/panels/Welcome.svelte index 9c5cd4af1c3..cec18661c7b 100644 --- a/frontend/src/components/panels/Welcome.svelte +++ b/frontend/src/components/panels/Welcome.svelte @@ -6,7 +6,6 @@ import TextLabel from "/src/components/widgets/labels/TextLabel.svelte"; import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; import { welcomeScreenButtonsLayout } from "/src/stores/portfolio"; - import { pasteFile } from "/src/utility-functions/files"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; const editor = getContext("editor"); @@ -16,7 +15,7 @@ e.preventDefault(); - Array.from(e.dataTransfer.items).forEach(async (item) => await pasteFile(item, editor)); + editor.ingest(e.dataTransfer); } diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 0a8930f250c..04e1f425d58 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -6,6 +6,7 @@ import FloatingMenu from "/src/components/layout/FloatingMenu.svelte"; import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import NodeGraphWire from "/src/components/views/NodeGraphWire.svelte"; + import RemoteCursor from "/src/components/views/RemoteCursor.svelte"; import ThumbnailCanvas from "/src/components/views/ThumbnailCanvas.svelte"; import ThumbnailImage from "/src/components/views/ThumbnailImage.svelte"; import IconButton from "/src/components/widgets/buttons/IconButton.svelte"; @@ -33,6 +34,7 @@ const nodeGraphWires = nodeGraph.wiresStore; const wireInsertionPreview = nodeGraph.wireInsertionPreviewStore; const nodeGlideOffsets = nodeGraph.glideOffsetsStore; + const remoteCursors = nodeGraph.remoteCursorsStore; const documentState = getContext("document"); const subscriptions = getContext("subscriptions"); @@ -342,6 +344,14 @@ style:--grid-offset-y={`${$nodeGraphTransform.y}px`} style:--grid-dot-radius={`${gridDotRadius}px`} > + + {#if $nodeGraph.readOnly} +
+ + The contents of this built-in node are shared by all its instances and read-only + editor.makeNetworkEditable()} /> +
+ {/if} {#if $nodeGraph.contextMenuInformation} +{#each $remoteCursors as cursor} + +{/each} + {#if $nodeGraph.box}
+ import IconLabel from "/src/components/widgets/labels/IconLabel.svelte"; + import { ICONS } from "/src/icons"; + import type { IconName } from "/src/icons"; + import type { FrontendRemoteCursor } from "/wrapper/pkg/graphite_wasm_wrapper"; + + export let cursor: FrontendRemoteCursor; + + // A peer running another build may name a tool icon this build lacks + function isIconName(name: string): name is IconName { + return Object.hasOwn(ICONS, name); + } + $: toolIcon = cursor.tool && isIconName(cursor.tool) ? cursor.tool : undefined; + + // White reads well only on darker hues, and black on the rest + function labelColor(background: string): string { + const [red, green, blue] = [1, 3, 5].map((start) => parseInt(background.slice(start, start + 2), 16)); + return 0.299 * red + 0.587 * green + 0.114 * blue > 128 ? "#000" : "#fff"; + } + + +
+ + + {#if toolIcon} + + {/if} + {cursor.name} + +
+ + diff --git a/frontend/src/components/widgets/WidgetLayout.svelte b/frontend/src/components/widgets/WidgetLayout.svelte index 5959e32b88a..7583ce06be7 100644 --- a/frontend/src/components/widgets/WidgetLayout.svelte +++ b/frontend/src/components/widgets/WidgetLayout.svelte @@ -9,8 +9,10 @@ layoutTarget: LayoutTarget; class?: string; classes?: Record; + // Asks for the rows of a virtually scrolled table from `start` up to but not including `end` + requestTableRows?: (start: number, end: number) => void; }; - let { layout, layoutTarget, class: className = "", classes = {} }: Props = $props(); + let { layout, layoutTarget, class: className = "", classes = {}, requestTableRows }: Props = $props(); {#each layout as layoutGroup} @@ -21,7 +23,7 @@ {:else if "NodeSection" in layoutGroup} {:else if "Table" in layoutGroup} - + {/if} {/each} diff --git a/frontend/src/components/widgets/WidgetTable.svelte b/frontend/src/components/widgets/WidgetTable.svelte index a9b6e1d43f6..3e811291669 100644 --- a/frontend/src/components/widgets/WidgetTable.svelte +++ b/frontend/src/components/widgets/WidgetTable.svelte @@ -1,33 +1,164 @@ - +
- {#each widgetData.tableWidgets as row} + {#each widgetData.tableWidgets as row, rowIndex} - {#each row as cell} + {#each row as cell, column} {/each} + + {#if rowIndex === 0 && widgetData.scrollWindow && widgetData.scrollWindow.rowsBefore > 0} + + {#each { length: columns }, column (column)}{/each} + + {/if} {/each} + {#if widgetData.scrollWindow && widgetData.scrollWindow.rowsAfter > 0} + + {#each { length: columns }, column (column)}{/each} + + {/if}
+ {#if rowIndex === 0 && virtuallyScrolled && columnContentWidths[column]} +
+ {/if}
diff --git a/frontend/src/components/widgets/buttons/ParameterExposeButton.svelte b/frontend/src/components/widgets/buttons/ParameterExposeButton.svelte index dcb2678fb5c..f5329da653d 100644 --- a/frontend/src/components/widgets/buttons/ParameterExposeButton.svelte +++ b/frontend/src/components/widgets/buttons/ParameterExposeButton.svelte @@ -5,6 +5,7 @@ // Content export let exposed: boolean; export let dataType: FrontendGraphDataType; + export let disabled = false; // Tooltips export let tooltipLabel: string | undefined = undefined; export let tooltipDescription: string | undefined = undefined; @@ -16,6 +17,7 @@ + {/if} {#if tabCloseButtons} { @@ -600,6 +616,31 @@ margin-left: 8px; } + .session { + flex: 0 0 auto; + align-self: center; + width: 6px; + height: 6px; + margin-left: 4px; + padding: 0; + border: none; + border-radius: 50%; + background: var(--color-session-green); + cursor: pointer; + + &.disconnected { + background: var(--color-error-red); + } + + &:hover { + box-shadow: 0 0 0 2px var(--color-5-dullgray); + } + + & + .icon-button { + margin-left: 4px; + } + } + & + .tab { margin-left: 1px; } diff --git a/frontend/src/components/window/PanelSubdivision.svelte b/frontend/src/components/window/PanelSubdivision.svelte index 53b3095278e..cab0c4ab2c5 100644 --- a/frontend/src/components/window/PanelSubdivision.svelte +++ b/frontend/src/components/window/PanelSubdivision.svelte @@ -38,7 +38,7 @@ } // Reactive array of resolved sizes (merging backend defaults with local overrides) $: resolvedSizes = subdivision && "Split" in subdivision ? subdivision.Split.children.map((child, index) => sizeOverrides[index] ?? child.size) : []; - $: documentTabLabels = $portfolio.documents.map((doc: DocumentInfo) => ({ name: doc.name, unsaved: !doc.is_saved })); + $: documentTabLabels = $portfolio.documents.map((doc: DocumentInfo) => ({ name: doc.name, unsaved: !doc.is_saved, session: doc.session ?? undefined })); onDestroy(() => { activeResizeCleanup?.(); @@ -206,6 +206,11 @@ editor.selectDocument($portfolio.documents[tabIndex].id); editor.renameDocument(newName); }} + sessionAction={(tabIndex) => { + // The Collaboration panel shows the active document + editor.selectDocument($portfolio.documents[tabIndex].id); + editor.focusPanel("Collaboration"); + }} tabActiveIndex={$portfolio.activeDocumentIndex} groupDropAction={groupDrop} splitDropAction={splitDrop} diff --git a/frontend/src/icons.ts b/frontend/src/icons.ts index a1434478bec..01e9e0b95bd 100644 --- a/frontend/src/icons.ts +++ b/frontend/src/icons.ts @@ -121,9 +121,6 @@ import NodeAsInteger from "/../branding/assets/16x16-nodes/node-as-integer.svg"; import NodeAsNumber from "/../branding/assets/16x16-nodes/node-as-number.svg"; import NodeAsString from "/../branding/assets/16x16-nodes/node-as-string.svg"; import NodeAsVector from "/../branding/assets/16x16-nodes/node-as-vector.svg"; -import NodeAssignColors from "/../branding/assets/16x16-nodes/node-assign-colors.svg"; -import NodeAssignRotations from "/../branding/assets/16x16-nodes/node-assign-rotations.svg"; -import NodeAssignScales from "/../branding/assets/16x16-nodes/node-assign-scales.svg"; import NodeAverage from "/../branding/assets/16x16-nodes/node-average.svg"; import NodeBakeTransform from "/../branding/assets/16x16-nodes/node-bake-transform.svg"; import NodeBasicBrush from "/../branding/assets/16x16-nodes/node-basic-brush.svg"; @@ -176,6 +173,7 @@ import NodeDimensions from "/../branding/assets/16x16-nodes/node-dimensions.svg" import NodeDistance from "/../branding/assets/16x16-nodes/node-distance.svg"; import NodeDivide from "/../branding/assets/16x16-nodes/node-divide.svg"; import NodeDotProduct from "/../branding/assets/16x16-nodes/node-dot-product.svg"; +import NodeDropShadow from "/../branding/assets/16x16-nodes/node-drop-shadow.svg"; import NodeEllipse from "/../branding/assets/16x16-nodes/node-ellipse.svg"; import NodeEquals from "/../branding/assets/16x16-nodes/node-equals.svg"; import NodeEvaluateGradient from "/../branding/assets/16x16-nodes/node-evaluate-gradient.svg"; @@ -189,7 +187,6 @@ import NodeFill from "/../branding/assets/16x16-nodes/node-fill.svg"; import NodeFilter from "/../branding/assets/16x16-nodes/node-filter.svg"; import NodeFlattenColor from "/../branding/assets/16x16-nodes/node-flatten-color.svg"; import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gradient.svg"; -import NodeFlattenGraphic from "/../branding/assets/16x16-nodes/node-flatten-graphic.svg"; import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg"; import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg"; import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg"; @@ -215,6 +212,7 @@ import NodeGradientValue from "/../branding/assets/16x16-nodes/node-gradient-val import NodeGreaterThan from "/../branding/assets/16x16-nodes/node-greater-than.svg"; import NodeGreatestCommonDivisor from "/../branding/assets/16x16-nodes/node-greatest-common-divisor.svg"; import NodeGrid from "/../branding/assets/16x16-nodes/node-grid.svg"; +import NodeGroup from "/../branding/assets/16x16-nodes/node-group.svg"; import NodeHeart from "/../branding/assets/16x16-nodes/node-heart.svg"; import NodeHslaToColor from "/../branding/assets/16x16-nodes/node-hsla-to-color.svg"; import NodeHsvaToColor from "/../branding/assets/16x16-nodes/node-hsva-to-color.svg"; @@ -225,12 +223,14 @@ import NodeImageToChannels from "/../branding/assets/16x16-nodes/node-image-to-c import NodeImage from "/../branding/assets/16x16-nodes/node-image.svg"; import NodeIndexPoints from "/../branding/assets/16x16-nodes/node-index-points.svg"; import NodeIndices from "/../branding/assets/16x16-nodes/node-indices.svg"; -import NodeIntoGroup from "/../branding/assets/16x16-nodes/node-into-group.svg"; +import NodeInnerShadow from "/../branding/assets/16x16-nodes/node-inner-shadow.svg"; import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-transform.svg"; import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg"; import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg"; import NodeItemAtIndex from "/../branding/assets/16x16-nodes/node-item-at-index.svg"; +import NodeIterate from "/../branding/assets/16x16-nodes/node-iterate.svg"; import NodeJitterPoints from "/../branding/assets/16x16-nodes/node-jitter-points.svg"; +import NodeLSystem from "/../branding/assets/16x16-nodes/node-l-system.svg"; import NodeLeastCommonMultiple from "/../branding/assets/16x16-nodes/node-least-common-multiple.svg"; import NodeLerp from "/../branding/assets/16x16-nodes/node-lerp.svg"; import NodeLessThan from "/../branding/assets/16x16-nodes/node-less-than.svg"; @@ -249,8 +249,10 @@ import NodeMandelbrot from "/../branding/assets/16x16-nodes/node-mandelbrot.svg" import NodeMapPoints from "/../branding/assets/16x16-nodes/node-map-points.svg"; import NodeMap from "/../branding/assets/16x16-nodes/node-map.svg"; import NodeMask from "/../branding/assets/16x16-nodes/node-mask.svg"; -import NodeMathF from "/../branding/assets/16x16-nodes/node-math-f.svg"; -import NodeMathFx from "/../branding/assets/16x16-nodes/node-math-fx.svg"; +import NodeMathAggregate from "/../branding/assets/16x16-nodes/node-math-aggregate.svg"; +import NodeMathFormula from "/../branding/assets/16x16-nodes/node-math-formula.svg"; +import NodeMathFunction from "/../branding/assets/16x16-nodes/node-math-function.svg"; +import NodeMathRunning from "/../branding/assets/16x16-nodes/node-math-running.svg"; import NodeMax from "/../branding/assets/16x16-nodes/node-max.svg"; import NodeMaximum from "/../branding/assets/16x16-nodes/node-maximum.svg"; import NodeMedianFilter from "/../branding/assets/16x16-nodes/node-median-filter.svg"; @@ -272,7 +274,9 @@ import NodeNumbersToVec2 from "/../branding/assets/16x16-nodes/node-numbers-to-v import NodeOffsetPath from "/../branding/assets/16x16-nodes/node-offset-path.svg"; import NodeOffsetPoints from "/../branding/assets/16x16-nodes/node-offset-points.svg"; import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg"; +import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg"; import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg"; +import NodeOuterGlow from "/../branding/assets/16x16-nodes/node-outer-glow.svg"; import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg"; import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg"; import NodePathIsClosed from "/../branding/assets/16x16-nodes/node-path-is-closed.svg"; @@ -373,9 +377,17 @@ import NodeText from "/../branding/assets/16x16-nodes/node-text.svg"; import NodeThreshold from "/../branding/assets/16x16-nodes/node-threshold.svg"; import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg"; import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg"; +import NodeTurtlePath from "/../branding/assets/16x16-nodes/node-turtle-path.svg"; +import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg"; import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg"; +import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg"; +import NodeVaryRotations from "/../branding/assets/16x16-nodes/node-vary-rotations.svg"; +import NodeVaryScales from "/../branding/assets/16x16-nodes/node-vary-scales.svg"; +import NodeVaryStrokeColors from "/../branding/assets/16x16-nodes/node-vary-stroke-colors.svg"; import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg"; import NodeVec2Value from "/../branding/assets/16x16-nodes/node-vec2-value.svg"; +import NodeVectorToPoints from "/../branding/assets/16x16-nodes/node-vector-to-points.svg"; +import NodeVectorize from "/../branding/assets/16x16-nodes/node-vectorize.svg"; import NodeVibrance from "/../branding/assets/16x16-nodes/node-vibrance.svg"; import NodeVoronoiCells from "/../branding/assets/16x16-nodes/node-voronoi-cells.svg"; import NodeWeld from "/../branding/assets/16x16-nodes/node-weld.svg"; @@ -397,9 +409,6 @@ export const ICON_16X16_NODES = { NodeAsGraphic: { svg: NodeAsGraphic, size: 16 }, NodeAsInteger: { svg: NodeAsInteger, size: 16 }, NodeAsNumber: { svg: NodeAsNumber, size: 16 }, - NodeAssignColors: { svg: NodeAssignColors, size: 16 }, - NodeAssignRotations: { svg: NodeAssignRotations, size: 16 }, - NodeAssignScales: { svg: NodeAssignScales, size: 16 }, NodeAsString: { svg: NodeAsString, size: 16 }, NodeAsVector: { svg: NodeAsVector, size: 16 }, NodeAverage: { svg: NodeAverage, size: 16 }, @@ -454,6 +463,7 @@ export const ICON_16X16_NODES = { NodeDistance: { svg: NodeDistance, size: 16 }, NodeDivide: { svg: NodeDivide, size: 16 }, NodeDotProduct: { svg: NodeDotProduct, size: 16 }, + NodeDropShadow: { svg: NodeDropShadow, size: 16 }, NodeEllipse: { svg: NodeEllipse, size: 16 }, NodeEquals: { svg: NodeEquals, size: 16 }, NodeEvaluateGradient: { svg: NodeEvaluateGradient, size: 16 }, @@ -467,7 +477,6 @@ export const ICON_16X16_NODES = { NodeFilter: { svg: NodeFilter, size: 16 }, NodeFlattenColor: { svg: NodeFlattenColor, size: 16 }, NodeFlattenGradient: { svg: NodeFlattenGradient, size: 16 }, - NodeFlattenGraphic: { svg: NodeFlattenGraphic, size: 16 }, NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 }, NodeFlattenVector: { svg: NodeFlattenVector, size: 16 }, NodeFloor: { svg: NodeFloor, size: 16 }, @@ -493,6 +502,7 @@ export const ICON_16X16_NODES = { NodeGreaterThan: { svg: NodeGreaterThan, size: 16 }, NodeGreatestCommonDivisor: { svg: NodeGreatestCommonDivisor, size: 16 }, NodeGrid: { svg: NodeGrid, size: 16 }, + NodeGroup: { svg: NodeGroup, size: 16 }, NodeHeart: { svg: NodeHeart, size: 16 }, NodeHslaToColor: { svg: NodeHslaToColor, size: 16 }, NodeHsvaToColor: { svg: NodeHsvaToColor, size: 16 }, @@ -503,11 +513,12 @@ export const ICON_16X16_NODES = { NodeImageToChannels: { svg: NodeImageToChannels, size: 16 }, NodeIndexPoints: { svg: NodeIndexPoints, size: 16 }, NodeIndices: { svg: NodeIndices, size: 16 }, - NodeIntoGroup: { svg: NodeIntoGroup, size: 16 }, + NodeInnerShadow: { svg: NodeInnerShadow, size: 16 }, NodeInvert: { svg: NodeInvert, size: 16 }, NodeInvertTransform: { svg: NodeInvertTransform, size: 16 }, NodeIsNonzero: { svg: NodeIsNonzero, size: 16 }, NodeItemAtIndex: { svg: NodeItemAtIndex, size: 16 }, + NodeIterate: { svg: NodeIterate, size: 16 }, NodeJitterPoints: { svg: NodeJitterPoints, size: 16 }, NodeLeastCommonMultiple: { svg: NodeLeastCommonMultiple, size: 16 }, NodeLerp: { svg: NodeLerp, size: 16 }, @@ -521,14 +532,17 @@ export const ICON_16X16_NODES = { NodeLogicalNot: { svg: NodeLogicalNot, size: 16 }, NodeLogicalOr: { svg: NodeLogicalOr, size: 16 }, NodeLoremIpsum: { svg: NodeLoremIpsum, size: 16 }, + NodeLSystem: { svg: NodeLSystem, size: 16 }, NodeMagnitude: { svg: NodeMagnitude, size: 16 }, NodeMakeOpaque: { svg: NodeMakeOpaque, size: 16 }, NodeMandelbrot: { svg: NodeMandelbrot, size: 16 }, NodeMap: { svg: NodeMap, size: 16 }, NodeMapPoints: { svg: NodeMapPoints, size: 16 }, NodeMask: { svg: NodeMask, size: 16 }, - NodeMathF: { svg: NodeMathF, size: 16 }, - NodeMathFx: { svg: NodeMathFx, size: 16 }, + NodeMathAggregate: { svg: NodeMathAggregate, size: 16 }, + NodeMathFormula: { svg: NodeMathFormula, size: 16 }, + NodeMathFunction: { svg: NodeMathFunction, size: 16 }, + NodeMathRunning: { svg: NodeMathRunning, size: 16 }, NodeMax: { svg: NodeMax, size: 16 }, NodeMaximum: { svg: NodeMaximum, size: 16 }, NodeMedianFilter: { svg: NodeMedianFilter, size: 16 }, @@ -550,7 +564,9 @@ export const ICON_16X16_NODES = { NodeOffsetPath: { svg: NodeOffsetPath, size: 16 }, NodeOffsetPoints: { svg: NodeOffsetPoints, size: 16 }, NodeOpacity: { svg: NodeOpacity, size: 16 }, + NodeOpenEnds: { svg: NodeOpenEnds, size: 16 }, NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 }, + NodeOuterGlow: { svg: NodeOuterGlow, size: 16 }, NodePackStrips: { svg: NodePackStrips, size: 16 }, NodePassthrough: { svg: NodePassthrough, size: 16 }, NodePath: { svg: NodePath, size: 16 }, @@ -651,9 +667,17 @@ export const ICON_16X16_NODES = { NodeThreshold: { svg: NodeThreshold, size: 16 }, NodeTransform: { svg: NodeTransform, size: 16 }, NodeTriangulate: { svg: NodeTriangulate, size: 16 }, + NodeTurtlePath: { svg: NodeTurtlePath, size: 16 }, + NodeUngroup: { svg: NodeUngroup, size: 16 }, NodeUnweld: { svg: NodeUnweld, size: 16 }, + NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 }, + NodeVaryRotations: { svg: NodeVaryRotations, size: 16 }, + NodeVaryScales: { svg: NodeVaryScales, size: 16 }, + NodeVaryStrokeColors: { svg: NodeVaryStrokeColors, size: 16 }, NodeVec2ToNumbers: { svg: NodeVec2ToNumbers, size: 16 }, NodeVec2Value: { svg: NodeVec2Value, size: 16 }, + NodeVectorToPoints: { svg: NodeVectorToPoints, size: 16 }, + NodeVectorize: { svg: NodeVectorize, size: 16 }, NodeVibrance: { svg: NodeVibrance, size: 16 }, NodeVoronoiCells: { svg: NodeVoronoiCells, size: 16 }, NodeWeld: { svg: NodeWeld, size: 16 }, diff --git a/frontend/src/managers/clipboard.ts b/frontend/src/managers/clipboard.ts index 678df68af6f..bdcb72426a9 100644 --- a/frontend/src/managers/clipboard.ts +++ b/frontend/src/managers/clipboard.ts @@ -12,11 +12,6 @@ export function createClipboardManager(subscriptions: SubscriptionsRouter, edito subscriptionsRouter = subscriptions; editorWrapper = editor; - subscriptions.subscribeFrontendMessage("TriggerClipboardWrite", (data) => { - // If the Clipboard API is supported in the browser, copy text to the clipboard - navigator.clipboard?.writeText?.(data.content); - }); - subscriptions.subscribeFrontendMessage("TriggerSelectionRead", async (data) => { const content = readAtCaret(data.cut); // A text field with nothing selected has nothing to copy, rather than leaving the shortcut to act on the selected layers @@ -34,7 +29,6 @@ export function destroyClipboardManager() { const subscriptions = subscriptionsRouter; if (!subscriptions) return; - subscriptions.unsubscribeFrontendMessage("TriggerClipboardWrite"); subscriptions.unsubscribeFrontendMessage("TriggerSelectionRead"); subscriptions.unsubscribeFrontendMessage("TriggerSelectionWrite"); } diff --git a/frontend/src/managers/input.ts b/frontend/src/managers/input.ts index fb4b5d91830..742296aa91f 100644 --- a/frontend/src/managers/input.ts +++ b/frontend/src/managers/input.ts @@ -3,7 +3,6 @@ import type { DocumentStore } from "/src/stores/document"; import { fullscreenModeChanged } from "/src/stores/fullscreen"; import type { PortfolioStore } from "/src/stores/portfolio"; import type { SubscriptionsRouter } from "/src/subscriptions-router"; -import { triggerClipboardRead } from "/src/utility-functions/clipboard"; import { onBeforeUnload, onKeyUp, @@ -69,10 +68,6 @@ export function createInputManager(subscriptions: SubscriptionsRouter, editor: E portfolioStore = portfolio; documentStore = doc; - subscriptions.subscribeFrontendMessage("TriggerClipboardRead", () => { - triggerClipboardRead(editor); - }); - subscriptions.subscribeFrontendMessage("WindowPointerLockMove", (data) => { // Desktop app only: dispatch custom pointer lock movement events const event = new CustomEvent("pointerlockmove", { detail: { x: data.position[0], y: data.position[1] } }); @@ -94,7 +89,6 @@ export function destroyInputManager() { const subscriptions = subscriptionsRouter; if (!subscriptions) return; - subscriptions.unsubscribeFrontendMessage("TriggerClipboardRead"); subscriptions.unsubscribeFrontendMessage("WindowPointerLockMove"); // Remove event bindings after the lifetime of the application (or on hot-module replacement during development) diff --git a/frontend/src/managers/persistence.ts b/frontend/src/managers/persistence.ts index e12d9d166a5..d25391b7acc 100644 --- a/frontend/src/managers/persistence.ts +++ b/frontend/src/managers/persistence.ts @@ -15,6 +15,7 @@ export function createPersistenceManager(subscriptions: SubscriptionsRouter, edi portfolioStore = portfolio; // Run persistence operations in request order + const writtenDocuments = new Set(); let tail: Promise = Promise.resolve(); const enqueue = (operation: () => Promise): Promise => { const next = tail.then(operation); @@ -26,7 +27,7 @@ export function createPersistenceManager(subscriptions: SubscriptionsRouter, edi subscriptions.subscribeFrontendMessage("TriggerLoadPreferences", () => enqueue(() => loadEditorPreferences(editor))); - subscriptions.subscribeFrontendMessage("TriggerPersistenceWriteState", (data) => enqueue(() => writePersistedState(data.state))); + subscriptions.subscribeFrontendMessage("TriggerPersistenceWriteState", (data) => enqueue(() => writePersistedState(data.state, writtenDocuments))); subscriptions.subscribeFrontendMessage("TriggerPersistenceReadState", () => enqueue(() => readPersistedState(editor))); diff --git a/frontend/src/stores/document.ts b/frontend/src/stores/document.ts index 913532dfa30..7edf8b8ab44 100644 --- a/frontend/src/stores/document.ts +++ b/frontend/src/stores/document.ts @@ -3,7 +3,7 @@ import type { Writable } from "svelte/store"; import type { SubscriptionsRouter } from "/src/subscriptions-router"; import { createLayout } from "/src/utility-functions/layout-state.svelte"; import { patchLayout } from "/src/utility-functions/widgets"; -import type { Layout, RenderStatus } from "/wrapper/pkg/graphite_wasm_wrapper"; +import type { FrontendRemoteCursor, Layout, RenderStatus } from "/wrapper/pkg/graphite_wasm_wrapper"; export type DocumentStore = ReturnType; @@ -33,6 +33,10 @@ let subscriptionsRouter: SubscriptionsRouter | undefined = undefined; // Store state persisted across HMR to maintain reactive subscriptions in the component tree const store: Writable = import.meta.hot?.data?.store || writable(initialState); if (import.meta.hot) import.meta.hot.data.store = store; + +// Separate since cursors move every frame and only the overlay draws them +const remoteCursorsStore: Writable = import.meta.hot?.data?.remoteCursorsStore || writable([]); +if (import.meta.hot) import.meta.hot.data.remoteCursorsStore = remoteCursorsStore; const { subscribe, update } = store; export function createDocumentStore(subscriptions: SubscriptionsRouter) { @@ -71,6 +75,9 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) { patchLayout(get(store).nodeGraphControlBarLayout, data); }); + subscriptions.subscribeFrontendMessage("UpdateDocumentCursors", (data) => { + remoteCursorsStore.set(data.cursors); + }); subscriptions.subscribeFrontendMessage("UpdateGraphViewOverlay", (data) => { update((state) => { state.graphViewOverlayOpen = data.open; @@ -85,7 +92,7 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) { }); }); - return { subscribe }; + return { subscribe, remoteCursorsStore }; } export function destroyDocumentStore() { @@ -95,6 +102,7 @@ export function destroyDocumentStore() { subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork"); subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay"); subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus"); + subscriptions.unsubscribeFrontendMessage("UpdateDocumentCursors"); subscriptions.unsubscribeLayoutUpdate("ToolOptions"); subscriptions.unsubscribeLayoutUpdate("DocumentBar"); subscriptions.unsubscribeLayoutUpdate("ToolShelf"); diff --git a/frontend/src/stores/history.ts b/frontend/src/stores/history.ts new file mode 100644 index 00000000000..34d5420524b --- /dev/null +++ b/frontend/src/stores/history.ts @@ -0,0 +1,35 @@ +import { writable } from "svelte/store"; +import type { Writable } from "svelte/store"; +import type { SubscriptionsRouter } from "/src/subscriptions-router"; +import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper"; + +export type HistoryStore = ReturnType; + +const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, collaborating: false }; + +// Store state persisted across HMR to maintain reactive subscriptions in the component tree +const store: Writable = import.meta.hot?.data?.store || writable(initialState); +if (import.meta.hot) import.meta.hot.data.store = store; + +const { subscribe, set } = store; + +let subscriptionsRouter: SubscriptionsRouter | undefined = undefined; + +export function createHistoryStore(subscriptions: SubscriptionsRouter) { + destroyHistoryStore(); + subscriptionsRouter = subscriptions; + + subscriptions.subscribeFrontendMessage("UpdateHistoryPanel", (data) => { + set(data.state); + }); + + return { subscribe }; +} + +export function destroyHistoryStore() { + const subscriptions = subscriptionsRouter; + if (!subscriptions) return; + + subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel"); + subscriptionsRouter = undefined; +} diff --git a/frontend/src/stores/node-graph.ts b/frontend/src/stores/node-graph.ts index ad8e5755de4..1d555f55648 100644 --- a/frontend/src/stores/node-graph.ts +++ b/frontend/src/stores/node-graph.ts @@ -3,7 +3,16 @@ import type { Writable } from "svelte/store"; import type { IconName } from "/src/icons"; import type { SubscriptionsRouter } from "/src/subscriptions-router"; import type { MessageBody } from "/src/subscriptions-router"; -import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper"; +import type { + NodeGraphErrorDiagnostic, + BoxSelection, + FrontendClickTargets, + ContextMenuInformation, + FrontendNode, + FrontendNodeType, + FrontendRemoteCursor, + WirePath, +} from "/wrapper/pkg/graphite_wasm_wrapper"; export type NodeGraphStore = ReturnType; @@ -30,6 +39,7 @@ type NodeGraphStoreState = { thumbnailCanvases: Map; selected: bigint[]; inSelectedNetwork: boolean; + readOnly: boolean; reorderImportIndex: number | undefined; reorderExportIndex: number | undefined; }; @@ -52,6 +62,7 @@ const initialState: NodeGraphStoreState = { thumbnailCanvases: new Map(), selected: [], inSelectedNetwork: true, + readOnly: false, reorderImportIndex: undefined, reorderExportIndex: undefined, }; @@ -113,6 +124,10 @@ export type GlideOffsets = { nodes: Map; imports: [num const glideOffsetsStore: Writable = import.meta.hot?.data?.glideOffsetsStore || writable({ nodes: new Map(), imports: [0, 0], exports: [0, 0] }); if (import.meta.hot) import.meta.hot.data.glideOffsetsStore = glideOffsetsStore; +// Separate since cursors move every frame and only the overlay draws them +const remoteCursorsStore: Writable = import.meta.hot?.data?.remoteCursorsStore || writable([]); +if (import.meta.hot) import.meta.hot.data.remoteCursorsStore = remoteCursorsStore; + export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { destroyNodeGraphStore(); @@ -134,6 +149,10 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); + subscriptions.subscribeFrontendMessage("UpdateNodeGraphCursors", (data) => { + remoteCursorsStore.set(data.cursors); + }); + subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => { update((state) => { state.clickTargets = data.clickTargets; @@ -184,6 +203,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); + subscriptions.subscribeFrontendMessage("UpdateNetworkReadOnly", (data) => { + update((state) => { + state.readOnly = data.readOnly; + return state; + }); + }); + subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => { update((state) => { state.layerWidths = data.layerWidths; @@ -312,7 +338,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); - return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore }; + return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore, remoteCursorsStore }; } export function destroyNodeGraphStore() { @@ -321,6 +347,7 @@ export function destroyNodeGraphStore() { subscriptions.unsubscribeFrontendMessage("SendUIMetadata"); subscriptions.unsubscribeFrontendMessage("UpdateBox"); + subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphCursors"); subscriptions.unsubscribeFrontendMessage("UpdateClickTargets"); subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation"); subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex"); @@ -329,6 +356,7 @@ export function destroyNodeGraphStore() { subscriptions.unsubscribeFrontendMessage("UpdateHoveredConnector"); subscriptions.unsubscribeFrontendMessage("UpdateImportsExports"); subscriptions.unsubscribeFrontendMessage("UpdateInSelectedNetwork"); + subscriptions.unsubscribeFrontendMessage("UpdateNetworkReadOnly"); subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics"); diff --git a/frontend/src/stores/portfolio.ts b/frontend/src/stores/portfolio.ts index e278152fe08..ec6d55af193 100644 --- a/frontend/src/stores/portfolio.ts +++ b/frontend/src/stores/portfolio.ts @@ -44,6 +44,7 @@ export const palettePanelBottomLeftBarLayout = persistedLayout("palettePanelBott export const dataPanelLayout = persistedLayout("dataPanelLayout"); export const dataPanelContextLayout = persistedLayout("dataPanelContextLayout"); export const dataPanelPathLayout = persistedLayout("dataPanelPathLayout"); +export const collaborationPanelLayout = persistedLayout("collaborationPanelLayout"); export const layersPanelControlBarLeftLayout = persistedLayout("layersPanelControlBarLeftLayout"); export const layersPanelBottomBarLeftLayout = persistedLayout("layersPanelBottomBarLeftLayout"); export const layersPanelBottomBarRightLayout = persistedLayout("layersPanelBottomBarRightLayout"); @@ -83,7 +84,7 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor: try { const url = new URL(`demo-artwork/${data.filename}`, document.location.href); const response = await fetch(url); - editor.ingestPicked(data.filename, "", await response.bytes(), "Open"); + editor.ingestPicked(data.filename, "", await response.bytes(), "OpenUnique"); } catch { // Needs to be delayed until the end of the current call stack so the existing demo artwork dialog can be closed first, otherwise this dialog won't show setTimeout(() => { @@ -156,6 +157,10 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor: patchLayout(palettePanelBottomLeftBarLayout, data); }); + subscriptions.subscribeLayoutUpdate("CollaborationPanel", (data) => { + patchLayout(collaborationPanelLayout, data); + }); + subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => { patchLayout(layersPanelControlBarLeftLayout, data); }); @@ -221,6 +226,7 @@ export function destroyPortfolioStore() { subscriptions.unsubscribeLayoutUpdate("DataPanel"); subscriptions.unsubscribeLayoutUpdate("DataPanelContext"); subscriptions.unsubscribeLayoutUpdate("DataPanelPath"); + subscriptions.unsubscribeLayoutUpdate("CollaborationPanel"); subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar"); subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomLeftBar"); subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomRightBar"); diff --git a/frontend/src/utility-functions/clipboard.ts b/frontend/src/utility-functions/clipboard.ts index 466756461bd..edfe5d4c2a4 100644 --- a/frontend/src/utility-functions/clipboard.ts +++ b/frontend/src/utility-functions/clipboard.ts @@ -1,6 +1,3 @@ -import { stripIndents } from "/src/utility-functions/strip-indents"; -import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; - export function readAtCaret(cut: boolean): string | undefined { const element = window.document.activeElement; @@ -92,75 +89,3 @@ export function insertAtCaret(text: string) { element.dispatchEvent(new Event("input", { bubbles: true })); } - -export async function triggerClipboardRead(editor: EditorWrapper) { - // In the try block, attempt to read from the Clipboard API, which may not have permission and may not be supported in all browsers - // In the catch block, explain to the user why the paste failed and how to fix or work around the problem - try { - // Attempt to check if the clipboard permission is denied, and throw an error if that is the case - // In Firefox, the `clipboard-read` permission isn't supported, so attempting to query it throws an error - // In Safari, the entire Permissions API isn't supported, so the query never occurs and this block is skipped without an error and we assume we might have permission - const permission = await navigator.permissions?.query({ name: "clipboard-read" }); - if (permission?.state === "denied") throw new Error("Permission denied"); - - // Read the clipboard contents if the Clipboard API is available - const clipboardItems = await navigator.clipboard.read(); - if (!clipboardItems) throw new Error("Clipboard API unsupported"); - - // Read any layer data or images from the clipboard - const success = await Promise.any( - Array.from(clipboardItems).map(async (item) => { - // Read plain text and, if it is a layer, pass it to the editor - if (item.types.includes("text/plain")) { - const blob = await item.getType("text/plain"); - const reader = new FileReader(); - reader.onload = () => { - if (typeof reader.result === "string") editor.pasteText(reader.result); - }; - reader.readAsText(blob); - return true; - } - - // Read an image from the clipboard and pass it to the editor to be loaded - const imageType = item.types.find((type) => type.startsWith("image/")); - - if (imageType) { - const blob = await item.getType(imageType); - editor.ingestFile(undefined, imageType, new Uint8Array(await blob.arrayBuffer())); - return true; - } - - // The API limits what kinds of data we can access, so we can get copied images and our text encodings of copied nodes, but not files (like - // .graphite or even image files). However, the user can paste those with Ctrl+V, which we recommend they in the error message that's shown to them. - return false; - }), - ); - - if (!success) throw new Error("No valid clipboard data"); - } catch (err) { - const unsupported = stripIndents` - This browser does not support reading from the clipboard. - Use the standard keyboard shortcut to paste instead. - `; - const denied = stripIndents` - The browser's clipboard permission has been denied. - - Open the browser's website settings (usually accessible - just left of the URL bar) to allow this permission. - `; - const nothing = stripIndents` - No valid clipboard data was found. You may have better - success pasting with the standard keyboard shortcut instead. - `; - - const matchMessage = { - "clipboard-read": unsupported, - "Clipboard API unsupported": unsupported, - "Permission denied": denied, - "No valid clipboard data": nothing, - }; - const message = Object.entries(matchMessage).find(([key]) => String(err).includes(key))?.[1] || String(err); - - editor.errorDialog("Cannot access clipboard", message); - } -} diff --git a/frontend/src/utility-functions/files.ts b/frontend/src/utility-functions/files.ts index b4690d930f0..24590fdf1be 100644 --- a/frontend/src/utility-functions/files.ts +++ b/frontend/src/utility-functions/files.ts @@ -1,4 +1,4 @@ -import type { EditorWrapper, FileFilter } from "/wrapper/pkg/graphite_wasm_wrapper"; +import type { FileFilter } from "/wrapper/pkg/graphite_wasm_wrapper"; export function downloadFileURL(filename: string, url: string) { const element = document.createElement("a"); @@ -80,13 +80,6 @@ export async function upload( } export type UploadResult = { filename: string; type: string; content: T }; -export async function pasteFile(item: DataTransferItem, editor: EditorWrapper, mouse?: [number, number], insertParentId?: bigint, insertIndex?: number) { - const file = item.getAsFile(); - if (!file) return; - - editor.ingestFile(file.name, file.type, await file.bytes(), mouse?.[0], mouse?.[1], insertParentId, insertIndex); -} - export function acceptStringFromFilters(filters: FileFilter[]): string { return filters.flatMap((filter) => [...filter.mimeTypes, ...filter.extensions.map((extension) => `.${extension}`)]).join(","); } diff --git a/frontend/src/utility-functions/input.ts b/frontend/src/utility-functions/input.ts index 7be6458e4bf..b31fd6754f3 100644 --- a/frontend/src/utility-functions/input.ts +++ b/frontend/src/utility-functions/input.ts @@ -2,7 +2,6 @@ import { get } from "svelte/store"; import type { DialogStore } from "/src/stores/dialog"; import { toggleFullscreen } from "/src/stores/fullscreen"; import type { PortfolioStore } from "/src/stores/portfolio"; -import { pasteFile } from "/src/utility-functions/files"; import { makeKeyboardModifiersBitfield, textInputCleanup, getLocalizedScanCode } from "/src/utility-functions/keyboard-entry"; import { operatingSystem } from "/src/utility-functions/platform"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; @@ -291,10 +290,7 @@ export function onPaste(e: ClipboardEvent, editor: EditorWrapper) { if (!dataTransfer || targetIsTextField(e.target || undefined)) return; e.preventDefault(); - Array.from(dataTransfer.items).forEach(async (item) => { - if (item.type === "text/plain") item.getAsString((text) => editor.pasteText(text)); - await pasteFile(item, editor); - }); + editor.ingest(dataTransfer); } // A spot that takes dropped files has canceled the event by the time it bubbles up to the window diff --git a/frontend/src/utility-functions/network.ts b/frontend/src/utility-functions/network.ts index c0b1173657d..92b9ecaa57f 100644 --- a/frontend/src/utility-functions/network.ts +++ b/frontend/src/utility-functions/network.ts @@ -34,6 +34,18 @@ export function requestWithUploadDownloadProgress( return [promise, xhrValue]; } +// Join the session in the URL's `?session=` token and remove it from the address bar +export function joinSessionFromUrl(editor: EditorWrapper) { + const token = new URLSearchParams(window.location.search).get("session"); + if (!token) return; + + editor.joinSession(token); + + const url = new URL(window.location.href); + url.searchParams.delete("session"); + history.replaceState("", "", `${url.pathname}${url.search}${url.hash}`); +} + // If the URL hash fragment contains a demo artwork path (e.g. #demo/isometric-light), fetch and open it export async function loadDemoArtwork(editor: EditorWrapper) { const demoArtwork = window.location.hash.trim().match(/#demo\/(.*)/)?.[1]; @@ -46,7 +58,7 @@ export async function loadDemoArtwork(editor: EditorWrapper) { const filename = url.pathname.split("/").pop() || "Untitled.graphite"; const content = await response.bytes(); - editor.ingestPicked(filename, "", content, "Open"); + editor.ingestPicked(filename, "", content, "OpenUnique"); history.replaceState("", "", `${window.location.pathname}${window.location.search}`); } catch { diff --git a/frontend/src/utility-functions/persistence.ts b/frontend/src/utility-functions/persistence.ts index ef09c8268f3..6125d6e5e48 100644 --- a/frontend/src/utility-functions/persistence.ts +++ b/frontend/src/utility-functions/persistence.ts @@ -36,13 +36,28 @@ function reorderDocuments(documents: DocumentInfo[], orderedIds: bigint[]): Docu // State-based persistence // ======================= -export async function writePersistedState(state: PersistedState) { +// A listed document this tab never wrote is another tab's and stays listed. One it wrote and no longer sends was closed. +export async function writePersistedState(state: PersistedState, writtenDocuments: Set) { // Keep state ordered and normalized before writing. state.documents = reorderDocuments( state.documents, state.documents.map((entry) => entry.id), ); - await databaseSet("state", state); + state.documents.forEach((entry) => writtenDocuments.add(entry.id)); + + const db = await databaseOpen(); + await new Promise((resolve, reject) => { + const transaction = db.transaction(PERSISTENCE_STORE, "readwrite"); + const store = transaction.objectStore(PERSISTENCE_STORE); + const request = store.get("state"); + request.onsuccess = () => { + const stored: PersistedState | undefined = request.result; + const others = (stored?.documents ?? []).filter((entry) => !writtenDocuments.has(entry.id)); + store.put({ ...state, documents: [...state.documents, ...others] }, "state"); + }; + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + }); } export async function readPersistedState(editor: EditorWrapper) { diff --git a/frontend/wrapper/Cargo.toml b/frontend/wrapper/Cargo.toml index cc371a8f281..f11f4b5ba99 100644 --- a/frontend/wrapper/Cargo.toml +++ b/frontend/wrapper/Cargo.toml @@ -11,10 +11,9 @@ publish.workspace = true readme = "./README.md" [features] -default = ["gpu", "web"] +default = ["web"] web = ["editor", "editor?/wasm"] editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:spin", "dep:wgpu"] -gpu = ["editor?/gpu"] native = [] [lib] @@ -36,7 +35,7 @@ serde-wasm-bindgen = { workspace = true } js-sys = { workspace = true } wasm-bindgen-futures = { workspace = true } wgpu = { workspace = true, optional = true } -web-sys = { workspace = true, features = ["Performance"] } +web-sys = { workspace = true, features = ["Blob", "BlobPropertyBag", "ClipboardItem", "DataTransfer", "DataTransferItem", "DataTransferItemList", "File", "IdleDeadline", "Location", "PermissionState", "PermissionStatus", "Permissions"] } serde_json = { workspace = true } spin = { workspace = true, optional = true } tsify = { workspace = true } diff --git a/frontend/wrapper/src/data_transfer.rs b/frontend/wrapper/src/data_transfer.rs new file mode 100644 index 00000000000..117effbbd44 --- /dev/null +++ b/frontend/wrapper/src/data_transfer.rs @@ -0,0 +1,139 @@ +use crate::helpers::wrapper; +use editor::messages::portfolio::ingest::utility_types::{DataTransfer, DataTransferItem, DataType, IngestAction, RawData}; +use editor::messages::prelude::*; +use js_sys::{Array, Object, Promise, Reflect, Uint8Array}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_futures::JsFuture; +use web_sys::{Blob, BlobPropertyBag, ClipboardItem, PermissionState, PermissionStatus}; + +const READ_UNSUPPORTED: &str = "This browser does not support reading from the clipboard.\nUse the standard keyboard shortcut to paste instead."; +const READ_DENIED: &str = "The browser's clipboard permission has been denied.\n\nOpen the browser's website settings (usually accessible\njust left of the URL bar) to allow this permission."; +const READ_NOTHING: &str = "No valid clipboard data was found. You may have better\nsuccess pasting with the standard keyboard shortcut instead."; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(catch, js_namespace = ["navigator", "clipboard"], js_name = read)] + fn clipboard_read() -> Result; + #[wasm_bindgen(catch, js_namespace = ["navigator", "clipboard"], js_name = write)] + fn clipboard_write(items: &Array) -> Result; + #[wasm_bindgen(catch, js_namespace = ["navigator", "clipboard"], js_name = writeText)] + fn clipboard_write_text(text: &str) -> Result; + #[wasm_bindgen(catch, js_namespace = ClipboardItem, js_name = supports)] + fn clipboard_item_supports(mime: &str) -> Result; +} + +pub(crate) fn write_clipboard(content: DataTransfer) { + let representations: Vec<_> = content.0.into_iter().filter_map(DataTransferItem::into_raw).collect(); + let text = representations.iter().find_map(|(data_type, data)| match data { + RawData::Text(text) if *data_type == DataType::Text => Some(text.clone()), + _ => None, + }); + let write_text = move || { + if let Some(text) = text { + let _ = clipboard_write_text(&text); + } + }; + + let record = Object::new(); + for (data_type, data) in representations { + let Some(mime) = data_type.mime().filter(|mime| clipboard_item_supports(mime).unwrap_or(false)) else { + continue; + }; + let options = BlobPropertyBag::new(); + options.set_type(mime); + if let Ok(blob) = Blob::new_with_u8_array_sequence_and_options(&Array::of1(&Uint8Array::from(data.into_bytes().as_slice())), &options) { + let _ = Reflect::set(&record, &mime.into(), &blob); + } + } + + let write = match Object::keys(&record).length() { + 0 => None, + _ => ClipboardItem::new_with_record_from_str_to_blob_promise(&record) + .ok() + .and_then(|item| clipboard_write(&Array::of1(&item)).ok()), + }; + match write { + Some(write) => wasm_bindgen_futures::spawn_local(async move { + if JsFuture::from(write).await.is_err() { + write_text(); + } + }), + None => write_text(), + } +} + +pub(crate) fn read_clipboard() { + wasm_bindgen_futures::spawn_local(async { + let message: Message = match clipboard_content().await { + Ok(content) => IngestMessage::Ingest { content, action: IngestAction::Paste }.into(), + Err(description) => DialogMessage::DisplayDialogError { + title: "Cannot access clipboard".to_string(), + description, + } + .into(), + }; + wrapper(|wrapper| wrapper.dispatch(message)); + }); +} + +async fn clipboard_content() -> Result { + let permissions = web_sys::window().expect("No global `window` exists").navigator().permissions(); + if let Some(permissions) = permissions.ok().filter(|permissions| !permissions.is_undefined()) { + let descriptor = Object::new(); + let _ = Reflect::set(&descriptor, &"name".into(), &"clipboard-read".into()); + let status = match permissions.query(&descriptor) { + Ok(query) => JsFuture::from(query).await, + Err(error) => Err(error), + }; + match status.map(PermissionStatus::unchecked_from_js) { + Ok(status) if status.state() == PermissionState::Denied => return Err(READ_DENIED.to_string()), + Ok(_) => {} + Err(_) => return Err(READ_UNSUPPORTED.to_string()), + } + } + + let items = JsFuture::from(clipboard_read().map_err(|_| READ_UNSUPPORTED.to_string())?).await.map_err(describe)?; + let mut content = Vec::new(); + for item in Array::from(&items).iter().map(ClipboardItem::unchecked_from_js) { + for mime in item.types().iter().filter_map(|mime| mime.as_string()) { + let blob = JsFuture::from(item.get_type(&mime)).await.map_err(describe)?; + let data = JsFuture::from(Blob::unchecked_from_js(blob).array_buffer()).await.map_err(describe)?; + content.extend(DataTransferItem::from_raw(DataType::from_mime(&mime), RawData::Bytes(Uint8Array::new(&data).to_vec()))); + } + } + if content.is_empty() { + return Err(READ_NOTHING.to_string()); + } + Ok(DataTransfer(content)) +} + +fn describe(error: JsValue) -> String { + match error.dyn_into::() { + Ok(error) => error.to_string().into(), + Err(error) => format!("{error:?}"), + } +} + +pub(crate) fn ingest(data_transfer: &web_sys::DataTransfer, action: IngestAction) { + let items = data_transfer.items(); + let mut content = Vec::new(); + let mut files = Vec::new(); + for item in (0..items.length()).filter_map(|index| items.get(index)) { + let mime = item.type_(); + if item.kind() == "file" { + files.extend(item.get_as_file().ok().flatten().map(|file| (mime, file))); + } else if let Ok(text) = data_transfer.get_data(&mime) { + content.extend(DataTransferItem::from_raw(DataType::from_mime(&mime), RawData::Text(text))); + } + } + + wasm_bindgen_futures::spawn_local(async move { + for (mime, file) in files { + let Ok(data) = JsFuture::from(file.array_buffer()).await else { continue }; + let mime = Some(mime.as_str()).filter(|mime| !mime.is_empty()); + content.push(DataTransferItem::from_file(file.name().into(), mime, Uint8Array::new(&data).to_vec())); + } + let content = DataTransfer(content); + wrapper(|wrapper| wrapper.dispatch(IngestMessage::Ingest { content, action })); + }); +} diff --git a/frontend/wrapper/src/editor_commands.rs b/frontend/wrapper/src/editor_commands.rs index a9a609c1731..ae9695b51d4 100644 --- a/frontend/wrapper/src/editor_commands.rs +++ b/frontend/wrapper/src/editor_commands.rs @@ -7,6 +7,8 @@ use crate::editor_wrapper::EditorWrapper; use graphite_proc_macros::editor_commands; use serde::{Deserialize, Serialize}; +#[cfg(target_family = "wasm")] +use tsify::Ts; use tsify::Tsify; #[cfg(target_family = "wasm")] use wasm_bindgen::prelude::*; @@ -14,12 +16,12 @@ use wasm_bindgen::prelude::*; #[editor_commands] mod editor_commands { use crate::helpers::translate_key; - use editor::messages::clipboard::utility_types::ClipboardContentRaw; use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys; use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta}; use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport; + use editor::messages::portfolio::ingest::utility_types::DataTransferItem; use editor::messages::portfolio::utility_types::PanelGroupId; use editor::messages::prelude::*; use editor::messages::tool::tool_messages::tool_prelude::{DroppedFile, WidgetId}; @@ -94,7 +96,7 @@ mod editor_commands { } /// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that) - fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message { + fn widget_value_update(layout_target: Ts, widget_id: u64, value: Ts, resend_widget: bool) -> Message { let widget_id = WidgetId(widget_id); let update = LayoutMessage::WidgetValueUpdate { layout_target, @@ -111,7 +113,7 @@ mod editor_commands { } /// Commit the value of a given UI widget to the history - fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message { + fn widget_value_commit(layout_target: Ts, widget_id: u64, value: Ts) -> Message { LayoutMessage::WidgetValueCommit { layout_target, widget_id: WidgetId(widget_id), @@ -121,7 +123,7 @@ mod editor_commands { } /// Update the value of a given UI widget, and commit it to the history - fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message { + fn widget_value_commit_and_update(layout_target: Ts, widget_id: u64, value: Ts, resend_widget: bool) -> Message { let widget_id = WidgetId(widget_id); let mut messages: Vec = vec![ LayoutMessage::WidgetValueCommit { @@ -147,13 +149,13 @@ mod editor_commands { } /// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button) - fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message { + fn widget_value_drag_drop(layout_target: Ts, widget_id: u64) -> Message { let widget_id = WidgetId(widget_id); LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into() } /// Hand a file dropped on a UI widget to the widget's file drop callback - fn widget_value_file_drop(layout_target: LayoutTarget, widget_id: u64, name: String, mime_type: String, data: Vec) -> Message { + fn widget_value_file_drop(layout_target: Ts, widget_id: u64, name: String, mime_type: String, data: Vec) -> Message { let widget_id = WidgetId(widget_id); let file = DroppedFile { name, mime_type, data }; LayoutMessage::WidgetValueFileDrop { layout_target, widget_id, file }.into() @@ -161,7 +163,7 @@ mod editor_commands { /// Tokenizes a math expression widget's text as it is typed, for the reply to color and typeset it, and offers names to finish /// the one at the caret, where the caret is given. Unless they're `asked` for, names are offered only once part of one is typed. - fn analyze_math_expression(layout_target: LayoutTarget, widget_id: u64, source: String, caret: Option, asked: bool) -> Message { + fn analyze_math_expression(layout_target: Ts, widget_id: u64, source: String, caret: Option, asked: bool) -> Message { LayoutMessage::AnalyzeMathExpression { layout_target, widget_id: WidgetId(widget_id), @@ -187,11 +189,7 @@ mod editor_commands { } fn load_preferences(preferences: Option) -> Message { - let Some(preferences) = preferences else { return Message::NoOp }; - let Ok(preferences) = serde_json::from_str(&preferences) else { - log::error!("Failed to deserialize preferences"); - return Message::NoOp; - }; + let preferences = PreferencesMessageHandler::from_stored(preferences.as_deref()); PreferencesMessage::Load { preferences }.into() } @@ -208,6 +206,11 @@ mod editor_commands { DialogMessage::RequestNewDocumentDialog.into() } + /// Join the live session under `token` + fn join_session(token: String) -> Message { + SyncMessage::Join { token }.into() + } + fn trigger_auto_save(document_id: u64) -> Message { PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into() } @@ -255,7 +258,54 @@ mod editor_commands { .into() } - fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message { + /// Bring a panel to the front, reopening it if closed + fn focus_panel(panel_type: Ts) -> Message { + WorkspaceMessage::FocusPanel { panel_type }.into() + } + + /// Show or hide an interaction's deltas + fn expand_history_interaction(id: String, expanded: bool) -> Message { + HistoryMessage::Expand { id, expanded }.into() + } + + fn load_more_history() -> Message { + HistoryMessage::LoadMore.into() + } + + fn go_back_to_history_interaction(id: String) -> Message { + HistoryMessage::GoBack { id }.into() + } + + /// Remove one interaction and keep the later ones + fn remove_history_interaction(id: String) -> Message { + HistoryMessage::RemoveStep { id }.into() + } + + /// Redo an undone interaction, or reapply an abandoned one + fn bring_back_history_interaction(id: String) -> Message { + HistoryMessage::BringBack { id }.into() + } + + /// Show a branch's line, or the head's line when `id` is `None` + fn follow_history_branch(id: Option) -> Message { + HistoryMessage::Follow { id }.into() + } + + /// Put the steps not yet in history into it, when editing alone + fn retire_pending_history() -> Message { + HistoryMessage::RetirePending.into() + } + + /// Name an interaction. An empty label removes the name + fn rename_history_interaction(id: String, label: String) -> Message { + HistoryMessage::Rename { id, label }.into() + } + + fn tag_history_interaction(id: String, tag: String, on: bool) -> Message { + HistoryMessage::Tag { id, tag, on }.into() + } + + fn split_panel_group(target_group: u64, direction: Ts, tabs: Vec>, active_tab_index: usize) -> Message { WorkspaceMessage::SplitPanelGroup { target_group: PanelGroupId(target_group), direction, @@ -435,7 +485,7 @@ mod editor_commands { } /// Update primary color from sRGB bytes (the wire format at the JS boundary). - fn update_primary_color(color: SRGBA8) -> Message { + fn update_primary_color(color: Ts) -> Message { ToolMessage::SelectWorkingColor { color: Color::from(color), primary: true, @@ -444,7 +494,7 @@ mod editor_commands { } /// Update secondary color from sRGB bytes (the wire format at the JS boundary). - fn update_secondary_color(color: SRGBA8) -> Message { + fn update_secondary_color(color: Ts) -> Message { ToolMessage::SelectWorkingColor { color: Color::from(color), primary: false, @@ -453,7 +503,7 @@ mod editor_commands { } /// Initialize the Rust color picker handler with a starting value (used when the frontend `` opens). - fn open_color_picker(initial_value: FillChoiceSRGBA8, allow_none: bool, disabled: bool) -> Message { + fn open_color_picker(initial_value: Ts, allow_none: bool, disabled: bool) -> Message { ColorPickerMessage::Open { initial_value: FillChoice::from(&initial_value.0), allow_none, @@ -468,7 +518,7 @@ mod editor_commands { } /// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary). - fn update_gradient_stop_color(color: SRGBA8) -> Message { + fn update_gradient_stop_color(color: Ts) -> Message { GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into() } @@ -511,6 +561,11 @@ mod editor_commands { .into() } + /// Tell the backend which rows of the Data panel's table to send, from `start` up to but not including `end`, being those in or near view. + fn set_data_panel_rows_in_view(start: u32, end: u32) -> Message { + DataPanelMessage::SetRowsInView { rows: start as usize..end as usize }.into() + } + /// Select exactly the given nodes. fn select_nodes(ids: Vec) -> Message { NodeGraphMessage::SelectedNodesSet { @@ -632,6 +687,11 @@ mod editor_commands { NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into() } + /// Gives the network open in the graph its own editable copy of the built-in node contents it lies in + fn make_network_editable() -> Message { + DocumentMessage::MakeNetworkEditable.into() + } + /// Merge the selected nodes into a subnetwork fn merge_selected_nodes() -> Message { NodeGraphMessage::MergeSelectedNodes.into() @@ -660,46 +720,15 @@ mod editor_commands { } /// The pixels of an export that `TriggerExportImage` had the frontend rasterize, which the editor encodes and saves as the chosen file type - fn save_rasterized_export(name: String, file_type: FileType, width: u32, height: u32, data: Vec) -> Message { + fn save_rasterized_export(name: String, file_type: Ts, width: u32, height: u32, data: Vec) -> Message { PortfolioMessage::SaveRasterizedExport { name, file_type, width, height, data }.into() } /// A file headed for a known action, picked in the dialog that `TriggerBrowse` opened - fn ingest_picked(name: String, mime_type: String, data: Vec, action: IngestAction) -> Message { - IngestMessage::Ingest { - data, - action, - mime_type, - path: Some(PathBuf::from(name)), - } - .into() - } - - /// A file dropped on a panel or pasted, placed by the drop position or the layer slot it landed in - fn ingest_file(name: Option, mime_type: String, data: Vec, mouse_x: Option, mouse_y: Option, insert_parent_id: Option, insert_index: Option) -> Message { - let action = match (insert_parent_id.zip(insert_index), mouse_x.zip(mouse_y)) { - (Some((parent, insert_index)), _) => IngestAction::DropOnLayers { - parent: LayerNodeIdentifier::new_unchecked(NodeId(parent)), - insert_index, - }, - (None, Some(mouse)) => IngestAction::DropOnCanvas { mouse }, - (None, None) => IngestAction::Paste, - }; - IngestMessage::Ingest { - data, - action, - mime_type, - path: name.map(PathBuf::from), - } - .into() - } - - /// Paste from a serialized JSON representation - fn paste_text(data: String) -> Message { - ClipboardMessage::ReadClipboard { - content: ClipboardContentRaw::Text(data), - } - .into() + fn ingest_picked(name: String, mime_type: String, data: Vec, action: Ts) -> Message { + let mime = Some(mime_type.as_str()).filter(|mime| !mime.is_empty()); + let content = DataTransferItem::from_file(PathBuf::from(name), mime, data).into(); + IngestMessage::Ingest { content, action }.into() } /// Toggle visibility of a layer or node in the document network, as listed in the Layers panel @@ -883,7 +912,6 @@ mod editor_commands { #[cfg(feature = "editor")] #[derive(Debug, Clone, Serialize, Deserialize, Tsify)] -#[tsify(from_wasm_abi)] pub struct FillChoiceSRGBA8( /// Concrete wasm boundary form of the generic [`FillChoice`], since a `#[wasm_bindgen]` argument's TS declaration names its type without the generic's argument. #[tsify(type = "FillChoice")] @@ -893,7 +921,6 @@ pub struct FillChoiceSRGBA8( pub type FillChoiceSRGBA8 = Any; #[derive(Debug, Clone, Serialize, Deserialize, Tsify)] -#[tsify(from_wasm_abi)] pub struct Any(#[tsify(type = "any")] serde_json::Value); impl Any { #[cfg(feature = "editor")] @@ -918,6 +945,6 @@ editor_proxy_types! { IngestAction = editor::messages::portfolio::ingest::utility_types::IngestAction; LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget; DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection; - PanelTypes = Vec; + PanelType = editor::messages::portfolio::utility_types::PanelType; SRGBA8 = graphene_std::color::SRGBA8; } diff --git a/frontend/wrapper/src/editor_wrapper.rs b/frontend/wrapper/src/editor_wrapper.rs index f1dc255597b..bd5210e63be 100644 --- a/frontend/wrapper/src/editor_wrapper.rs +++ b/frontend/wrapper/src/editor_wrapper.rs @@ -7,18 +7,24 @@ use crate::EDITOR; use crate::MESSAGE_BUFFER; #[cfg(all(feature = "native", target_family = "wasm"))] use crate::editor_commands::EditorCommand; -#[cfg(feature = "editor")] -use crate::helpers::render_image_data_to_canvases; #[cfg(not(feature = "native"))] use crate::helpers::run_node_runtime; #[cfg(any(not(feature = "native"), target_family = "wasm"))] use crate::helpers::wrapper; use crate::helpers::{request_animation_frame, set_timeout}; +#[cfg(not(feature = "native"))] +use crate::intercept_frontend_message::intercept_frontend_message; use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY}; #[cfg(all(not(feature = "native"), target_family = "wasm"))] use editor::application::{Environment, Host, Platform}; +#[cfg(not(feature = "native"))] +use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; +#[cfg(not(feature = "native"))] +use editor::messages::portfolio::ingest::utility_types::IngestAction; #[cfg(feature = "editor")] use editor::messages::prelude::*; +#[cfg(not(feature = "native"))] +use graph_craft::document::NodeId; #[cfg(feature = "editor")] use serde::Serialize; use std::cell::RefCell; @@ -63,6 +69,9 @@ impl EditorWrapper { _ => unreachable!(), }; + let location = web_sys::window().expect("No global `window` exists").location(); + let url = format!("{}{}", location.origin().unwrap_or_default(), location.pathname().unwrap_or_default()); + let storage: std::sync::Arc = match OpfsResourceStorage::load("resources").await { Ok(storage) => std::sync::Arc::new(storage), Err(error) => { @@ -77,15 +86,15 @@ impl EditorWrapper { .with_editor( EditorBuilder::new() .with_wake(crate::helpers::wake_editor) - .with_environment(Environment { platform: Platform::Web, host }) + .with_environment(Environment { + platform: Platform::Web, + host, + url: url.leak(), + }) .with_resource_storage(storage) .with_document_store(document_store), ) - .with_runtime( - RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock)) - .with_wake(crate::helpers::wake_runtime) - .with_application_io(application_io), - ) + .with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io)) .with_spawner(crate::helpers::WasmSpawner) .with_random_seed(uuid_random_seed) .build(); @@ -123,23 +132,13 @@ impl EditorWrapper { }); // Send each `FrontendMessage` to the JavaScript frontend - for message in frontend_messages.into_iter() { + for message in frontend_messages.into_iter().filter_map(intercept_frontend_message) { self.send_frontend_message_to_js(message); } } #[cfg(feature = "editor")] pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) { - if let FrontendMessage::UpdateImageData { - ref image_data, - ref canvas_ids_in_use, - } = message - { - let images = image_data.iter().map(|image| (image.id, image.width, image.height, image.pixels.as_slice())); - render_image_data_to_canvases(images, canvas_ids_in_use); - return; - } - let message_type = message.to_discriminant().local_name(); let serializer = serde_wasm_bindgen::Serializer::new().serialize_large_number_types_as_bigints(true); @@ -197,14 +196,7 @@ impl EditorWrapper { *g.borrow_mut() = Some(Closure::new(move |_timestamp| { #[cfg(not(feature = "native"))] - { - if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock() - && let Some(runtime) = runtime.as_mut() - { - runtime.begin_frame(); - } - wasm_bindgen_futures::spawn_local(run_node_runtime()); - } + wasm_bindgen_futures::spawn_local(run_node_runtime(true)); #[cfg(any(not(feature = "native"), target_family = "wasm"))] wrapper(|wrapper| { @@ -261,7 +253,14 @@ impl EditorWrapper { /// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered) #[cfg(all(feature = "web", not(feature = "native")))] #[wasm_bindgen(js_name = loadPersistedState)] - pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) { + pub fn load_persisted_state(&self, state: tsify::Ts) { + let state = match state.to_rust() { + Ok(state) => state, + Err(e) => { + log::error!("Cannot convert state to type utility_types::PersistedState: {e:?}"); + return; + } + }; self.dispatch(PersistentStateMessage::LoadState { state }); } #[cfg(feature = "native")] @@ -269,4 +268,21 @@ impl EditorWrapper { pub fn load_persisted_state(&self, _state: JsValue) { log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively"); } + + #[cfg(not(feature = "native"))] + pub fn ingest(&self, data: &web_sys::DataTransfer, mouse_x: Option, mouse_y: Option, insert_parent_id: Option, insert_index: Option) { + let action = match (insert_parent_id.zip(insert_index), mouse_x.zip(mouse_y)) { + (Some((parent, insert_index)), _) => IngestAction::DropOnLayers { + parent: LayerNodeIdentifier::new_unchecked(NodeId(parent)), + insert_index, + }, + (None, Some(mouse)) => IngestAction::DropOnCanvas { mouse }, + (None, None) => IngestAction::Paste, + }; + crate::data_transfer::ingest(data, action); + } + #[cfg(feature = "native")] + pub fn ingest(&self, _data: JsValue, _mouse_x: Option, _mouse_y: Option, _insert_parent_id: Option, _insert_index: Option) { + log::error!("ingest is unavailable on desktop; drops and pastes are handled natively"); + } } diff --git a/frontend/wrapper/src/helpers.rs b/frontend/wrapper/src/helpers.rs index 725d7794ceb..2a3d12cfd5d 100644 --- a/frontend/wrapper/src/helpers.rs +++ b/frontend/wrapper/src/helpers.rs @@ -7,8 +7,12 @@ use editor::messages::input_mapper::utility_types::keyboard::Key; #[cfg(all(not(feature = "native"), target_family = "wasm"))] use editor::messages::prelude::*; #[cfg(all(not(feature = "native"), target_family = "wasm"))] -use editor::task::{Clock, Spawn, Task}; +use editor::task::{Spawn, Task}; +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +use graphene_std::runtime::Instant; use js_sys::{Object, Reflect}; +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +use std::cell::Cell; use std::cell::RefCell; use std::collections::HashSet; #[cfg(not(feature = "native"))] @@ -50,7 +54,7 @@ pub(crate) fn wrapper(callback: impl FnOnce(&mut EditorWrapper)) { } #[cfg(not(feature = "native"))] -pub(crate) async fn run_node_runtime() { +pub(crate) async fn run_node_runtime(update: bool) { // Process no further messages after a crash to avoid spamming the console if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { return; @@ -58,6 +62,9 @@ pub(crate) async fn run_node_runtime() { let Some(mut runtime) = crate::NODE_RUNTIME.try_lock() else { return }; let Some(runtime) = runtime.as_mut() else { return }; + if update { + runtime.update(); + } runtime.run().await; } @@ -70,16 +77,6 @@ impl Spawn for WasmSpawner { } } -#[cfg(all(not(feature = "native"), target_family = "wasm"))] -pub(crate) struct PerformanceClock; -#[cfg(all(not(feature = "native"), target_family = "wasm"))] -impl Clock for PerformanceClock { - fn now(&self) -> Duration { - let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`"); - Duration::from_secs_f64(performance.now() / 1000.) - } -} - /// Web editor wake: queues a microtask that dispatches [`Message::Wake`]. #[cfg(all(not(feature = "native"), target_family = "wasm"))] pub(crate) fn wake_editor() { @@ -88,10 +85,42 @@ pub(crate) fn wake_editor() { }); } -/// Web runtime wake: queues a run of the node runtime. Used to wake the runtime on async task completion. +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +thread_local! { + static IDLE_RUN_QUEUED: Cell = const { Cell::new(false) }; + static IDLE_PERIOD: RefCell> = const { RefCell::new(None) }; + static IDLE_RUN: Closure = Closure::new(|deadline| { + IDLE_RUN_QUEUED.set(false); + IDLE_PERIOD.set(Some((deadline, Instant::now()))); + wasm_bindgen_futures::spawn_local(run_node_runtime(false)); + }); +} + +/// Web runtime wake: runs the node runtime in the time left before the next frame, so it can't hold up the browser's painting +/// Within an idle period it runs again at once if the time the last run took still fits. #[cfg(all(not(feature = "native"), target_family = "wasm"))] pub(crate) fn wake_runtime() { - wasm_bindgen_futures::spawn_local(run_node_runtime()); + let fits = IDLE_PERIOD.with_borrow_mut(|period| { + period.as_mut().is_some_and(|(deadline, run_start)| { + let now = Instant::now(); + let fits = deadline.time_remaining() > (now - *run_start).as_secs_f64() * 1000.; + if fits { + *run_start = now; + } + fits + }) + }); + if fits { + wasm_bindgen_futures::spawn_local(run_node_runtime(false)); + return; + } + + let Some(window) = window() else { return }; + if Reflect::has(&window, &"requestIdleCallback".into()).unwrap_or(false) && !IDLE_RUN_QUEUED.replace(true) { + IDLE_RUN.with(|run| { + let _ = window.request_idle_callback(run.as_ref().unchecked_ref()); + }); + } } thread_local! { diff --git a/frontend/wrapper/src/intercept_frontend_message.rs b/frontend/wrapper/src/intercept_frontend_message.rs new file mode 100644 index 00000000000..e1976a3016e --- /dev/null +++ b/frontend/wrapper/src/intercept_frontend_message.rs @@ -0,0 +1,20 @@ +use crate::data_transfer; +use crate::helpers::render_image_data_to_canvases; +use editor::messages::prelude::FrontendMessage; + +pub(crate) fn intercept_frontend_message(message: FrontendMessage) -> Option { + match message { + FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use } => { + let images = image_data.iter().map(|image| (image.id, image.width, image.height, image.pixels.as_slice())); + render_image_data_to_canvases(images, &canvas_ids_in_use); + } + FrontendMessage::TriggerClipboardRead => { + data_transfer::read_clipboard(); + } + FrontendMessage::TriggerClipboardWrite { content } => { + data_transfer::write_clipboard(content); + } + m => return Some(m), + } + None +} diff --git a/frontend/wrapper/src/lib.rs b/frontend/wrapper/src/lib.rs index 8a92014b55e..223de2d3d8d 100644 --- a/frontend/wrapper/src/lib.rs +++ b/frontend/wrapper/src/lib.rs @@ -4,9 +4,13 @@ #[macro_use] extern crate log; +#[cfg(not(feature = "native"))] +mod data_transfer; pub mod editor_commands; pub mod editor_wrapper; pub mod helpers; +#[cfg(not(feature = "native"))] +mod intercept_frontend_message; pub mod native_communication; mod wasm_value; diff --git a/libraries/dyn-any/Cargo.toml b/libraries/dyn-any/Cargo.toml index 57604b3f25c..285b9e61e4d 100644 --- a/libraries/dyn-any/Cargo.toml +++ b/libraries/dyn-any/Cargo.toml @@ -30,7 +30,7 @@ glam = ["dep:glam"] dyn-any-derive = { path = "derive", optional = true } # Optional dependencies -glam = { version = "0.33", optional = true, default-features = false, features = ["all-types"] } +glam = { version = "0.34", optional = true, default-features = false, features = ["all-types"] } reqwest = { version = "0.13", optional = true, default-features = false } [package.metadata.docs.rs] diff --git a/libraries/dyn-any/src/lib.rs b/libraries/dyn-any/src/lib.rs index 047557a4b42..9761b23d623 100644 --- a/libraries/dyn-any/src/lib.rs +++ b/libraries/dyn-any/src/lib.rs @@ -213,13 +213,13 @@ unsafe impl StaticType for [T] { type Static = [::Static]; } -unsafe impl StaticType for dyn for<'i> DynAny<'_> + '_ { +unsafe impl StaticType for dyn DynAny<'_> + '_ { type Static = dyn DynAny<'static>; } -unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + Sync + '_ { +unsafe impl StaticType for dyn DynAny<'_> + Send + Sync + '_ { type Static = dyn DynAny<'static> + Send + Sync; } -unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + '_ { +unsafe impl StaticType for dyn DynAny<'_> + Send + '_ { type Static = dyn DynAny<'static> + Sync; } unsafe impl StaticType for dyn core::future::Future + Send + Sync + '_ { diff --git a/libraries/math-parser/Cargo.toml b/libraries/math-parser/Cargo.toml index 25975a5867b..7031dee9f35 100644 --- a/libraries/math-parser/Cargo.toml +++ b/libraries/math-parser/Cargo.toml @@ -18,6 +18,7 @@ workspace = true thiserror = "2.0" num-complex = "0.4" unicode-ident = "1.0" +# This is intentionally not upgraded since the cache API was removed for soundness https://codeberg.org/zesterer/chumsky/pulls/980 chumsky = { version = "0.10", default-features = false, features = ["std", "unstable"] } [dev-dependencies] diff --git a/libraries/math-parser/src/constants.rs b/libraries/math-parser/src/constants.rs index bf28c39297f..a56ee874749 100644 --- a/libraries/math-parser/src/constants.rs +++ b/libraries/math-parser/src/constants.rs @@ -532,7 +532,8 @@ pub fn builtin_function(name: &str) -> Option { }; // An odd root of a negative real is real, where `powf` alone would climb to the principal complex root if let Some(x) = x.as_real() - && x < 0. && n.rem_euclid(2.) == 1. + && x < 0. + && n.rem_euclid(2.) == 1. { return Some(Value::from_f64(-(-x).powf(1. / n))); } diff --git a/libraries/math-parser/src/parser.rs b/libraries/math-parser/src/parser.rs index 7288099df8b..dc08d7fa441 100644 --- a/libraries/math-parser/src/parser.rs +++ b/libraries/math-parser/src/parser.rs @@ -17,6 +17,12 @@ impl ParseError { pub fn messages(&self) -> &[ErrorMessage] { &self.0 } + + /// The error of a source that should be a lone operator or function name but isn't, spanning the given range of it. + pub(crate) fn lone_reducer_expected(span: Range) -> Self { + let message = ErrorMessage::from_prose("Expected a lone operator like `+` or a function name like `max`"); + Self(vec![ErrorMessage { span: Some(span), ..message }]) + } } impl fmt::Display for ParseError { diff --git a/libraries/math-parser/src/reducer.rs b/libraries/math-parser/src/reducer.rs index 63e20b21caf..f8eaf207a71 100644 --- a/libraries/math-parser/src/reducer.rs +++ b/libraries/math-parser/src/reducer.rs @@ -1,10 +1,11 @@ use crate::ast::BinaryOp; use crate::constants::{Builtin, BuiltinFunction, builtin_function}; -use crate::context::ValueProvider; +use crate::context::{NothingMap, ValueProvider}; use crate::executer::settle_matrix; use crate::lexer::{Lexer, Token}; use crate::matrix::Matrix; use crate::object::Object; +use crate::parser::ParseError; use crate::value::{Number, Value}; use std::cmp::Ordering; use std::collections::HashSet; @@ -80,6 +81,17 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option Option { + if source.trim().is_empty() || classify_reducer(source, NothingMap).is_some() { + return None; + } + + // The whole source is wrong rather than any part of it, so the error spans all of it but the whitespace around it + let start = source.len() - source.trim_start().len(); + Some(ParseError::lone_reducer_expected(start..source.trim_end().len())) +} + impl Reducer { /// Evaluates this reducer across the given items, or `None` for an ill-formed application, like a NaN item, a fold of an /// empty list under an operator with no identity element, or an indeterminate result, since no operation produces NaN. @@ -87,8 +99,69 @@ impl Reducer { if items.iter().any(|Value::Number(number)| number.is_nan()) { return None; } - let Value::Number(result) = self.evaluate_unsettled(items)?; - (!result.is_nan()).then(|| Value::Number(result.canonical())) + settle(self.evaluate_unsettled(items)?) + } + + /// Evaluates this reducer across each leading run of the items, the first item alone, then the first two, and so on, giving for + /// each run exactly what [`Self::evaluate`] gives for it. Once a fold step fails, every longer run fails with it. + pub fn evaluate_running(&self, items: &[Value]) -> Vec> { + // A NaN item makes every run containing it ill-formed + let valid_count = items.iter().position(|Value::Number(number)| number.is_nan()).unwrap_or(items.len()); + let valid_items = &items[..valid_count]; + + // Items take canonical form first, as in `evaluate_unsettled` + let numbers = valid_items.iter().map(|Value::Number(number)| number.canonical()); + let mut results: Vec> = match self { + // O(n) by folding each item into the previous run's result + Reducer::FoldLeft(op) => { + let mut accumulated: Option = None; + numbers + .enumerate() + .map(|(index, item)| { + accumulated = match index { + // A lone item meets no operator, so logic checks it is a truth value here + 0 if matches!(op, BinaryOp::And | BinaryOp::Or) => item.as_bool().map(|_| item), + 0 => Some(item), + _ => accumulated.and_then(|accumulated| accumulated.binary_op(*op, item)), + }; + accumulated.and_then(|accumulated| settle(Value::Number(accumulated))) + }) + .collect() + } + + // O(n) by checking only the newest adjacent pair against the previous run's result + Reducer::ChainAdjacent(op) => { + let mut satisfied = Some(true); + let mut previous = None; + numbers + .map(|number| { + if let Some(previous) = previous { + satisfied = satisfied.and_then(|satisfied| adjacent_holds(*op, previous, number).map(|holds| satisfied && holds)); + } + previous = Some(number); + satisfied.and_then(|satisfied| settle(Value::from_bool(satisfied))) + }) + .collect() + } + + // O(n) by keeping the set of items seen so far + Reducer::ChainDistinct => { + let mut seen = HashSet::new(); + let mut distinct = true; + numbers + .map(|number| { + distinct &= seen.insert(CanonicalBits::of(number)); + settle(Value::from_bool(distinct)) + }) + .collect() + } + + // O(n²) since `^` groups from the right and a variadic builtin reads its whole list, so no run builds on a shorter one's result + Reducer::FoldRight(_) | Reducer::Function { .. } => (1..=valid_count).map(|count| self.evaluate(&valid_items[..count])).collect(), + }; + + results.resize(items.len(), None); + results } fn evaluate_unsettled(&self, items: &[Value]) -> Option { @@ -138,13 +211,7 @@ impl Reducer { match self { Reducer::FoldLeft(op) => { - let combine: fn(Matrix, Matrix) -> Option = match op { - BinaryOp::Add => |a, b| Some(a + b), - BinaryOp::Sub => |a, b| Some(a - b), - BinaryOp::Mul => |a, b| Some(a.compose(b)), - BinaryOp::Div => |a, b| Some(a.compose(b.inverse()?)), - _ => return None, - }; + let combine = matrix_fold_step(*op)?; let mut iter = items.iter().copied(); let Some(first) = iter.next() else { @@ -161,6 +228,60 @@ impl Reducer { Reducer::FoldRight(_) | Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => None, } } + + /// Evaluates this reducer across each leading run of the matrices, the first alone, then the first two, and so on, giving for + /// each run exactly what [`Self::evaluate_matrices`] gives for it. Under `*`, each result is where that many steps end up. + pub fn evaluate_running_matrices(&self, items: &[Matrix]) -> Vec> { + // A NaN item makes every run containing it ill-formed + let valid_count = items.iter().position(|matrix| matrix.is_nan()).unwrap_or(items.len()); + let valid_items = &items[..valid_count]; + + let mut results: Vec> = match self { + // O(n) by folding each matrix into the previous run's result + Reducer::FoldLeft(op) => match matrix_fold_step(*op) { + Some(combine) => { + let mut accumulated: Option = None; + valid_items + .iter() + .enumerate() + .map(|(index, &matrix)| { + accumulated = match index { + 0 => Some(matrix), + _ => accumulated.and_then(|accumulated| settle_matrix(combine(accumulated, matrix)?).ok()), + }; + accumulated.map(Object::from) + }) + .collect() + } + None => Vec::new(), + }, + + // O(n²) since a matrix function is an opaque function of its whole list + Reducer::Function { over_matrices, .. } => (1..=valid_count).map(|count| over_matrices.and_then(|function| function(&valid_items[..count]))).collect(), + + Reducer::FoldRight(_) | Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => Vec::new(), + }; + + results.resize(items.len(), None); + results + } +} + +/// A reducer's result in canonical form, or `None` for an indeterminate result, since no operation produces NaN. +fn settle(Value::Number(result): Value) -> Option { + (!result.is_nan()).then(|| Value::Number(result.canonical())) +} + +/// How a fold combines its running matrix with the next one: `*` and `/` compose in list order, while `+` and `-` are pointwise. +/// Any other operator has no action across matrices. +fn matrix_fold_step(op: BinaryOp) -> Option Option> { + Some(match op { + BinaryOp::Add => |a, b| Some(a + b), + BinaryOp::Sub => |a, b| Some(a - b), + BinaryOp::Mul => |a, b| Some(a.compose(b)), + BinaryOp::Div => |a, b| Some(a.compose(b.inverse()?)), + _ => return None, + }) } /// Whether every adjacent pair of items satisfies the chain's relation: true over zero or one items, since no pair exists to fail @@ -430,4 +551,35 @@ mod tests { } assert_eq!(reduce("+", &[scale, Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN))]), None); } + + #[test] + fn running_results_match_each_leading_run() { + // Between them, the lists hold repeats, descents, a zero divisor, a NaN, and items that aren't truth values + let lists: [&[f64]; 6] = [&[3., 1., 4., 1., 5.], &[2., 0., 3.], &[1., 1., 0., 1.], &[0.5, 2., -1., 2.], &[1., f64::NAN, 2.], &[]]; + for source in ["+", "-", "*", "/", "&&", "||", "^", "<", "<=", "==", "!=", "min", "max", "mean", "count"] { + let reducer = classify_reducer(source, NothingMap).unwrap(); + for list in lists { + let items: Vec = list.iter().map(|&item| Value::from_f64(item)).collect(); + let expected: Vec> = (1..=items.len()).map(|count| reducer.evaluate(&items[..count])).collect(); + assert_eq!(reducer.evaluate_running(&items), expected, "`{source}` over {list:?}"); + } + } + } + + #[test] + fn running_matrix_results_match_each_leading_run() { + let scale = Matrix::scale(Quaternion::new(2., 0., 0., 0.)); + let shift = Matrix::IDENTITY.translated(Quaternion::I); + let nan = Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN)); + + // Between them, the lists hold a singular divisor and a NaN + let lists: [&[Matrix]; 4] = [&[scale, shift, scale, shift], &[shift, Matrix::ZERO, scale], &[scale, nan, shift], &[]]; + for source in ["*", "/", "+", "-", "mean", "count", "<", "min"] { + let reducer = classify_reducer(source, NothingMap).unwrap(); + for (list_index, list) in lists.into_iter().enumerate() { + let expected: Vec> = (1..=list.len()).map(|count| reducer.evaluate_matrices(&list[..count])).collect(); + assert_eq!(reducer.evaluate_running_matrices(list), expected, "`{source}` over list {list_index}"); + } + } + } } diff --git a/node-graph/README.md b/node-graph/README.md index b63e711937b..01a82ab0c03 100644 --- a/node-graph/README.md +++ b/node-graph/README.md @@ -14,7 +14,6 @@ pub struct DocumentNode { pub call_argument: Type, pub implementation: DocumentNodeImplementation, pub visible: bool, - pub skip_deduplication: bool, pub compile_metadata: Option, pub original_location: OriginalLocation, } @@ -139,7 +138,7 @@ When the document graph is executed, the following steps occur: - The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation. - The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes. -The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize and monitor nodes. +The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize nodes. ## Debugging diff --git a/node-graph/graph-craft/Cargo.toml b/node-graph/graph-craft/Cargo.toml index 506628b2c02..9bdde0b8091 100644 --- a/node-graph/graph-craft/Cargo.toml +++ b/node-graph/graph-craft/Cargo.toml @@ -87,6 +87,8 @@ graph-craft = { workspace = true, features = ["loading"] } pretty_assertions = { workspace = true } criterion = { workspace = true } gungraun = { workspace = true } +document-loader = { workspace = true } +futures = { workspace = true } # Benchmarks [[bench]] diff --git a/node-graph/graph-craft/benches/compile_demo_art_criterion.rs b/node-graph/graph-craft/benches/compile_demo_art_criterion.rs index a614f8dbcfe..45cc658cb28 100644 --- a/node-graph/graph-craft/benches/compile_demo_art_criterion.rs +++ b/node-graph/graph-craft/benches/compile_demo_art_criterion.rs @@ -2,13 +2,16 @@ use std::hint::black_box; use criterion::{Criterion, criterion_group, criterion_main}; use graph_craft::util::DEMO_ART; +use std::path::Path; fn compile_to_proto(c: &mut Criterion) { - use graph_craft::util::{compile, load_from_name}; + use graph_craft::util::compile; let mut c = c.benchmark_group("Compile Network cold"); for name in DEMO_ART { - let network = load_from_name(name); + let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite")))) + .unwrap() + .network; c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput)); } } diff --git a/node-graph/graph-craft/benches/compile_demo_art_gungraun.rs b/node-graph/graph-craft/benches/compile_demo_art_gungraun.rs index 176df58ba84..dbabbb3f842 100644 --- a/node-graph/graph-craft/benches/compile_demo_art_gungraun.rs +++ b/node-graph/graph-craft/benches/compile_demo_art_gungraun.rs @@ -1,9 +1,16 @@ use graph_craft::document::NodeNetwork; use graph_craft::util::*; use gungraun::prelude::*; +use std::path::Path; + +fn open_demo_artwork(name: &str) -> NodeNetwork { + futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite")))) + .unwrap() + .network +} #[library_benchmark] -#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)] +#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = open_demo_artwork)] pub fn compile_to_proto(_input: NodeNetwork) { std::hint::black_box(compile(_input)); } diff --git a/node-graph/graph-craft/src/application_io/resource/mmap.rs b/node-graph/graph-craft/src/application_io/resource/mmap.rs index c5d618f469c..d481fad2c77 100644 --- a/node-graph/graph-craft/src/application_io/resource/mmap.rs +++ b/node-graph/graph-craft/src/application_io/resource/mmap.rs @@ -149,7 +149,7 @@ struct MmappedBytes(MemoryMappedFile); impl AsRef<[u8]> for MmappedBytes { fn as_ref(&self) -> &[u8] { let len = self.0.len(); - match self.0.as_slice(0, len) { + match self.0.as_slice_bytes(0, len) { Ok(slice) => slice, Err(error) => { log::error!("Failed to obtain mmap slice: {error}"); diff --git a/node-graph/graph-craft/src/application_io/resource/opfs.rs b/node-graph/graph-craft/src/application_io/resource/opfs.rs index 40064806604..c153f351dbb 100644 --- a/node-graph/graph-craft/src/application_io/resource/opfs.rs +++ b/node-graph/graph-craft/src/application_io/resource/opfs.rs @@ -1,5 +1,6 @@ use graphene_application_io::resource::{LoadResource, Resource, ResourceFuture, ResourceHash, ResourceStorage}; use js_sys::Uint8Array; +use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet, VecDeque}; use std::pin::Pin; use std::sync::{Arc, Mutex}; @@ -57,9 +58,6 @@ impl LoadResource for OpfsResourceStorage { let resource = resource.clone(); return Box::pin(async move { Some(resource) }); } - if !guard.on_disk.contains(&hash) { - return Box::pin(async move { None }); - } } let (sender, receiver) = oneshot(); @@ -77,9 +75,9 @@ impl ResourceStorage for OpfsResourceStorage { let mut guard = self.inner.lock().unwrap(); let mut bytes = None; - if !guard.cache.contains_key(&hash) { + if let Entry::Vacant(entry) = guard.cache.entry(hash) { let resource_bytes = Arc::<[u8]>::from(data); - guard.cache.insert(hash, Resource::new_unchecked(resource_bytes.clone(), hash)); + entry.insert(Resource::new_unchecked(resource_bytes.clone(), hash)); bytes = Some(resource_bytes); } @@ -218,15 +216,13 @@ async fn delete_file(directory: &FileSystemDirectoryHandle, hash: &ResourceHash) } async fn read_from_opfs(inner: Arc>, hash: ResourceHash) -> Option { - let directory = { + // Another tab may have written a file this tab's listing predates, so one it doesn't know of is still looked for + let (directory, known) = { let guard = inner.lock().unwrap(); if let Some(resource) = guard.cache.get(&hash) { return Some(resource.clone()); } - if !guard.on_disk.contains(&hash) { - return None; - } - guard.directory.clone() + (guard.directory.clone(), guard.on_disk.contains(&hash)) }; let name = file_name(&hash); @@ -238,7 +234,10 @@ async fn read_from_opfs(inner: Arc>, hash: ResourceHash) -> Option< return None; } }, - Err(error) if is_not_found(&error) => return None, + Err(error) if is_not_found(&error) => { + inner.lock().unwrap().on_disk.remove(&hash); + return None; + } Err(error) => { log::error!("OPFS getFileHandle for {hash} failed: {error:?}"); return None; @@ -279,9 +278,10 @@ async fn read_from_opfs(inner: Arc>, hash: ResourceHash) -> Option< if let Some(resource) = guard.cache.get(&hash) { return Some(resource.clone()); } - if !guard.on_disk.contains(&hash) { + if known && !guard.on_disk.contains(&hash) { return None; } + guard.on_disk.insert(hash); guard.cache.insert(hash, resource.clone()); Some(resource) diff --git a/node-graph/graph-craft/src/compiler/flatten.rs b/node-graph/graph-craft/src/compiler/flatten.rs new file mode 100644 index 00000000000..054d3b8854f --- /dev/null +++ b/node-graph/graph-craft/src/compiler/flatten.rs @@ -0,0 +1,446 @@ +use crate::document::value::TaggedValue; +use crate::document::*; +use core_types::{ProtoNodeIdentifier, concrete}; +use rustc_hash::FxHashMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +/// Hash two IDs together, returning a new ID that is always consistent for two input IDs in a specific order. +/// This is used during [`NodeNetwork::flatten`] in order to ensure consistent yet non-conflicting IDs for inner networks. +fn merge_ids(a: NodeId, b: NodeId) -> NodeId { + let mut hasher = DefaultHasher::new(); + a.hash(&mut hasher); + b.hash(&mut hasher); + NodeId(hasher.finish()) +} + +impl DocumentNode { + /// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`]. + pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize) { + let (index, _) = self + .inputs + .iter() + .enumerate() + .nth(offset) + .unwrap_or_else(|| panic!("no network input found for {self:#?} and offset: {offset}")); + + self.inputs[index] = NodeInput::Node { node_id, output_index }; + } +} + +impl NodeNetwork { + /// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and observing node values. + /// + /// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry. + pub fn generate_node_paths(&mut self, prefix: &[NodeId]) { + let definitions = std::mem::take(&mut self.definitions); + self.generate_node_paths_with(prefix, &definitions); + self.definitions = definitions; + } + + fn generate_node_paths_with(&mut self, prefix: &[NodeId], definitions: &FxHashMap) { + for (node_id, node) in &mut self.nodes { + let mut new_path = prefix.to_vec(); + if !self.generated { + new_path.push(*node_id); + } + if let DocumentNodeImplementation::Network(network) = &mut node.implementation { + network.generate_node_paths_with(new_path.as_slice(), definitions); + } + if node.original_location.path.is_some() { + log::warn!("Attempting to overwrite node path"); + } else { + node.original_location.path = Some(new_path); + let output_count = output_count_in(&node.implementation, definitions).unwrap_or(1); + node.original_location.dependants = vec![Vec::new(); output_count]; + } + } + } + + /// A copy of table entry `id` for the instance at `instance_path`, with its node paths and dependant slots in place. + fn instantiate_definition(&self, id: NetworkId, instance_path: &[NodeId]) -> Option { + let mut instance = self.definitions.get(&id)?.clone(); + instance.generate_node_paths_with(instance_path, &self.definitions); + Some(instance) + } + + pub fn populate_dependants(&mut self) { + let mut dep_changes = Vec::new(); + for (node_id, node) in &mut self.nodes { + let len = node.original_location.dependants.len(); + let output_count = output_count_in(&node.implementation, &self.definitions).unwrap_or(len); + node.original_location.dependants.extend(vec![vec![]; output_count.max(len) - len]); + for input in &node.inputs { + if let NodeInput::Node { node_id: dep_id, output_index, .. } = input { + dep_changes.push((*dep_id, *output_index, *node_id)); + } + } + } + // println!("{:#?}", self.nodes.get(&NodeId(1))); + for (dep_id, output_index, node_id) in dep_changes { + let node = self.nodes.get_mut(&dep_id).expect("Encountered invalid node id"); + let len = node.original_location.dependants.len(); + // One must be added to the index to find the length because indexing in rust starts from 0. + node.original_location.dependants.extend(vec![vec![]; (output_index + 1).max(len) - len]); + // println!("{node_id} {output_index} {}", node.implementation.output_count()); + node.original_location.dependants[output_index].push(node_id); + } + } + + /// Replace all references in any node of `old_input` with `new_input` + fn replace_node_inputs(&mut self, node_id: NodeId, old_input: (NodeId, usize), new_input: (NodeId, usize)) { + let Some(node) = self.nodes.get_mut(&node_id) else { return }; + node.inputs.iter_mut().for_each(|input| { + if let NodeInput::Node { node_id: input_id, output_index, .. } = input + && (*input_id, *output_index) == old_input + { + (*input_id, *output_index) = new_input; + } + }); + } + + /// Replace all references in any node of `old_output` with `new_output` + fn replace_network_outputs(&mut self, old_output: &NodeInput, new_output: &NodeInput) { + for output in self.exports.iter_mut() { + if *output == *old_output { + *output = new_output.clone(); + } + } + } + + /// Removes unused nodes from the graph. Returns a list of booleans which represent if each of the inputs have been retained. + pub fn remove_dead_nodes(&mut self, number_of_inputs: usize) -> Vec { + // Take all the nodes out of the nodes list + let mut old_nodes = std::mem::take(&mut self.nodes); + + let mut stack = self + .exports + .iter() + .filter_map(|output| if let NodeInput::Node { node_id, .. } = output { Some(*node_id) } else { None }) + .collect::>(); + while let Some(node_id) = stack.pop() { + let Some((node_id, mut document_node)) = old_nodes.remove_entry(&node_id) else { + continue; + }; + // Remove dead nodes from child networks + if let DocumentNodeImplementation::Network(network) = &mut document_node.implementation { + // Remove inputs to the parent node if they have been removed from the child + let mut retain_inputs = network.remove_dead_nodes(document_node.inputs.len()).into_iter(); + document_node.inputs.retain(|_| retain_inputs.next().unwrap_or(true)) + } + // Visit all nodes that this node references + stack.extend( + document_node + .inputs + .iter() + .filter_map(|input| if let NodeInput::Node { node_id, .. } = input { Some(node_id) } else { None }), + ); + // Add the node back to the list of nodes + self.nodes.insert(node_id, document_node); + } + + // Remove references to nodes that have been deleted + for node in self.nodes.values_mut() { + for dependants in &mut node.original_location.dependants { + dependants.retain(|dependant| !old_nodes.contains_key(dependant)); + } + } + + // Check if inputs are used and store for return value + let mut are_inputs_used = vec![false; number_of_inputs]; + for node in &self.nodes { + for node_input in &node.1.inputs { + if let NodeInput::Import { import_index, .. } = node_input + && let Some(is_used) = are_inputs_used.get_mut(*import_index) + { + *is_used = true; + } + } + } + are_inputs_used + } + + /// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network. + pub fn flatten(&mut self, node_id: NodeId) { + self.flatten_with_fns(node_id, merge_ids, NodeId::new) + } + + /// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network. + pub fn flatten_with_fns(&mut self, node_id: NodeId, map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, gen_id: impl Fn() -> NodeId + Copy) { + let Some((id, mut node)) = self.nodes.remove_entry(&node_id) else { + warn!("The node which was supposed to be flattened does not exist in the network, id {node_id} network {self:#?}"); + return; + }; + + // If the node is hidden, replace it with a passthrough node + let passthrough_node = DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER); + if !node.visible && node.implementation != passthrough_node { + node.implementation = passthrough_node; + + // A node without inputs has nothing to pass through, so it passes through the unit value instead + if node.inputs.is_empty() { + node.inputs.push(NodeInput::value(TaggedValue::None, false)); + } + + // Keep only the primary input, which the passthrough forwards + let removed_inputs = node.inputs.split_off(1); + + // Remove the dependants on the ignored inputs + for removed_input in removed_inputs { + if let NodeInput::Node { node_id, output_index } = removed_input + && let Some(former_dependency) = self.nodes.get_mut(&node_id) + // Ensure that the other node inputs do not also reference the dependency + && !node.inputs.iter().any(|input| matches!(input, NodeInput::Node { node_id: other, .. } if *other == node_id)) + { + former_dependency.original_location.dependants[output_index].retain(|&dependant| dependant != id); + } + } + + // Removing the passthrough later splices its input into its consumers, which accept only node wires, so an unwired input becomes a value node + let path = node.original_location.path.clone().unwrap_or_default(); + Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); + + node.call_argument = concrete!(()); + self.nodes.insert(id, node); + return; + } + + let path = node.original_location.path.clone().unwrap_or_default(); + + // Replace value inputs with dedicated value nodes + if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) { + Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); + } + + if let DocumentNodeImplementation::Definition(definition) = node.implementation { + let Some(instance) = self.instantiate_definition(definition, &path) else { + log::error!("Node {id} names definition {definition:?}, which the definitions table lacks"); + self.nodes.insert(id, node); + return; + }; + node.implementation = DocumentNodeImplementation::Network(instance); + } + + let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else { + // If the node is not a network, it is a primitive node and can be inserted into the network as is. + assert!(!self.nodes.contains_key(&id), "Trying to insert a node into the network caused an id conflict"); + + self.nodes.insert(id, node); + return; + }; + debug_assert!( + node.compile_metadata.is_none(), + "Network {id} should not have compile metadata: {compile_metadata:#?}", + compile_metadata = node.compile_metadata + ); + + // Replace value and reflection imports with value nodes, added inside nested network + Self::replace_value_inputs_with_nodes( + &mut inner_network.exports, + &mut inner_network.nodes, + node.original_location.path.as_ref().unwrap_or(&vec![]), + gen_id, + map_ids, + id, + ); + + // Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node. + inner_network.map_ids(|inner_id| map_ids(id, inner_id)); + inner_network.populate_dependants(); + let new_nodes = inner_network.nodes.keys().cloned().collect::>(); + + for (key, value) in inner_network.scope_injections.into_iter() { + match self.scope_injections.entry(key) { + std::collections::hash_map::Entry::Occupied(o) => { + log::warn!("Found duplicate scope injection for key {}, ignoring", o.key()); + } + std::collections::hash_map::Entry::Vacant(v) => { + v.insert(value); + } + } + } + + // Match the document node input and the inputs of the inner network + for (nested_node_id, mut nested_node) in inner_network.nodes.into_iter() { + for (nested_input_index, nested_input) in nested_node.clone().inputs.iter().enumerate() { + if let NodeInput::Import { import_index, .. } = nested_input { + let parent_input = node + .inputs + .get(*import_index) + .unwrap_or_else(|| panic!("Import index {import_index} of network node implementation {:?} should always exist", nested_node.implementation)); + match *parent_input { + // If the input to self is a node, connect the corresponding output of the inner network to it + NodeInput::Node { node_id, output_index } => { + nested_node.populate_first_network_input(node_id, output_index, nested_input_index); + let input_node = self.nodes.get_mut(&node_id).unwrap_or_else(|| panic!("Unable to find input node {node_id:?}")); + input_node.original_location.dependants[output_index].push(nested_node_id); + } + NodeInput::Import { import_index, .. } => { + let parent_input_index = import_index; + let Some(NodeInput::Import { import_index, .. }) = nested_node.inputs.get_mut(nested_input_index) else { + log::error!("Nested node should have a network input"); + continue; + }; + *import_index = parent_input_index; + } + NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"), + NodeInput::Scope(_) => unreachable!("Scope inputs should have been resolved by resolve_scope_inputs_recursive before flattening"), + NodeInput::Reflection(_) => unreachable!("Reflection inputs should have been replaced with value nodes"), + } + } + } + self.nodes.insert(nested_node_id, nested_node); + } + + // Remove the newly flattened node from the dependants + for parent_input in &node.inputs { + if let NodeInput::Node { node_id, output_index } = *parent_input + && let Some(input_node) = self.nodes.get_mut(&node_id) + { + input_node.original_location.dependants[output_index].retain(|&dependant| dependant != id); + } + } + + // TODO: Add support for flattening exports that are NodeInput::Import (https://github.com/GraphiteEditor/Graphite/issues/1762) + + self.replace_node_with_its_exports(id, &node.original_location, &inner_network.exports); + + for node_id in new_nodes { + self.flatten_with_fns(node_id, map_ids, gen_id); + } + } + + /// Connect all nodes that were previously connected to this node to the nodes of the inner network + fn replace_node_with_its_exports(&mut self, id: NodeId, original_location: &OriginalLocation, exports: &[NodeInput]) { + for (i, export) in exports.iter().enumerate() { + if let NodeInput::Node { node_id, output_index, .. } = &export { + for deps in &original_location.dependants { + for dep in deps { + self.replace_node_inputs(*dep, (id, i), (*node_id, *output_index)); + } + } + + if let Some(new_output_node) = self.nodes.get_mut(node_id) { + for dep in &original_location.dependants[i] { + new_output_node.original_location.dependants[*output_index].push(*dep); + } + + // Remove references from dependants on wrapper + new_output_node.original_location.dependants[*output_index].retain(|&dependant| dependant != id); + } + } + + self.replace_network_outputs(&NodeInput::node(id, i), export); + } + } + + #[inline(never)] + fn replace_value_inputs_with_nodes( + inputs: &mut [NodeInput], + collection: &mut FxHashMap, + path: &[NodeId], + gen_id: impl Fn() -> NodeId + Copy, + map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, + id: NodeId, + ) { + // Replace value exports and imports with value nodes, added inside the nested network + for export in inputs { + let previous_export = std::mem::replace(export, NodeInput::import(concrete!(()), 0)); + + let (tagged_value, exposed) = match previous_export { + NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed), + NodeInput::Reflection(reflect) => match reflect { + DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false), + DocumentNodeMetadata::SourceId => (TaggedValue::SourceId(core_types::SourceId::from_path(path)).into(), false), + }, + previous_export => { + *export = previous_export; + continue; + } + }; + let value_node_id = gen_id(); + let merged_node_id = map_ids(id, value_node_id); + let mut original_location = OriginalLocation { + path: Some(path.to_vec()), + dependants: vec![vec![id]], + ..Default::default() + }; + + if let Some(path) = &mut original_location.path { + path.push(value_node_id); + } + collection.insert( + merged_node_id, + DocumentNode { + inputs: vec![NodeInput::Value { tagged_value, exposed }], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), + original_location, + ..Default::default() + }, + ); + *export = NodeInput::Node { + node_id: merged_node_id, + output_index: 0, + }; + } + } + + fn remove_passthrough_node(&mut self, passthrough_id: NodeId) { + let node = self.nodes.remove(&passthrough_id).unwrap_or_else(|| panic!("Node with id {passthrough_id} does not exist")); + + let implementation = &node.implementation; + assert!( + matches!(implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER), + "remove_passthrough_node was given a node {implementation:?} and id {passthrough_id:?}", + ); + assert_eq!(node.inputs.len(), 1, "Passthrough node has more than one input"); + + // Consider the upstream node (the input to the passthrough) + if let NodeInput::Node { + node_id: upstream_node_id, + output_index: upstream_output_index, + .. + } = node.inputs[0] + && let Some(upstream_node) = self.nodes.get_mut(&upstream_node_id) + { + let dependants_of_upstream = &mut upstream_node.original_location.dependants[upstream_output_index]; + // Add our dependants to the list of dependants + dependants_of_upstream.extend(node.original_location.dependants[0].iter().copied()); + // Remove ourselves from the list of dependants + dependants_of_upstream.retain(|&dependant| dependant != passthrough_id); + }; + + // Check if the passthrough output is connected to a network export + for node_input in self.exports.iter_mut() { + if matches!(node_input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) { + *node_input = node.inputs[0].clone(); + } + } + + // Look at all downstream nodes + for &dependant_id in &node.original_location.dependants[0] { + let Some(dependant_node) = self.nodes.get_mut(&dependant_id) else { + error!("remove_passthrough_node got a dependant id {dependant_id:?} that did not exist in the network\n{self:#?}"); + continue; + }; + for input in dependant_node.inputs.iter_mut() { + if matches!(input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) { + *input = node.inputs[0].clone(); + } + } + } + } + + /// Strips out all [`graphene_core::ops::PassthroughNode`]s. + pub fn remove_all_passthrough_nodes(&mut self) { + let passthrough_nodes = self + .nodes + .iter() + .filter(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER)) + .map(|(id, _)| *id) + .collect::>(); + for id in passthrough_nodes { + self.remove_passthrough_node(id); + } + } +} diff --git a/node-graph/graph-craft/src/compiler/flatten_tests.rs b/node-graph/graph-craft/src/compiler/flatten_tests.rs new file mode 100644 index 00000000000..7c8670fa90a --- /dev/null +++ b/node-graph/graph-craft/src/compiler/flatten_tests.rs @@ -0,0 +1,310 @@ +use crate::document::document_tests::add_network; +use crate::document::value::TaggedValue; +use crate::document::*; +use crate::proto::{ConstructionArgs, ProtoNetwork}; +use core_types::{ProtoNodeIdentifier, concrete}; +use std::sync::atomic::AtomicU64; + +/// Generates IDs from a counter all tests share, so the IDs a test gets depend on what else runs in parallel. +fn gen_node_id() -> NodeId { + static NODE_ID: AtomicU64 = AtomicU64::new(4); + NodeId(NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)) +} + +#[test] +fn flatten_add() { + let mut network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0)], + nodes: [( + NodeId(1), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::Integer(2), false)], + implementation: DocumentNodeImplementation::Network(add_network()), + ..Default::default() + }, + )] + .into_iter() + .collect(), + ..Default::default() + }; + network.populate_dependants(); + + // A counter of its own, since the expected network names the nodes by the IDs it generates + let next_id = AtomicU64::new(4); + let gen_id = || NodeId(next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst)); + network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_id); + + let expected = flatten_add_expected(); + println!("{expected:#?}"); + println!("{network:#?}"); + + assert_eq!(expected, network); +} + +fn flatten_add_expected() -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(11), 0)], + nodes: [ + ( + NodeId(10), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::node(NodeId(14), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), + original_location: OriginalLocation { + dependants: vec![vec![NodeId(11)]], + ..Default::default() + }, + ..Default::default() + }, + ), + ( + NodeId(14), + DocumentNode { + inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), + original_location: OriginalLocation { + path: Some(vec![NodeId(4)]), + dependants: vec![vec![NodeId(10)]], + ..Default::default() + }, + ..Default::default() + }, + ), + ( + NodeId(11), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(10), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), + original_location: OriginalLocation { + dependants: vec![vec![]], + ..Default::default() + }, + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} + +fn two_node_passthrough() -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)], + nodes: [ + ( + NodeId(1), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 0)], + implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), + ..Default::default() + }, + ), + ( + NodeId(2), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 1)], + implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} + +fn output_duplicate(network_outputs: Vec, result_node_input: NodeInput) -> NodeNetwork { + let mut network = NodeNetwork { + exports: network_outputs, + nodes: [ + ( + NodeId(1), + DocumentNode { + inputs: vec![NodeInput::value(TaggedValue::Number(1.), false), NodeInput::value(TaggedValue::Number(2.), false)], + implementation: DocumentNodeImplementation::Network(two_node_passthrough()), + ..Default::default() + }, + ), + ( + NodeId(2), + DocumentNode { + inputs: vec![result_node_input], + implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + }; + let _new_ids = 101..; + network.populate_dependants(); + network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10000)); + network.validate_dependants(); + network.flatten_with_fns(NodeId(2), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10001)); + network.validate_dependants(); + network.remove_dead_nodes(0); + network.validate_dependants(); + network +} + +#[test] +fn simple_duplicate() { + let result = output_duplicate(vec![NodeInput::node(NodeId(1), 0)], NodeInput::node(NodeId(1), 0)); + println!("{result:#?}"); + result.validate_dependants(); + assert_eq!(result.exports.len(), 1, "The number of outputs should remain as 1"); + assert_eq!(result.exports[0], NodeInput::node(NodeId(11), 0), "The outer network output should be from a duplicated inner network"); + let mut ids = result.nodes.keys().copied().collect::>(); + ids.sort(); + assert_eq!(ids, vec![NodeId(11), NodeId(10010)], "Should only contain passthrough and values"); +} + +fn passthrough_network() -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(10), 0)], + nodes: [ + ( + NodeId(1), + DocumentNode { + implementation: DocumentNodeImplementation::Network(NodeNetwork { + exports: vec![NodeInput::node(NodeId(5), 0); 3], + ..Default::default() + }), + ..Default::default() + }, + ), + ( + NodeId(10), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(1), 2)], + implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), + ..Default::default() + }, + ), + ( + NodeId(11), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(10), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("add")), + ..Default::default() + }, + ), + ( + NodeId(12), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(10), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("double")), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} + +#[test] +fn remove_passthrough_node() { + let mut network = passthrough_network(); + network.generate_node_paths(&[]); + network.populate_dependants(); + network.remove_all_passthrough_nodes(); + + assert_eq!(network.nodes.len(), 3); + + let mut generator_dependants = network.nodes.get(&NodeId(1)).unwrap().original_location.dependants[2].clone(); + generator_dependants.sort(); + generator_dependants.dedup(); + assert_eq!(generator_dependants, vec![NodeId(11), NodeId(12)]); + + let add_inputs = &network.nodes.get(&NodeId(11)).unwrap().inputs; + assert_eq!(add_inputs, &vec![NodeInput::node(NodeId(1), 2); 2]); + + let double_inputs = &network.nodes.get(&NodeId(12)).unwrap().inputs; + assert_eq!(double_inputs, &vec![NodeInput::node(NodeId(1), 2); 1]); + + assert_eq!(&network.exports, &vec![NodeInput::node(NodeId(1), 2), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(1), 2)]); + + network.validate_dependants(); +} + +/// A hidden node with nothing wired into it (a layer chain's first node, or a generator) feeding a node with several inputs. +fn hidden_source_network(source_inputs: Vec) -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(2), 0)], + nodes: [ + ( + NodeId(1), + DocumentNode { + inputs: source_inputs, + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Source")), + visible: false, + ..Default::default() + }, + ), + ( + NodeId(2), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(2.), false)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Consumer")), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} + +// Flattens and strips passthroughs as the compiler does, then resolves the proto nodes, where an unwired input would panic +fn compile_hidden_source(mut network: NodeNetwork) -> ProtoNetwork { + network.generate_node_paths(&[]); + network.populate_dependants(); + let ids: Vec<_> = network.nodes.keys().copied().collect(); + ids.into_iter() + .for_each(|id| network.flatten_with_fns(id, |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_node_id)); + network.remove_all_passthrough_nodes(); + network.into_proto_networks().next().expect("The network should give a proto network") +} + +#[test] +fn hidden_node_with_an_unwired_input_passes_its_value() { + let proto_network = compile_hidden_source(hidden_source_network(vec![NodeInput::value(TaggedValue::Number(1.), true)])); + + // The consumer's first input is now a value node holding the hidden node's unwired value + let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); + let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { + panic!("The consumer should take node inputs") + }; + let value_node = proto_network + .nodes + .iter() + .find(|(id, _)| *id == inputs[0]) + .map(|(_, node)| node) + .expect("The consumer's first input should be a node"); + assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::Number(1.))); +} + +#[test] +fn hidden_node_without_inputs_passes_the_unit_value() { + let proto_network = compile_hidden_source(hidden_source_network(vec![])); + + let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); + let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { + panic!("The consumer should take node inputs") + }; + let value_node = proto_network + .nodes + .iter() + .find(|(id, _)| *id == inputs[0]) + .map(|(_, node)| node) + .expect("The consumer's first input should be a node"); + assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::None)); +} diff --git a/node-graph/graph-craft/src/compiler/lowering.rs b/node-graph/graph-craft/src/compiler/lowering.rs new file mode 100644 index 00000000000..a451d451e63 --- /dev/null +++ b/node-graph/graph-craft/src/compiler/lowering.rs @@ -0,0 +1,107 @@ +use crate::document::*; +use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; + +impl DocumentNode { + pub(crate) fn resolve_proto_node(self) -> ProtoNode { + let DocumentNodeImplementation::ProtoNode(identifier) = self.implementation else { + unreachable!("tried to resolve not flattened node on resolved node {self:?}"); + }; + assert!(!self.inputs.iter().any(|input| matches!(input, NodeInput::Import { .. })), "received non-resolved input"); + + let mut construction_args = ConstructionArgs::Nodes(vec![]); + + // If we have one input of the type value, set it as the construction args + if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() { + construction_args = ConstructionArgs::Value(tagged_value.clone()); + } + if let ConstructionArgs::Nodes(nodes) = &mut construction_args { + nodes.extend(self.inputs.iter().map(|input| match input { + NodeInput::Node { node_id, .. } => *node_id, + _ => unreachable!(), + })); + } + + ProtoNode { + identifier, + call_argument: self.call_argument, + construction_args, + original_location: self.original_location, + compile_metadata: self.compile_metadata.unwrap_or_default(), + upstream_context_features: Default::default(), + } + } +} + +impl NodeNetwork { + /// Creates a proto network for evaluating each output of this network. + pub fn into_proto_networks(self) -> impl Iterator { + #[cfg(test)] + self.validate_dependants(); + + let nodes: Vec<_> = self.nodes.into_iter().map(|(id, node)| (id, node.resolve_proto_node())).collect(); + + // Create a network to evaluate each output + if self.exports.len() == 1 + && let NodeInput::Node { node_id, .. } = self.exports[0] + { + return vec![ProtoNetwork { + inputs: Vec::new(), + output: node_id, + nodes, + }] + .into_iter(); + } + + // Create a network to evaluate each output + let networks: Vec<_> = self + .exports + .into_iter() + .filter_map(move |output| { + if let NodeInput::Node { node_id, .. } = output { + Some(ProtoNetwork { + inputs: Vec::new(), // Inputs field is not used. Should be deleted + // inputs: vec![input_node.expect("Set node should always exist")], + // inputs: self.imports.clone(), + output: node_id, + nodes: nodes.clone(), + }) + } else { + None + } + }) + .collect(); + networks.into_iter() + } + + /// Ensure the cached list of dependants exactly matches the real list of dependants + #[cfg(test)] + pub(crate) fn validate_dependants(&self) { + use std::collections::{HashMap, HashSet}; + + let mut dependants = HashMap::>>::new(); + + for (&id, node) in self.nodes.iter() { + dependants.insert(id, vec![HashSet::new(); node.implementation.output_count()]); + } + + for (&id, node) in self.nodes.iter() { + for input in &node.inputs { + if let NodeInput::Node { node_id, output_index } = *input { + dependants.get_mut(&node_id).unwrap()[output_index].insert(id); + } + } + } + + for (&id, node) in self.nodes.iter() { + for output_index in 0..node.implementation.output_count() { + let real_dependants = &dependants.get(&id).unwrap()[output_index]; + let listed_dependants = node.original_location.dependants.get(output_index).map_or_default(|d| d.iter().copied().collect::>()); + assert_eq!( + real_dependants, &listed_dependants, + "real {:?} should equal listed {:?} for output index {} in id {:?} in network:\n{:#?}", + real_dependants, listed_dependants, output_index, id, self + ); + } + } + } +} diff --git a/node-graph/graph-craft/src/compiler/lowering_tests.rs b/node-graph/graph-craft/src/compiler/lowering_tests.rs new file mode 100644 index 00000000000..75b1a8292d0 --- /dev/null +++ b/node-graph/graph-craft/src/compiler/lowering_tests.rs @@ -0,0 +1,134 @@ +use crate::document::value::TaggedValue; +use crate::document::*; +use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; +use core_types::{Context, ProtoNodeIdentifier, concrete}; + +#[test] +fn resolve_proto_node_add() { + let document_node = DocumentNode { + inputs: vec![NodeInput::node(NodeId(0), 0)], + call_argument: concrete!(i64), + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), + ..Default::default() + }; + + let proto_node = document_node.resolve_proto_node(); + let reference = ProtoNode { + identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"), + call_argument: concrete!(i64), + construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]), + ..Default::default() + }; + assert_eq!(proto_node, reference); +} + +#[test] +fn resolve_flatten_add_as_proto_network() { + let construction_network = ProtoNetwork { + inputs: Vec::new(), + output: NodeId(11), + nodes: [ + ( + NodeId(10), + ProtoNode { + identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"), + call_argument: concrete!(i64), + construction_args: ConstructionArgs::Nodes(vec![NodeId(14)]), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(0)]), + dependants: vec![vec![NodeId(11)]], + ..Default::default() + }, + + ..Default::default() + }, + ), + ( + NodeId(11), + ProtoNode { + identifier: ProtoNodeIdentifier::new("core_types::ops::AddPairNode"), + call_argument: concrete!(Context), + construction_args: ConstructionArgs::Nodes(vec![NodeId(10)]), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(1)]), + dependants: vec![vec![]], + ..Default::default() + }, + ..Default::default() + }, + ), + ( + NodeId(14), + ProtoNode { + identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"), + call_argument: concrete!(core_types::Context), + construction_args: ConstructionArgs::Value(TaggedValue::Integer(2).into()), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(4)]), + dependants: vec![vec![NodeId(10)]], + ..Default::default() + }, + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + }; + let mut network = flat_network(); + network.populate_dependants(); + let mut resolved_network = network.into_proto_networks().collect::>(); + resolved_network[0].nodes.sort_unstable_by_key(|(id, _)| *id); + + println!("{:#?}", resolved_network[0]); + println!("{construction_network:#?}"); + pretty_assertions::assert_eq!(resolved_network[0], construction_network); +} + +fn flat_network() -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(11), 0)], + nodes: [ + ( + NodeId(10), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(14), 0)], + call_argument: concrete!(i64), + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(0)]), + ..Default::default() + }, + ..Default::default() + }, + ), + ( + NodeId(14), + DocumentNode { + inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(4)]), + ..Default::default() + }, + ..Default::default() + }, + ), + ( + NodeId(11), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(10), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), + original_location: OriginalLocation { + path: Some(vec![NodeId(1), NodeId(1)]), + ..Default::default() + }, + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} diff --git a/node-graph/graph-craft/src/compiler/mod.rs b/node-graph/graph-craft/src/compiler/mod.rs new file mode 100644 index 00000000000..57b996f0ab3 --- /dev/null +++ b/node-graph/graph-craft/src/compiler/mod.rs @@ -0,0 +1,10 @@ +mod flatten; +mod lowering; +mod scope; + +#[cfg(test)] +mod flatten_tests; +#[cfg(test)] +mod lowering_tests; +#[cfg(test)] +mod scope_tests; diff --git a/node-graph/graph-craft/src/compiler/scope.rs b/node-graph/graph-craft/src/compiler/scope.rs new file mode 100644 index 00000000000..8233459b087 --- /dev/null +++ b/node-graph/graph-craft/src/compiler/scope.rs @@ -0,0 +1,261 @@ +use crate::document::value::TaggedValue; +use crate::document::*; +use core_types::{Cow, Type}; +use rustc_hash::{FxHashMap, FxHashSet}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +/// Every table entry, each listed after the entries its nodes name. O(entries + nodes). +fn definitions_children_first(definitions: &FxHashMap) -> Vec { + fn visit_network(network: &NodeNetwork, definitions: &FxHashMap, visited: &mut FxHashSet, order: &mut Vec) { + for node in network.nodes.values() { + match &node.implementation { + DocumentNodeImplementation::Definition(id) => visit_definition(*id, definitions, visited, order), + DocumentNodeImplementation::Network(nested) => visit_network(nested, definitions, visited, order), + _ => {} + } + } + } + fn visit_definition(id: NetworkId, definitions: &FxHashMap, visited: &mut FxHashSet, order: &mut Vec) { + if !visited.insert(id) { + return; + } + if let Some(definition) = definitions.get(&id) { + visit_network(definition, definitions, visited, order); + } + order.push(id); + } + + let mut ids: Vec = definitions.keys().copied().collect(); + ids.sort(); + + let mut visited = FxHashSet::default(); + let mut order = Vec::with_capacity(ids.len()); + for id in ids { + visit_definition(id, definitions, &mut visited, &mut order); + } + order +} + +impl NodeNetwork { + /// Resolves each scope input to the node injecting it, adding imports to carry it into nested networks. + /// + /// Each table entry is resolved once per scope context, children first: the keys an entry does not inject become its imports, + /// and every node naming the entry gets a matching scope input that its own network then resolves, so the nearest injection wins. + /// An entry reached from contexts that give a key different types is specialized into one entry per context. + pub fn resolve_scope_inputs(&mut self) { + let mut free_keys = FxHashMap::default(); + for id in definitions_children_first(&self.definitions) { + let Some(definition) = self.definitions.get(&id) else { continue }; + let keys = definition.free_scope_keys(&free_keys); + free_keys.insert(id, keys); + } + + let originals = std::mem::take(&mut self.definitions); + let mut specializer = ScopeSpecializer { + originals: &originals, + free_keys: &free_keys, + base_signatures: FxHashMap::default(), + contexts: FxHashMap::default(), + specialized: FxHashMap::default(), + }; + let root_chain = self.scope_injections.clone(); + specializer.specialize(self, &root_chain); + let ScopeSpecializer { + contexts, + specialized: mut definitions, + .. + } = specializer; + + let mut import_counts = FxHashMap::default(); + for network in std::iter::once(&*self).chain(definitions.values()) { + network.collect_instance_input_counts(&mut import_counts); + } + + let mut forwarded: FxHashMap> = FxHashMap::default(); + for id in definitions_children_first(&definitions) { + let (Some(definition), Some(context)) = (definitions.get_mut(&id), contexts.get(&id)) else { + continue; + }; + definition.append_forwarded_scopes(&forwarded); + + // Stands in for an instance's inputs, so the forwarded keys become imports after the existing ones + let import_count = import_counts.get(&id).copied().unwrap_or_default(); + let mut instance_inputs = vec![NodeInput::value(TaggedValue::None, false); import_count]; + let outside = ScopeChain { scopes: context, parent: None }; + definition.resolve_scope_inputs_impl(Some(&outside), &mut instance_inputs); + forwarded.insert(id, instance_inputs.split_off(import_count)); + } + + self.append_forwarded_scopes(&forwarded); + self.definitions = definitions; + + let mut leftover = Vec::new(); + self.resolve_scope_inputs_impl(None, &mut leftover); + assert!(leftover.is_empty(), "Unresolved scope keys at top level: {leftover:?}"); + } + + /// The scope keys this network reads, directly or through the networks it contains, without injecting them itself. + fn free_scope_keys(&self, entry_keys: &FxHashMap>) -> FxHashSet { + let mut keys = FxHashSet::default(); + for node in self.nodes.values() { + keys.extend(node.inputs.iter().filter_map(|input| match input { + NodeInput::Scope(key) => Some(key.to_string()), + _ => None, + })); + match &node.implementation { + DocumentNodeImplementation::Definition(id) => keys.extend(entry_keys.get(id).into_iter().flatten().cloned()), + DocumentNodeImplementation::Network(nested) => keys.extend(nested.free_scope_keys(entry_keys)), + _ => {} + } + } + + keys.retain(|key| !self.scope_injections.contains_key(key)); + keys + } + + fn collect_instance_input_counts(&self, counts: &mut FxHashMap) { + for node in self.nodes.values() { + match &node.implementation { + DocumentNodeImplementation::Definition(id) => { + counts.entry(*id).or_insert(node.inputs.len()); + } + DocumentNodeImplementation::Network(nested) => nested.collect_instance_input_counts(counts), + _ => {} + } + } + } + + fn append_forwarded_scopes(&mut self, forwarded: &FxHashMap>) { + for node in self.nodes.values_mut() { + match &mut node.implementation { + DocumentNodeImplementation::Definition(id) => node.inputs.extend(forwarded.get(id).into_iter().flatten().cloned()), + DocumentNodeImplementation::Network(nested) => nested.append_forwarded_scopes(forwarded), + _ => {} + } + } + } + + fn resolve_scope_inputs_impl(&mut self, parent: Option<&ScopeChain<'_>>, network_inputs: &mut Vec) { + let scope_chain = ScopeChain { + scopes: &self.scope_injections, + parent, + }; + + for node in self.nodes.values_mut() { + let DocumentNodeImplementation::Network(network) = &mut node.implementation else { continue }; + network.resolve_scope_inputs_impl(Some(&scope_chain), &mut node.inputs); + } + + let mut key_to_idx: FxHashMap, usize> = FxHashMap::default(); + for node in self.nodes.values_mut() { + for input in node.inputs.iter_mut() { + let NodeInput::Scope(key) = input else { continue }; + *input = match scope_chain.lookup(key) { + ScopeChainLookup::Current(node_id, _ty) => NodeInput::node(*node_id, 0), + ScopeChainLookup::Parent(_node_id, ty) => { + let import_index = *key_to_idx.entry(key.clone()).or_insert_with(|| { + let index = network_inputs.len(); + network_inputs.push(NodeInput::Scope(key.clone())); + index + }); + NodeInput::Import { + import_type: ty.clone(), + import_index, + } + } + ScopeChainLookup::None => panic!("Scope key `{key}` not found in any ancestor scope_injections"), + }; + } + } + } +} + +type ScopeInjections = FxHashMap; + +/// Gives every instance the entry matching the scope types its context provides, copying an entry for each further context. +struct ScopeSpecializer<'a> { + originals: &'a FxHashMap, + free_keys: &'a FxHashMap>, + /// The signature of the first context reaching each original entry, which keeps the entry's ID. + base_signatures: FxHashMap>, + /// The injections each specialized entry resolves its free keys against. + contexts: FxHashMap, + specialized: FxHashMap, +} + +impl ScopeSpecializer<'_> { + /// Points every instance in `network` at its specialization, where `chain` holds the nearest injection of every key visible in `network`. + fn specialize(&mut self, network: &mut NodeNetwork, chain: &ScopeInjections) { + let mut node_ids: Vec = network.nodes.keys().copied().collect(); + node_ids.sort(); + + for node_id in node_ids { + let Some(node) = network.nodes.get_mut(&node_id) else { continue }; + match &mut node.implementation { + DocumentNodeImplementation::Definition(id) => *id = self.specialization(*id, chain), + DocumentNodeImplementation::Network(nested) => { + let mut nested_chain = chain.clone(); + nested_chain.extend(nested.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone()))); + self.specialize(nested, &nested_chain); + } + _ => {} + } + } + } + + fn specialization(&mut self, id: NetworkId, chain: &ScopeInjections) -> NetworkId { + let Some(original) = self.originals.get(&id) else { return id }; + + let context: ScopeInjections = self.free_keys.get(&id).into_iter().flatten().filter_map(|key| Some((key.clone(), chain.get(key)?.clone()))).collect(); + let mut signature: Vec<(String, Type)> = context.iter().map(|(key, (_, ty))| (key.clone(), ty.clone())).collect(); + signature.sort_by(|(a, _), (b, _)| a.cmp(b)); + + let base_signature = self.base_signatures.entry(id).or_insert_with(|| signature.clone()); + let specialized_id = if *base_signature == signature { id } else { specialized_network_id(id, &signature) }; + if self.contexts.contains_key(&specialized_id) { + return specialized_id; + } + + let mut body = original.clone(); + let mut inner_chain = context.clone(); + inner_chain.extend(body.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone()))); + self.contexts.insert(specialized_id, context); + + self.specialize(&mut body, &inner_chain); + self.specialized.insert(specialized_id, body); + specialized_id + } +} + +fn specialized_network_id(id: NetworkId, signature: &[(String, Type)]) -> NetworkId { + let mut hasher = DefaultHasher::new(); + "scope specialization".hash(&mut hasher); + id.hash(&mut hasher); + signature.hash(&mut hasher); + NetworkId(hasher.finish()) +} + +struct ScopeChain<'a> { + scopes: &'a ScopeInjections, + parent: Option<&'a ScopeChain<'a>>, +} +enum ScopeChainLookup<'a> { + Current(&'a NodeId, &'a Type), + Parent(&'a NodeId, &'a Type), + None, +} +impl ScopeChain<'_> { + fn lookup(&'_ self, key: &str) -> ScopeChainLookup<'_> { + self.scopes + .get(key) + .map(|(id, ty)| ScopeChainLookup::Current(id, ty)) + .or_else(|| { + self.parent.and_then(|parent| match parent.lookup(key) { + ScopeChainLookup::Current(id, ty) | ScopeChainLookup::Parent(id, ty) => Some(ScopeChainLookup::Parent(id, ty)), + ScopeChainLookup::None => None, + }) + }) + .unwrap_or(ScopeChainLookup::None) + } +} diff --git a/node-graph/graph-craft/src/compiler/scope_tests.rs b/node-graph/graph-craft/src/compiler/scope_tests.rs new file mode 100644 index 00000000000..a348def6aa5 --- /dev/null +++ b/node-graph/graph-craft/src/compiler/scope_tests.rs @@ -0,0 +1,128 @@ +use crate::document::document_tests::{ADD, add_network}; +use crate::document::value::TaggedValue; +use crate::document::*; +use core_types::{ProtoNodeIdentifier, Type, concrete}; + +/// Two instances of `ADD`, one of them through another entry, with a scope input inside the entry it names. +fn shared_instances_with_a_scope_input() -> NodeNetwork { + let outer = NetworkId(2); + let mut add = add_network(); + add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected")); + let node = |implementation, inputs| DocumentNode { + implementation, + inputs, + ..Default::default() + }; + let value = |number| NodeInput::value(TaggedValue::Integer(number), false); + + let outer_network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::import(concrete!(i64), 0), value(2)]))] + .into_iter() + .collect(), + ..Default::default() + }; + let injected = node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")), vec![value(7)]); + + NodeNetwork { + exports: vec![NodeInput::node(NodeId(11), 0)], + nodes: [ + (NodeId(10), node(DocumentNodeImplementation::Definition(outer), vec![value(1)])), + (NodeId(11), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::node(NodeId(10), 0), value(3)])), + (NodeId(20), injected), + ] + .into_iter() + .collect(), + scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(), + definitions: [(ADD, add), (outer, outer_network)].into_iter().collect(), + ..Default::default() + } +} + +/// A root instance of `ADD` and one inside `group`, which shadows the root's `injected` with a node of type `shadowing_type`. +fn shadowed_scope_input(shadowing_type: Type) -> NodeNetwork { + let group = NetworkId(2); + let mut add = add_network(); + add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected")); + let node = |implementation| DocumentNode { implementation, ..Default::default() }; + let identity = || node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode"))); + + let group_network = NodeNetwork { + nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD))), (NodeId(21), identity())].into_iter().collect(), + scope_injections: [("injected".to_string(), (NodeId(21), shadowing_type))].into_iter().collect(), + ..Default::default() + }; + NodeNetwork { + nodes: [ + (NodeId(10), node(DocumentNodeImplementation::Definition(group))), + (NodeId(11), node(DocumentNodeImplementation::Definition(ADD))), + (NodeId(20), identity()), + ] + .into_iter() + .collect(), + scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(), + definitions: [(ADD, add), (group, group_network)].into_iter().collect(), + ..Default::default() + } +} + +fn scope_import_types(network: &NodeNetwork) -> Vec { + let mut types: Vec = network + .definitions + .values() + .filter_map(|definition| match definition.nodes.get(&NodeId(1))?.inputs.last()? { + NodeInput::Import { import_type, .. } => Some(import_type.clone()), + _ => None, + }) + .collect(); + types.sort_by_key(|ty| format!("{ty:?}")); + types +} + +#[test] +fn the_nearest_injection_resolves_a_scope_input() { + let mut network = shadowed_scope_input(concrete!(i64)); + network.resolve_scope_inputs(); + + assert_eq!(scope_import_types(&network), vec![concrete!(i64)], "a shadowing injection of the same type shares the entry"); + assert_eq!(network.nodes[&NodeId(11)].inputs.last(), Some(&NodeInput::node(NodeId(20), 0))); + assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0))); +} + +#[test] +fn a_shadowing_injection_of_another_type_specializes_the_entry() { + let mut network = shadowed_scope_input(concrete!(f64)); + network.resolve_scope_inputs(); + + assert_eq!(scope_import_types(&network), vec![concrete!(i64), concrete!(f64)]); + let DocumentNodeImplementation::Definition(root_instance) = network.nodes[&NodeId(11)].implementation else { + panic!() + }; + let DocumentNodeImplementation::Definition(group_instance) = network.definitions[&NetworkId(2)].nodes[&NodeId(10)].implementation else { + panic!() + }; + assert_ne!(root_instance, group_instance); + assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0))); +} + +#[test] +fn a_table_compiles_like_its_inlined_network() { + let table = shared_instances_with_a_scope_input(); + let mut inlined = table.clone(); + inlined.inline_definitions().unwrap(); + + // Flattening gives value nodes random IDs, which their paths carry, so only the other paths are compared + let compile = |network| { + let mut compiled = crate::graphene_compiler::Compiler {}.compile_single(network).expect("the network compiles").network; + let mut paths: Vec<_> = compiled + .nodes + .iter() + .filter(|(_, node)| node.identifier != ProtoNodeIdentifier::new("core_types::value::ClonedNode")) + .map(|(_, node)| node.original_location.path.clone()) + .collect(); + paths.sort(); + compiled.nodes.iter_mut().for_each(|(_, node)| node.original_location = OriginalLocation::default()); + (compiled, paths) + }; + assert_eq!(compile(table), compile(inlined)); +} diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index c189b585e26..4f40b8281fc 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -1,7 +1,9 @@ +mod migration; pub mod value; +pub use migration::{NodeExportVersions, NodeOutput, OldDocumentNode, OldDocumentNodeImplementation, OldDocumentNodeMetadata, OldNodeNetwork, OldPreviewing, OldRootNode}; + use crate::document::value::TaggedValue; -use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; use core_types::memo::MemoHashGuard; pub use core_types::uuid::NodeId; pub use core_types::uuid::generate_uuid; @@ -11,17 +13,7 @@ use glam::IVec2; use log::Metadata; use rustc_hash::{FxHashMap, FxHashSet}; use std::collections::HashMap; -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; - -/// Hash two IDs together, returning a new ID that is always consistent for two input IDs in a specific order. -/// This is used during [`NodeNetwork::flatten`] in order to ensure consistent yet non-conflicting IDs for inner networks. -fn merge_ids(a: NodeId, b: NodeId) -> NodeId { - let mut hasher = DefaultHasher::new(); - a.hash(&mut hasher); - b.hash(&mut hasher); - NodeId(hasher.finish()) -} +use std::hash::Hash; /// Utility function for providing a default boolean value to serde. #[inline(always)] @@ -45,18 +37,13 @@ pub struct DocumentNode { #[cfg_attr(target_family = "wasm", serde(alias = "outputs"))] pub inputs: Vec, /// Type of the argument which this node can be evaluated with. - #[serde(default, alias = "manual_composition", deserialize_with = "migrate_call_argument")] + #[serde(default, alias = "manual_composition", deserialize_with = "migration::migrate_call_argument")] pub call_argument: Type, // A nested document network or a proto-node identifier. pub implementation: DocumentNodeImplementation, /// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step. #[serde(default = "return_true")] pub visible: bool, - /// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed. - /// See [`ProtoNetwork::generate_stable_node_ids`] for details. - /// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph. - #[serde(default)] - pub skip_deduplication: bool, #[serde(skip)] pub compile_metadata: Option, /// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called. @@ -90,7 +77,6 @@ impl Default for DocumentNode { call_argument: concrete!(Context), implementation: Default::default(), visible: true, - skip_deduplication: Default::default(), original_location: OriginalLocation::default(), compile_metadata: Default::default(), } @@ -124,48 +110,6 @@ impl DocumentNode { network.normalize_stored_types(); } } - - /// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`]. - pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize) { - let (index, _) = self - .inputs - .iter() - .enumerate() - .nth(offset) - .unwrap_or_else(|| panic!("no network input found for {self:#?} and offset: {offset}")); - - self.inputs[index] = NodeInput::Node { node_id, output_index }; - } - - fn resolve_proto_node(self) -> ProtoNode { - let DocumentNodeImplementation::ProtoNode(identifier) = self.implementation else { - unreachable!("tried to resolve not flattened node on resolved node {self:?}"); - }; - assert!(!self.inputs.iter().any(|input| matches!(input, NodeInput::Import { .. })), "received non-resolved input"); - - let mut construction_args = ConstructionArgs::Nodes(vec![]); - - // If we have one input of the type value, set it as the construction args - if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() { - construction_args = ConstructionArgs::Value(tagged_value.clone()); - } - if let ConstructionArgs::Nodes(nodes) = &mut construction_args { - nodes.extend(self.inputs.iter().map(|input| match input { - NodeInput::Node { node_id, .. } => *node_id, - _ => unreachable!(), - })); - } - - ProtoNode { - identifier, - call_argument: self.call_argument, - construction_args, - original_location: self.original_location, - skip_deduplication: self.skip_deduplication, - compile_metadata: self.compile_metadata.unwrap_or_default(), - upstream_context_features: Default::default(), - } - } } /// Represents the possible inputs to a node. @@ -274,16 +218,6 @@ impl NodeInput { } } -// TODO: Eventually remove this document upgrade code -#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] -/// Represents the implementation of a node, which can be a nested [`NodeNetwork`], a proto [`ProtoNodeIdentifier`], or `Extract`. -pub enum OldDocumentNodeImplementation { - Network(OldNodeNetwork), - #[serde(alias = "Unresolved")] - ProtoNode(ProtoNodeIdentifier), - Extract, -} - #[repr(transparent)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, core_types::CacheHash, PartialOrd, Ord, DynAny, serde::Serialize, serde::Deserialize)] pub struct NetworkId(pub u64); @@ -295,7 +229,7 @@ impl NetworkId { } #[derive(Clone, Debug, PartialEq, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)] -/// Represents the implementation of a node, which can be a nested [`NodeNetwork`], a proto [`ProtoNodeIdentifier`], or `Extract`. +/// Represents the implementation of a node, which can be a nested [`NodeNetwork`], a reference to a definitions table entry, or a proto [`ProtoNodeIdentifier`]. pub enum DocumentNodeImplementation { /// This describes a (document) node built out of a subgraph of other (document) nodes. /// @@ -307,24 +241,6 @@ pub enum DocumentNodeImplementation { /// A proto node identifier which can be found in `node_registry.rs`. #[serde(alias = "Unresolved")] // TODO: Eventually remove this alias document upgrade code ProtoNode(ProtoNodeIdentifier), - /// The Extract variant is a tag which tells the compilation process to do something special: it invokes language-level functionality built for use by the ExtractNode to enable metaprogramming. - /// When the ExtractNode is compiled, it gets replaced by a value node containing a representation of the source code for the function/lambda of the document node that's fed into the ExtractNode - /// (but only that one document node, not upstream nodes). - /// - /// This is explained in more detail here: - /// - /// Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph. - /// We would use an assortment of nodes that operate on Graphene source code (just data, no different from any other data flowing through the graph) to make graph transformations. - /// - /// We use this for dealing with macros in a syntactic way of modifying the node graph from within the graph itself. Just like we often deal with lambdas to represent a whole group of - /// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, rather than its executable logic. - /// - /// This is analogous to how Rust macros operate at the level of source code, not executable code. When we speak of source code, that represents Graphene's source code in the form of a - /// DocumentNode network, not the text form of Rust's source code. (Analogous to the token stream/AST of a Rust macro.) - /// - /// `DocumentNode`s with a `DocumentNodeImplementation::Extract` are converted into a `ClonedNode` that returns the `DocumentNode` specified by the single `NodeInput::Node`. The referenced node - /// (specified by the single `NodeInput::Node`) is removed from the network, and any `NodeInput::Node`s used by the referenced node are replaced with a generically typed network input. - Extract, } impl Default for DocumentNodeImplementation { @@ -367,170 +283,13 @@ impl DocumentNodeImplementation { } } -// TODO: Eventually remove this document upgrade code -#[derive(Debug, serde::Deserialize)] -#[serde(untagged)] -pub enum NodeExportVersions { - OldNodeInput(NodeOutput), - NodeInput(NodeInput), -} - -// TODO: Eventually remove this document upgrade code -#[derive(Debug, serde::Deserialize)] -pub struct NodeOutput { - pub node_id: NodeId, - pub node_output_index: usize, -} - -// TODO: Eventually remove this document upgrade code -fn deserialize_exports<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - use serde::Deserialize; - let node_input_versions = Vec::::deserialize(deserializer)?; - - // Convert Vec to Vec - let inputs = node_input_versions - .into_iter() - .map(|node_input_version| { - let node_output = match node_input_version { - NodeExportVersions::OldNodeInput(node_output) => node_output, - NodeExportVersions::NodeInput(node_input) => return node_input, - }; - NodeInput::node(node_output.node_id, node_output.node_output_index) - }) - .collect(); - - Ok(inputs) -} - -/// An instance of a [`DocumentNodeDefinition`] that has been instantiated in a [`NodeNetwork`]. -/// Currently, when an instance is made, it lives all on its own without any lasting connection to the definition. -/// But we will want to change it in the future so it merely references its definition. -#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] -pub struct OldDocumentNode { - /// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the node definition's name is displayed to the user in italics. - /// Ensure the click target in the encapsulating network is updated when this is modified by using network.update_click_target(node_id). - #[serde(default)] - pub alias: String, - // TODO: Replace this name with a reference to the [`DocumentNodeDefinition`] node definition to use the name from there instead. - /// The name of the node definition, as originally set by [`DocumentNodeDefinition`], used to display in the UI and to display the appropriate Inspector layout. - #[serde(deserialize_with = "migrate_layer_to_merge")] - pub name: String, - /// The inputs to a node, which are either: - /// - From other nodes within this graph [`NodeInput::Node`], - /// - A constant value [`NodeInput::Value`], - /// - A [`NodeInput::Import`] which specifies that this input is from outside the graph, which is resolved in the graph flattening step in the case of nested networks. - /// - /// In the root network, it is resolved when evaluating the borrow tree. - /// Ensure the click target in the encapsulating network is updated when the inputs cause the node shape to change (currently only when exposing/hiding an input) by using network.update_click_target(node_id). - #[cfg_attr(target_family = "wasm", serde(alias = "outputs"))] - pub inputs: Vec, - pub manual_composition: Option, - // TODO: Remove once this references its definition instead (see above TODO). - /// Indicates to the UI if a primary output should be drawn for this node. - /// True for most nodes, but the Split Channels node is an example of a node that has multiple secondary outputs but no primary output. - #[serde(default = "return_true")] - pub has_primary_output: bool, - // A nested document network or a proto-node identifier. - pub implementation: OldDocumentNodeImplementation, - /// User chosen state for displaying this as a left-to-right node or bottom-to-top layer. Ensure the click target in the encapsulating network is updated when the node changes to a layer by using network.update_click_target(node_id). - #[serde(default)] - pub is_layer: bool, - /// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step. - #[serde(default = "return_true")] - pub visible: bool, - /// Represents the lock icon for locking/unlocking the node in the graph UI. When locked, a node cannot be moved in the graph UI. - #[serde(default)] - pub locked: bool, - /// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id). - pub metadata: OldDocumentNodeMetadata, - /// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed. - /// See [`ProtoNetwork::generate_stable_node_ids`] for details. - /// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph. - #[serde(default)] - pub skip_deduplication: bool, - /// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called. - #[serde(skip)] - pub original_location: OriginalLocation, -} - -// TODO: Eventually remove this document upgrade code -#[derive(Clone, Debug, PartialEq, Default, Hash, DynAny, serde::Serialize, serde::Deserialize)] -/// Metadata about the node including its position in the graph UI -pub struct OldDocumentNodeMetadata { - pub position: IVec2, -} - -// TODO: Eventually remove this document upgrade code -#[derive(Clone, Copy, Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)] -/// Root Node is the "default" export for a node network. Used by document metadata, displaying UI-only "Export" node, and for restoring the default preview node. -pub struct OldRootNode { - pub id: NodeId, - pub output_index: usize, -} - -// TODO: Eventually remove this document upgrade code -#[derive(PartialEq, Debug, Clone, Hash, Default, serde::Serialize, serde::Deserialize)] -pub enum OldPreviewing { - /// If there is a node to restore the connection to the export for, then it is stored in the option. - /// Otherwise, nothing gets restored and the primary export is disconnected. - Yes { root_node_to_restore: Option }, - #[default] - No, -} - -// TODO: Eventually remove this document upgrade code -#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] -/// A network (subgraph) of nodes containing each [`DocumentNode`] and its ID, as well as list mapping each export to its connected node, or a value if disconnected -pub struct OldNodeNetwork { - /// The list of data outputs that are exported from this network to the parent network. - /// Each export is a reference to a node within this network, paired with its output index, that is the source of the network's exported data. - #[serde(alias = "outputs", deserialize_with = "deserialize_exports")] // TODO: Eventually remove this alias document upgrade code - pub exports: Vec, - /// The list of all nodes in this network. - //cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))] - pub nodes: HashMap, - /// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends. - #[serde(default)] - pub previewing: OldPreviewing, - /// Temporary fields to store metadata for "Import"/"Export" UI-only nodes, eventually will be replaced with lines leading to edges - #[serde(default = "default_import_metadata")] - pub imports_metadata: (NodeId, IVec2), - #[serde(default = "default_export_metadata")] - pub exports_metadata: (NodeId, IVec2), - - /// A network may expose nodes as constants which can by used by other nodes using a `NodeInput::Scope(key)`. - #[serde(default)] - //cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))] - pub scope_injections: HashMap, -} - -// TODO: Eventually remove this document upgrade code -fn migrate_layer_to_merge<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { - let mut s: String = serde::Deserialize::deserialize(deserializer)?; - if s == "Layer" { - s = "Merge".to_string(); - } - Ok(s) -} -// TODO: Eventually remove this document upgrade code -fn default_import_metadata() -> (NodeId, IVec2) { - (NodeId::new(), IVec2::new(-25, -4)) -} -// TODO: Eventually remove this document upgrade code -fn default_export_metadata() -> (NodeId, IVec2) { - (NodeId::new(), IVec2::new(8, -4)) -} - #[derive(Clone, Default, Debug, DynAny, serde::Serialize, serde::Deserialize)] /// A network (subgraph) of nodes containing each [`DocumentNode`] and its ID, as well as list mapping each export to its connected node, or a value if disconnected pub struct NodeNetwork { /// The list of data outputs that are exported from this network to the parent network. /// Each export is a reference to a node within this network, paired with its output index, that is the source of the network's exported data. // TODO: Eventually remove this alias document upgrade code - #[cfg_attr(target_family = "wasm", serde(alias = "outputs", deserialize_with = "deserialize_exports"))] + #[cfg_attr(target_family = "wasm", serde(alias = "outputs", deserialize_with = "migration::deserialize_exports"))] pub exports: Vec, // TODO: Instead of storing import types in each NodeInput::Import connection, the types are stored here. This is similar to how types need to be defined for parameters when creating a function in Rust. // pub import_types: Vec, @@ -553,65 +312,14 @@ pub struct NodeNetwork { pub generated: bool, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct NetworkLocation<'a> { - pub definition: Option, - pub inline_path: &'a [NodeId], -} - -impl NetworkLocation<'_> { - pub const ROOT: NetworkLocation<'static> = NetworkLocation { definition: None, inline_path: &[] }; - - pub fn to_owned_location(self) -> OwnedNetworkLocation { - OwnedNetworkLocation { - definition: self.definition, - inline_path: self.inline_path.to_vec(), - } - } - - pub fn child(self, node_id: NodeId) -> OwnedNetworkLocation { - let mut location = self.to_owned_location(); - location.inline_path.push(node_id); - location - } - - /// The location of the network that the node `node_id` in this network implements with `implementation`. - pub fn implemented_by(self, node_id: NodeId, implementation: &DocumentNodeImplementation) -> OwnedNetworkLocation { - match implementation { - DocumentNodeImplementation::Definition(id) => OwnedNetworkLocation::definition(*id), - _ => self.child(node_id), - } - } +/// Where a network of the document lives: a definitions table entry, or `None` for the document network itself. +pub type NetworkLocation = Option; - pub fn is_root(self) -> bool { - self == Self::ROOT - } -} - -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct OwnedNetworkLocation { - pub definition: Option, - pub inline_path: Vec, -} - -impl OwnedNetworkLocation { - pub const ROOT: OwnedNetworkLocation = OwnedNetworkLocation { - definition: None, - inline_path: Vec::new(), - }; - - pub fn definition(id: NetworkId) -> Self { - Self { - definition: Some(id), - inline_path: Vec::new(), - } - } - - pub fn as_location(&self) -> NetworkLocation<'_> { - NetworkLocation { - definition: self.definition, - inline_path: &self.inline_path, - } +/// The output count of `implementation`, or `None` for a table entry that `definitions` lacks. +pub(crate) fn output_count_in(implementation: &DocumentNodeImplementation, definitions: &FxHashMap) -> Option { + match implementation { + DocumentNodeImplementation::Definition(id) => definitions.get(id).map(|definition| definition.exports.len()), + _ => Some(implementation.output_count()), } } @@ -643,6 +351,43 @@ impl std::fmt::Display for DefinitionError { impl std::error::Error for DefinitionError {} +fn validate_named_definitions( + network: &NodeNetwork, + definitions: &FxHashMap, + visiting: &mut Vec, + validated: &mut FxHashSet, +) -> Result<(), DefinitionError> { + for node in network.nodes.values() { + match &node.implementation { + DocumentNodeImplementation::Definition(id) => { + if let Some(start) = visiting.iter().position(|visiting| visiting == id) { + return Err(DefinitionError::Cycle(visiting[start..].to_vec())); + } + if validated.contains(id) { + continue; + } + + let definition = definitions.get(id).ok_or(DefinitionError::Missing(*id))?; + if !definition.definitions.is_empty() { + return Err(DefinitionError::NestedTable); + } + visiting.push(*id); + validate_named_definitions(definition, definitions, visiting, validated)?; + visiting.pop(); + validated.insert(*id); + } + DocumentNodeImplementation::Network(nested) => { + if !nested.definitions.is_empty() { + return Err(DefinitionError::NestedTable); + } + validate_named_definitions(nested, definitions, visiting, validated)?; + } + _ => {} + } + } + Ok(()) +} + struct DefinitionInliner { definitions: FxHashMap, inlined: FxHashMap, @@ -752,49 +497,27 @@ impl NodeNetwork { self.located_network_mut(location) } - pub fn locate<'a>(&self, nested_path: &'a [NodeId]) -> Option> { - let mut location = NetworkLocation { - definition: None, - inline_path: nested_path, - }; - let mut network = self; - - for (index, segment) in nested_path.iter().enumerate() { - let implementation = &network.nodes.get(segment)?.implementation; - if let DocumentNodeImplementation::Definition(id) = implementation { - location = NetworkLocation { - definition: Some(*id), - inline_path: &nested_path[index + 1..], - }; - } - network = self.implementation_network(implementation)?; + /// The location of the network at `nested_path`, or `None` if the path doesn't end at a table entry. + pub fn locate(&self, nested_path: &[NodeId]) -> Option { + let Some((node_id, parent_path)) = nested_path.split_last() else { return Some(None) }; + match self.nested_network(parent_path)?.nodes.get(node_id)?.implementation { + DocumentNodeImplementation::Definition(id) if self.definitions.contains_key(&id) => Some(Some(id)), + _ => None, } - - Some(location) } pub fn located_network(&self, location: NetworkLocation) -> Option<&Self> { - let mut network = match location.definition { - Some(id) => self.definitions.get(&id)?, - None => self, - }; - - for segment in location.inline_path { - network = network.nodes.get(segment)?.implementation.get_network()?; + match location { + Some(id) => self.definitions.get(&id), + None => Some(self), } - Some(network) } pub fn located_network_mut(&mut self, location: NetworkLocation) -> Option<&mut Self> { - let mut network = match location.definition { - Some(id) => self.definitions.get_mut(&id)?, - None => self, - }; - - for segment in location.inline_path { - network = network.nodes.get_mut(segment)?.implementation.get_network_mut()?; + match location { + Some(id) => self.definitions.get_mut(&id), + None => Some(self), } - Some(network) } pub fn implementation_network<'a>(&'a self, implementation: &'a DocumentNodeImplementation) -> Option<&'a Self> { @@ -806,10 +529,7 @@ impl NodeNetwork { } pub fn implementation_output_count(&self, implementation: &DocumentNodeImplementation) -> usize { - match implementation { - DocumentNodeImplementation::Definition(_) => self.implementation_network(implementation).map_or(0, |network| network.exports.len()), - _ => implementation.output_count(), - } + output_count_in(implementation, &self.definitions).unwrap_or(0) } /// The path of the node producing this output once compiled, following network exports and the primary inputs of hidden and Passthrough nodes. @@ -917,6 +637,11 @@ impl NodeNetwork { dropped } + /// Checks that every table entry a node names exists, that no entries name each other in a cycle, and that only this network holds a table. + pub fn validate_definitions(&self) -> Result<(), DefinitionError> { + validate_named_definitions(self, &self.definitions, &mut Vec::new(), &mut FxHashSet::default()) + } + pub fn inline_definitions(&mut self) -> Result<(), DefinitionError> { let mut inliner = DefinitionInliner { definitions: std::mem::take(&mut self.definitions), @@ -973,73 +698,6 @@ impl NodeNetwork { } } -// Functions for resolving scope inputs -impl NodeNetwork { - pub fn resolve_scope_inputs(&mut self) { - let mut leftover = Vec::new(); - self.resolve_scope_inputs_impl(None, &mut leftover); - assert!(leftover.is_empty(), "Unresolved scope keys at top level: {leftover:?}"); - } - - fn resolve_scope_inputs_impl(&mut self, parent: Option<&ScopeChain<'_>>, network_inputs: &mut Vec) { - let scope_chain = ScopeChain { - scopes: &self.scope_injections, - parent, - }; - - for node in self.nodes.values_mut() { - let DocumentNodeImplementation::Network(network) = &mut node.implementation else { continue }; - network.resolve_scope_inputs_impl(Some(&scope_chain), &mut node.inputs); - } - - let mut key_to_idx: FxHashMap, usize> = FxHashMap::default(); - for node in self.nodes.values_mut() { - for input in node.inputs.iter_mut() { - let NodeInput::Scope(key) = input else { continue }; - *input = match scope_chain.lookup(key) { - ScopeChainLookup::Current(node_id, _ty) => NodeInput::node(*node_id, 0), - ScopeChainLookup::Parent(_node_id, ty) => { - let import_index = *key_to_idx.entry(key.clone()).or_insert_with(|| { - let index = network_inputs.len(); - network_inputs.push(NodeInput::Scope(key.clone())); - index - }); - NodeInput::Import { - import_type: ty.clone(), - import_index, - } - } - ScopeChainLookup::None => panic!("Scope key `{key}` not found in any ancestor scope_injections"), - }; - } - } - } -} - -struct ScopeChain<'a> { - scopes: &'a FxHashMap, - parent: Option<&'a ScopeChain<'a>>, -} -enum ScopeChainLookup<'a> { - Current(&'a NodeId, &'a Type), - Parent(&'a NodeId, &'a Type), - None, -} -impl ScopeChain<'_> { - fn lookup(&'_ self, key: &str) -> ScopeChainLookup<'_> { - self.scopes - .get(key) - .map(|(id, ty)| ScopeChainLookup::Current(id, ty)) - .or_else(|| { - self.parent.and_then(|parent| match parent.lookup(key) { - ScopeChainLookup::Current(id, ty) | ScopeChainLookup::Parent(id, ty) => Some(ScopeChainLookup::Parent(id, ty)), - ScopeChainLookup::None => None, - }) - }) - .unwrap_or(ScopeChainLookup::None) - } -} - /// Functions for compiling the network /// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload. fn normalize_input_stored_type(input: &mut NodeInput) { @@ -1090,473 +748,6 @@ impl NodeNetwork { .collect(); } - /// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes. - pub fn generate_node_paths(&mut self, prefix: &[NodeId]) { - for (node_id, node) in &mut self.nodes { - let mut new_path = prefix.to_vec(); - if !self.generated { - new_path.push(*node_id); - } - if let DocumentNodeImplementation::Network(network) = &mut node.implementation { - network.generate_node_paths(new_path.as_slice()); - } - if node.original_location.path.is_some() { - log::warn!("Attempting to overwrite node path"); - } else { - node.original_location.path = Some(new_path); - node.original_location.dependants = (0..node.implementation.output_count()).map(|_| Vec::new()).collect(); - } - } - } - - pub fn populate_dependants(&mut self) { - let mut dep_changes = Vec::new(); - for (node_id, node) in &mut self.nodes { - let len = node.original_location.dependants.len(); - node.original_location.dependants.extend(vec![vec![]; (node.implementation.output_count()).max(len) - len]); - for input in &node.inputs { - if let NodeInput::Node { node_id: dep_id, output_index, .. } = input { - dep_changes.push((*dep_id, *output_index, *node_id)); - } - } - } - // println!("{:#?}", self.nodes.get(&NodeId(1))); - for (dep_id, output_index, node_id) in dep_changes { - let node = self.nodes.get_mut(&dep_id).expect("Encountered invalid node id"); - let len = node.original_location.dependants.len(); - // One must be added to the index to find the length because indexing in rust starts from 0. - node.original_location.dependants.extend(vec![vec![]; (output_index + 1).max(len) - len]); - // println!("{node_id} {output_index} {}", node.implementation.output_count()); - node.original_location.dependants[output_index].push(node_id); - } - } - - /// Replace all references in any node of `old_input` with `new_input` - fn replace_node_inputs(&mut self, node_id: NodeId, old_input: (NodeId, usize), new_input: (NodeId, usize)) { - let Some(node) = self.nodes.get_mut(&node_id) else { return }; - node.inputs.iter_mut().for_each(|input| { - if let NodeInput::Node { node_id: input_id, output_index, .. } = input - && (*input_id, *output_index) == old_input - { - (*input_id, *output_index) = new_input; - } - }); - } - - /// Replace all references in any node of `old_output` with `new_output` - fn replace_network_outputs(&mut self, old_output: &NodeInput, new_output: &NodeInput) { - for output in self.exports.iter_mut() { - if *output == *old_output { - *output = new_output.clone(); - } - } - } - - /// Removes unused nodes from the graph. Returns a list of booleans which represent if each of the inputs have been retained. - pub fn remove_dead_nodes(&mut self, number_of_inputs: usize) -> Vec { - // Take all the nodes out of the nodes list - let mut old_nodes = std::mem::take(&mut self.nodes); - - let mut stack = self - .exports - .iter() - .filter_map(|output| if let NodeInput::Node { node_id, .. } = output { Some(*node_id) } else { None }) - .collect::>(); - while let Some(node_id) = stack.pop() { - let Some((node_id, mut document_node)) = old_nodes.remove_entry(&node_id) else { - continue; - }; - // Remove dead nodes from child networks - if let DocumentNodeImplementation::Network(network) = &mut document_node.implementation { - // Remove inputs to the parent node if they have been removed from the child - let mut retain_inputs = network.remove_dead_nodes(document_node.inputs.len()).into_iter(); - document_node.inputs.retain(|_| retain_inputs.next().unwrap_or(true)) - } - // Visit all nodes that this node references - stack.extend( - document_node - .inputs - .iter() - .filter_map(|input| if let NodeInput::Node { node_id, .. } = input { Some(node_id) } else { None }), - ); - // Add the node back to the list of nodes - self.nodes.insert(node_id, document_node); - } - - // Remove references to nodes that have been deleted - for node in self.nodes.values_mut() { - for dependants in &mut node.original_location.dependants { - dependants.retain(|dependant| !old_nodes.contains_key(dependant)); - } - } - - // Check if inputs are used and store for return value - let mut are_inputs_used = vec![false; number_of_inputs]; - for node in &self.nodes { - for node_input in &node.1.inputs { - if let NodeInput::Import { import_index, .. } = node_input - && let Some(is_used) = are_inputs_used.get_mut(*import_index) - { - *is_used = true; - } - } - } - are_inputs_used - } - - /// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network. - pub fn flatten(&mut self, node_id: NodeId) { - self.flatten_with_fns(node_id, merge_ids, NodeId::new) - } - - /// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network. - pub fn flatten_with_fns(&mut self, node_id: NodeId, map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, gen_id: impl Fn() -> NodeId + Copy) { - let Some((id, mut node)) = self.nodes.remove_entry(&node_id) else { - warn!("The node which was supposed to be flattened does not exist in the network, id {node_id} network {self:#?}"); - return; - }; - - // If the node is hidden, replace it with a passthrough node - let passthrough_node = DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER); - if !node.visible && node.implementation != passthrough_node { - node.implementation = passthrough_node; - - // A node without inputs has nothing to pass through, so it passes through the unit value instead - if node.inputs.is_empty() { - node.inputs.push(NodeInput::value(TaggedValue::None, false)); - } - - // Keep only the primary input, which the passthrough forwards - let removed_inputs = node.inputs.split_off(1); - - // Remove the dependants on the ignored inputs - for removed_input in removed_inputs { - if let NodeInput::Node { node_id, output_index } = removed_input - && let Some(former_dependency) = self.nodes.get_mut(&node_id) - // Ensure that the other node inputs do not also reference the dependency - && !node.inputs.iter().any(|input| matches!(input, NodeInput::Node { node_id: other, .. } if *other == node_id)) - { - former_dependency.original_location.dependants[output_index].retain(|&dependant| dependant != id); - } - } - - // Removing the passthrough later splices its input into its consumers, which accept only node wires, so an unwired input becomes a value node - let path = node.original_location.path.clone().unwrap_or_default(); - Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); - - node.call_argument = concrete!(()); - self.nodes.insert(id, node); - return; - } - - let path = node.original_location.path.clone().unwrap_or_default(); - - // Replace value inputs with dedicated value nodes - if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) { - Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); - } - - let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else { - // If the node is not a network, it is a primitive node and can be inserted into the network as is. - assert!(!self.nodes.contains_key(&id), "Trying to insert a node into the network caused an id conflict"); - - self.nodes.insert(id, node); - return; - }; - debug_assert!( - node.compile_metadata.is_none(), - "Network {id} should not have compile metadata: {compile_metadata:#?}", - compile_metadata = node.compile_metadata - ); - - // Replace value and reflection imports with value nodes, added inside nested network - Self::replace_value_inputs_with_nodes( - &mut inner_network.exports, - &mut inner_network.nodes, - node.original_location.path.as_ref().unwrap_or(&vec![]), - gen_id, - map_ids, - id, - ); - - // Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node. - inner_network.map_ids(|inner_id| map_ids(id, inner_id)); - inner_network.populate_dependants(); - let new_nodes = inner_network.nodes.keys().cloned().collect::>(); - - for (key, value) in inner_network.scope_injections.into_iter() { - match self.scope_injections.entry(key) { - std::collections::hash_map::Entry::Occupied(o) => { - log::warn!("Found duplicate scope injection for key {}, ignoring", o.key()); - } - std::collections::hash_map::Entry::Vacant(v) => { - v.insert(value); - } - } - } - - // Match the document node input and the inputs of the inner network - for (nested_node_id, mut nested_node) in inner_network.nodes.into_iter() { - for (nested_input_index, nested_input) in nested_node.clone().inputs.iter().enumerate() { - if let NodeInput::Import { import_index, .. } = nested_input { - let parent_input = node - .inputs - .get(*import_index) - .unwrap_or_else(|| panic!("Import index {import_index} of network node implementation {:?} should always exist", nested_node.implementation)); - match *parent_input { - // If the input to self is a node, connect the corresponding output of the inner network to it - NodeInput::Node { node_id, output_index } => { - nested_node.populate_first_network_input(node_id, output_index, nested_input_index); - let input_node = self.nodes.get_mut(&node_id).unwrap_or_else(|| panic!("Unable to find input node {node_id:?}")); - input_node.original_location.dependants[output_index].push(nested_node_id); - } - NodeInput::Import { import_index, .. } => { - let parent_input_index = import_index; - let Some(NodeInput::Import { import_index, .. }) = nested_node.inputs.get_mut(nested_input_index) else { - log::error!("Nested node should have a network input"); - continue; - }; - *import_index = parent_input_index; - } - NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"), - NodeInput::Scope(_) => unreachable!("Scope inputs should have been resolved by resolve_scope_inputs_recursive before flattening"), - NodeInput::Reflection(_) => unreachable!("Reflection inputs should have been replaced with value nodes"), - } - } - } - self.nodes.insert(nested_node_id, nested_node); - } - - // Remove the newly flattened node from the dependants - for parent_input in &node.inputs { - if let NodeInput::Node { node_id, output_index } = *parent_input - && let Some(input_node) = self.nodes.get_mut(&node_id) - { - input_node.original_location.dependants[output_index].retain(|&dependant| dependant != id); - } - } - - // TODO: Add support for flattening exports that are NodeInput::Import (https://github.com/GraphiteEditor/Graphite/issues/1762) - - self.replace_node_with_its_exports(id, &node.original_location, &inner_network.exports); - - for node_id in new_nodes { - self.flatten_with_fns(node_id, map_ids, gen_id); - } - } - - /// Connect all nodes that were previously connected to this node to the nodes of the inner network - fn replace_node_with_its_exports(&mut self, id: NodeId, original_location: &OriginalLocation, exports: &[NodeInput]) { - for (i, export) in exports.iter().enumerate() { - if let NodeInput::Node { node_id, output_index, .. } = &export { - for deps in &original_location.dependants { - for dep in deps { - self.replace_node_inputs(*dep, (id, i), (*node_id, *output_index)); - } - } - - if let Some(new_output_node) = self.nodes.get_mut(node_id) { - for dep in &original_location.dependants[i] { - new_output_node.original_location.dependants[*output_index].push(*dep); - } - - // Remove references from dependants on wrapper - new_output_node.original_location.dependants[*output_index].retain(|&dependant| dependant != id); - } - } - - self.replace_network_outputs(&NodeInput::node(id, i), export); - } - } - - #[inline(never)] - fn replace_value_inputs_with_nodes( - inputs: &mut [NodeInput], - collection: &mut FxHashMap, - path: &[NodeId], - gen_id: impl Fn() -> NodeId + Copy, - map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, - id: NodeId, - ) { - // Replace value exports and imports with value nodes, added inside the nested network - for export in inputs { - let previous_export = std::mem::replace(export, NodeInput::import(concrete!(()), 0)); - - let (tagged_value, exposed) = match previous_export { - NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed), - NodeInput::Reflection(reflect) => match reflect { - DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false), - DocumentNodeMetadata::SourceId => (TaggedValue::SourceId(core_types::SourceId::from_path(path)).into(), false), - }, - previous_export => { - *export = previous_export; - continue; - } - }; - let value_node_id = gen_id(); - let merged_node_id = map_ids(id, value_node_id); - let mut original_location = OriginalLocation { - path: Some(path.to_vec()), - dependants: vec![vec![id]], - ..Default::default() - }; - - if let Some(path) = &mut original_location.path { - path.push(value_node_id); - } - collection.insert( - merged_node_id, - DocumentNode { - inputs: vec![NodeInput::Value { tagged_value, exposed }], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), - original_location, - ..Default::default() - }, - ); - *export = NodeInput::Node { - node_id: merged_node_id, - output_index: 0, - }; - } - } - - fn remove_passthrough_node(&mut self, passthrough_id: NodeId) { - let node = self.nodes.remove(&passthrough_id).unwrap_or_else(|| panic!("Node with id {passthrough_id} does not exist")); - - let implementation = &node.implementation; - assert!( - matches!(implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER), - "remove_passthrough_node was given a node {implementation:?} and id {passthrough_id:?}", - ); - assert_eq!(node.inputs.len(), 1, "Passthrough node has more than one input"); - - // Consider the upstream node (the input to the passthrough) - if let NodeInput::Node { - node_id: upstream_node_id, - output_index: upstream_output_index, - .. - } = node.inputs[0] - && let Some(upstream_node) = self.nodes.get_mut(&upstream_node_id) - { - let dependants_of_upstream = &mut upstream_node.original_location.dependants[upstream_output_index]; - // Add our dependants to the list of dependants - dependants_of_upstream.extend(node.original_location.dependants[0].iter().copied()); - // Remove ourselves from the list of dependants - dependants_of_upstream.retain(|&dependant| dependant != passthrough_id); - }; - - // Check if the passthrough output is connected to a network export - for node_input in self.exports.iter_mut() { - if matches!(node_input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) { - *node_input = node.inputs[0].clone(); - } - } - - // Look at all downstream nodes - for &dependant_id in &node.original_location.dependants[0] { - let Some(dependant_node) = self.nodes.get_mut(&dependant_id) else { - error!("remove_passthrough_node got a dependant id {dependant_id:?} that did not exist in the network\n{self:#?}"); - continue; - }; - for input in dependant_node.inputs.iter_mut() { - if matches!(input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) { - *input = node.inputs[0].clone(); - } - } - } - } - - /// Strips out all [`graphene_core::ops::PassthroughNode`]s. - pub fn remove_all_passthrough_nodes(&mut self) { - let passthrough_nodes = self - .nodes - .iter() - .filter(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER)) - .map(|(id, _)| *id) - .collect::>(); - for id in passthrough_nodes { - self.remove_passthrough_node(id); - } - } - - /// Converts the `DocumentNode`s with a `DocumentNodeImplementation::Extract` into a `ClonedNode` that returns - /// the `DocumentNode` specified by the single `NodeInput::Node`. - /// The referenced node is removed from the network, and any `NodeInput::Node`s used by the referenced node are replaced with a generically typed network input. - pub fn resolve_extract_nodes(&mut self) { - let mut extraction_nodes = self - .nodes - .iter() - .filter(|(_, node)| matches!(node.implementation, DocumentNodeImplementation::Extract)) - .map(|(id, node)| (*id, node.clone())) - .collect::>(); - self.nodes.retain(|_, node| !matches!(node.implementation, DocumentNodeImplementation::Extract)); - - for (_, node) in &mut extraction_nodes { - assert_eq!(node.inputs.len(), 1); - let NodeInput::Node { node_id, output_index, .. } = node.inputs.pop().unwrap() else { - panic!("Extract node has no input, inputs: {:?}", node.inputs); - }; - assert_eq!(output_index, 0); - // TODO: check if we can read lambda checking? - let mut input_node = self.nodes.remove(&node_id).unwrap(); - node.implementation = DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")); - if let Some(input) = input_node.inputs.get_mut(0) { - *input = match &input { - NodeInput::Node { .. } => NodeInput::import(generic!(T), 0), - ni => NodeInput::import(ni.ty(), 0), - }; - } - - for input in input_node.inputs.iter_mut() { - if let NodeInput::Node { .. } = input { - *input = NodeInput::import(generic!(T), 0) - } - } - node.inputs = vec![NodeInput::value(TaggedValue::DocumentNode(input_node), false)]; - } - self.nodes.extend(extraction_nodes); - } - - /// Creates a proto network for evaluating each output of this network. - pub fn into_proto_networks(self) -> impl Iterator { - #[cfg(test)] - self.validate_dependants(); - - let nodes: Vec<_> = self.nodes.into_iter().map(|(id, node)| (id, node.resolve_proto_node())).collect(); - - // Create a network to evaluate each output - if self.exports.len() == 1 - && let NodeInput::Node { node_id, .. } = self.exports[0] - { - return vec![ProtoNetwork { - inputs: Vec::new(), - output: node_id, - nodes, - }] - .into_iter(); - } - - // Create a network to evaluate each output - let networks: Vec<_> = self - .exports - .into_iter() - .filter_map(move |output| { - if let NodeInput::Node { node_id, .. } = output { - Some(ProtoNetwork { - inputs: Vec::new(), // Inputs field is not used. Should be deleted - // inputs: vec![input_node.expect("Set node should always exist")], - // inputs: self.imports.clone(), - output: node_id, - nodes: nodes.clone(), - }) - } else { - None - } - }) - .collect(); - networks.into_iter() - } - /// Create a [`RecursiveNodeIter`] that iterates over all [`DocumentNode`]s, including ones that are deeply nested. pub fn recursive_nodes(&self) -> RecursiveNodeIter<'_> { let nodes = self.nodes.iter().map(|(id, node)| (id, node, Vec::new())).collect(); @@ -1566,38 +757,6 @@ impl NodeNetwork { nodes, } } - - /// Ensure the cached list of dependants exactly matches the real list of dependants - #[cfg(test)] - fn validate_dependants(&self) { - use std::collections::HashSet; - - let mut dependants = HashMap::>>::new(); - - for (&id, node) in self.nodes.iter() { - dependants.insert(id, vec![HashSet::new(); node.implementation.output_count()]); - } - - for (&id, node) in self.nodes.iter() { - for input in &node.inputs { - if let NodeInput::Node { node_id, output_index } = *input { - dependants.get_mut(&node_id).unwrap()[output_index].insert(id); - } - } - } - - for (&id, node) in self.nodes.iter() { - for output_index in 0..node.implementation.output_count() { - let real_dependants = &dependants.get(&id).unwrap()[output_index]; - let listed_dependants = node.original_location.dependants.get(output_index).map_or_default(|d| d.iter().copied().collect::>()); - assert_eq!( - real_dependants, &listed_dependants, - "real {:?} should equal listed {:?} for output index {} in id {:?} in network:\n{:#?}", - real_dependants, listed_dependants, output_index, id, self - ); - } - } - } } /// An iterator over all [`DocumentNode`]s, including ones that are deeply nested. @@ -1628,753 +787,15 @@ impl<'a> Iterator for RecursiveNodeIter<'a> { } } -fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { - use serde::Deserialize; - - #[derive(serde::Serialize, serde::Deserialize)] - #[serde(untagged)] - enum CallArg { - New(Type), - Old(Option), - } - - Ok(match CallArg::deserialize(deserializer)? { - CallArg::New(ty) => ty, - CallArg::Old(ty) => ty.unwrap_or_default(), - }) -} - impl core_types::graphene_hash::CacheHash for DocumentNode { fn cache_hash(&self, state: &mut H) { self.inputs.cache_hash(state); self.call_argument.cache_hash(state); self.implementation.cache_hash(state); self.visible.cache_hash(state); - self.skip_deduplication.cache_hash(state); self.compile_metadata.cache_hash(state); } } #[cfg(test)] -mod test { - use super::*; - use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; - use std::sync::atomic::AtomicU64; - - /// Generates IDs from a counter all tests share, so the IDs a test gets depend on what else runs in parallel. - fn gen_node_id() -> NodeId { - static NODE_ID: AtomicU64 = AtomicU64::new(4); - NodeId(NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)) - } - - fn add_network() -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(1), 0)], - nodes: [ - ( - NodeId(0), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), - ..Default::default() - }, - ), - ( - NodeId(1), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(0), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - #[test] - fn map_ids() { - let mut network = add_network(); - network.map_ids(|id| NodeId(id.0 + 1)); - let mapped_add = NodeNetwork { - exports: vec![NodeInput::node(NodeId(2), 0)], - nodes: [ - ( - NodeId(1), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), - ..Default::default() - }, - ), - ( - NodeId(2), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(1), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - }; - assert_eq!(network, mapped_add); - } - - #[test] - fn output_source_follows_exports_imports_and_hidden_nodes() { - let proto_node = |inputs: Vec| DocumentNode { - inputs, - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), - ..Default::default() - }; - let network_node = |input: NodeInput, network: NodeNetwork| DocumentNode { - inputs: vec![input], - implementation: DocumentNodeImplementation::Network(network), - ..Default::default() - }; - - // Network 2 passes its import through to its export, network 3 exports its inner node 0, and node 4 is hidden - let passing_network = NodeNetwork { - exports: vec![NodeInput::import(concrete!(i64), 0)], - ..Default::default() - }; - let wrapping_network = NodeNetwork { - exports: vec![NodeInput::node(NodeId(0), 0)], - nodes: [(NodeId(0), proto_node(vec![NodeInput::import(concrete!(i64), 0)]))].into_iter().collect(), - ..Default::default() - }; - let network = NodeNetwork { - exports: vec![NodeInput::node(NodeId(4), 0)], - nodes: [ - (NodeId(1), proto_node(vec![NodeInput::value(TaggedValue::Integer(1), false)])), - (NodeId(2), network_node(NodeInput::node(NodeId(1), 0), passing_network)), - (NodeId(3), network_node(NodeInput::node(NodeId(2), 0), wrapping_network)), - ( - NodeId(4), - DocumentNode { - visible: false, - ..proto_node(vec![NodeInput::node(NodeId(3), 0)]) - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - }; - - assert_eq!(network.output_source(&[NodeId(1)], 0), Some(vec![NodeId(1)])); - assert_eq!( - network.output_source(&[NodeId(2)], 0), - Some(vec![NodeId(1)]), - "A network passing its import through gives what's wired to it" - ); - assert_eq!(network.output_source(&[NodeId(3)], 0), Some(vec![NodeId(3), NodeId(0)]), "A network gives what its export is wired to"); - assert_eq!(network.output_source(&[NodeId(4)], 0), Some(vec![NodeId(3), NodeId(0)]), "A hidden node gives its primary input"); - assert_eq!(network.input_source(&[NodeId(3)], &NodeInput::import(concrete!(i64), 0)), Some(vec![NodeId(1)])); - assert_eq!(network.output_source(&[NodeId(5)], 0), None); - } - - #[test] - fn extract_node() { - let passthrough_node = DocumentNode { - inputs: vec![], - implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), - ..Default::default() - }; - // TODO: Extend test cases to test nested network - let mut extraction_network = NodeNetwork { - exports: vec![NodeInput::node(NodeId(1), 0)], - nodes: [ - passthrough_node.clone(), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(0), 0)], - implementation: DocumentNodeImplementation::Extract, - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }; - extraction_network.resolve_extract_nodes(); - assert_eq!(extraction_network.nodes.len(), 1); - let inputs = extraction_network.nodes.get(&NodeId(1)).unwrap().inputs.clone(); - assert_eq!(inputs.len(), 1); - assert!(matches!(&inputs[0].as_value(), &Some(TaggedValue::DocumentNode(network), ..) if network == &passthrough_node)); - } - - #[test] - fn flatten_add() { - let mut network = NodeNetwork { - exports: vec![NodeInput::node(NodeId(1), 0)], - nodes: [( - NodeId(1), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::Integer(2), false)], - implementation: DocumentNodeImplementation::Network(add_network()), - ..Default::default() - }, - )] - .into_iter() - .collect(), - ..Default::default() - }; - network.populate_dependants(); - - // A counter of its own, since the expected network names the nodes by the IDs it generates - let next_id = AtomicU64::new(4); - let gen_id = || NodeId(next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst)); - network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_id); - - let expected = flatten_add_expected(); - println!("{expected:#?}"); - println!("{network:#?}"); - - assert_eq!(expected, network); - } - - #[test] - fn resolve_proto_node_add() { - let document_node = DocumentNode { - inputs: vec![NodeInput::node(NodeId(0), 0)], - call_argument: concrete!(i64), - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), - ..Default::default() - }; - - let proto_node = document_node.resolve_proto_node(); - let reference = ProtoNode { - identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"), - call_argument: concrete!(i64), - construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]), - ..Default::default() - }; - assert_eq!(proto_node, reference); - } - - #[test] - fn resolve_flatten_add_as_proto_network() { - let construction_network = ProtoNetwork { - inputs: Vec::new(), - output: NodeId(11), - nodes: [ - ( - NodeId(10), - ProtoNode { - identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"), - call_argument: concrete!(i64), - construction_args: ConstructionArgs::Nodes(vec![NodeId(14)]), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(0)]), - dependants: vec![vec![NodeId(11)]], - ..Default::default() - }, - - ..Default::default() - }, - ), - ( - NodeId(11), - ProtoNode { - identifier: ProtoNodeIdentifier::new("core_types::ops::AddPairNode"), - call_argument: concrete!(Context), - construction_args: ConstructionArgs::Nodes(vec![NodeId(10)]), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(1)]), - dependants: vec![vec![]], - ..Default::default() - }, - ..Default::default() - }, - ), - ( - NodeId(14), - ProtoNode { - identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"), - call_argument: concrete!(core_types::Context), - construction_args: ConstructionArgs::Value(TaggedValue::Integer(2).into()), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(4)]), - dependants: vec![vec![NodeId(10)]], - ..Default::default() - }, - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - }; - let mut network = flat_network(); - network.populate_dependants(); - let mut resolved_network = network.into_proto_networks().collect::>(); - resolved_network[0].nodes.sort_unstable_by_key(|(id, _)| *id); - - println!("{:#?}", resolved_network[0]); - println!("{construction_network:#?}"); - pretty_assertions::assert_eq!(resolved_network[0], construction_network); - } - - fn flatten_add_expected() -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(11), 0)], - nodes: [ - ( - NodeId(10), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::node(NodeId(14), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), - original_location: OriginalLocation { - dependants: vec![vec![NodeId(11)]], - ..Default::default() - }, - ..Default::default() - }, - ), - ( - NodeId(14), - DocumentNode { - inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), - original_location: OriginalLocation { - path: Some(vec![NodeId(4)]), - dependants: vec![vec![NodeId(10)]], - ..Default::default() - }, - ..Default::default() - }, - ), - ( - NodeId(11), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(10), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), - original_location: OriginalLocation { - dependants: vec![vec![]], - ..Default::default() - }, - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - fn flat_network() -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(11), 0)], - nodes: [ - ( - NodeId(10), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(14), 0)], - call_argument: concrete!(i64), - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(0)]), - ..Default::default() - }, - ..Default::default() - }, - ), - ( - NodeId(14), - DocumentNode { - inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(4)]), - ..Default::default() - }, - ..Default::default() - }, - ), - ( - NodeId(11), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(10), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), - original_location: OriginalLocation { - path: Some(vec![NodeId(1), NodeId(1)]), - ..Default::default() - }, - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - fn two_node_passthrough() -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)], - nodes: [ - ( - NodeId(1), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 0)], - implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), - ..Default::default() - }, - ), - ( - NodeId(2), - DocumentNode { - inputs: vec![NodeInput::import(concrete!(i64), 1)], - implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - fn output_duplicate(network_outputs: Vec, result_node_input: NodeInput) -> NodeNetwork { - let mut network = NodeNetwork { - exports: network_outputs, - nodes: [ - ( - NodeId(1), - DocumentNode { - inputs: vec![NodeInput::value(TaggedValue::Number(1.), false), NodeInput::value(TaggedValue::Number(2.), false)], - implementation: DocumentNodeImplementation::Network(two_node_passthrough()), - ..Default::default() - }, - ), - ( - NodeId(2), - DocumentNode { - inputs: vec![result_node_input], - implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - }; - let _new_ids = 101..; - network.populate_dependants(); - network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10000)); - network.validate_dependants(); - network.flatten_with_fns(NodeId(2), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10001)); - network.validate_dependants(); - network.remove_dead_nodes(0); - network.validate_dependants(); - network - } - - #[test] - fn simple_duplicate() { - let result = output_duplicate(vec![NodeInput::node(NodeId(1), 0)], NodeInput::node(NodeId(1), 0)); - println!("{result:#?}"); - result.validate_dependants(); - assert_eq!(result.exports.len(), 1, "The number of outputs should remain as 1"); - assert_eq!(result.exports[0], NodeInput::node(NodeId(11), 0), "The outer network output should be from a duplicated inner network"); - let mut ids = result.nodes.keys().copied().collect::>(); - ids.sort(); - assert_eq!(ids, vec![NodeId(11), NodeId(10010)], "Should only contain passthrough and values"); - } - - fn passthrough_network() -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(10), 0)], - nodes: [ - ( - NodeId(1), - DocumentNode { - implementation: DocumentNodeImplementation::Network(NodeNetwork { - exports: vec![NodeInput::node(NodeId(5), 0); 3], - ..Default::default() - }), - ..Default::default() - }, - ), - ( - NodeId(10), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(1), 2)], - implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER), - ..Default::default() - }, - ), - ( - NodeId(11), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(10), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("add")), - ..Default::default() - }, - ), - ( - NodeId(12), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(10), 0)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("double")), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - #[test] - fn remove_passthrough_node() { - let mut network = passthrough_network(); - network.generate_node_paths(&[]); - network.populate_dependants(); - network.remove_all_passthrough_nodes(); - - assert_eq!(network.nodes.len(), 3); - - let mut generator_dependants = network.nodes.get(&NodeId(1)).unwrap().original_location.dependants[2].clone(); - generator_dependants.sort(); - generator_dependants.dedup(); - assert_eq!(generator_dependants, vec![NodeId(11), NodeId(12)]); - - let add_inputs = &network.nodes.get(&NodeId(11)).unwrap().inputs; - assert_eq!(add_inputs, &vec![NodeInput::node(NodeId(1), 2); 2]); - - let double_inputs = &network.nodes.get(&NodeId(12)).unwrap().inputs; - assert_eq!(double_inputs, &vec![NodeInput::node(NodeId(1), 2); 1]); - - assert_eq!(&network.exports, &vec![NodeInput::node(NodeId(1), 2), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(1), 2)]); - - network.validate_dependants(); - } - - /// A hidden node with nothing wired into it (a layer chain's first node, or a generator) feeding a node with several inputs. - fn hidden_source_network(source_inputs: Vec) -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(2), 0)], - nodes: [ - ( - NodeId(1), - DocumentNode { - inputs: source_inputs, - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Source")), - visible: false, - ..Default::default() - }, - ), - ( - NodeId(2), - DocumentNode { - inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(2.), false)], - implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Consumer")), - ..Default::default() - }, - ), - ] - .into_iter() - .collect(), - ..Default::default() - } - } - - // Flattens and strips passthroughs as the compiler does, then resolves the proto nodes, where an unwired input would panic - fn compile_hidden_source(mut network: NodeNetwork) -> ProtoNetwork { - network.generate_node_paths(&[]); - network.populate_dependants(); - let ids: Vec<_> = network.nodes.keys().copied().collect(); - ids.into_iter() - .for_each(|id| network.flatten_with_fns(id, |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_node_id)); - network.remove_all_passthrough_nodes(); - network.into_proto_networks().next().expect("The network should give a proto network") - } - - #[test] - fn hidden_node_with_an_unwired_input_passes_its_value() { - let proto_network = compile_hidden_source(hidden_source_network(vec![NodeInput::value(TaggedValue::Number(1.), true)])); - - // The consumer's first input is now a value node holding the hidden node's unwired value - let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); - let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { - panic!("The consumer should take node inputs") - }; - let value_node = proto_network - .nodes - .iter() - .find(|(id, _)| *id == inputs[0]) - .map(|(_, node)| node) - .expect("The consumer's first input should be a node"); - assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::Number(1.))); - } - - #[test] - fn hidden_node_without_inputs_passes_the_unit_value() { - let proto_network = compile_hidden_source(hidden_source_network(vec![])); - - let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); - let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { - panic!("The consumer should take node inputs") - }; - let value_node = proto_network - .nodes - .iter() - .find(|(id, _)| *id == inputs[0]) - .map(|(_, node)| node) - .expect("The consumer's first input should be a node"); - assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::None)); - } - - fn node_with(implementation: DocumentNodeImplementation) -> DocumentNode { - DocumentNode { implementation, ..Default::default() } - } - - fn network_with(nodes: impl IntoIterator, definitions: impl IntoIterator) -> NodeNetwork { - NodeNetwork { - exports: vec![NodeInput::node(NodeId(10), 0)], - nodes: nodes.into_iter().map(|(id, implementation)| (id, node_with(implementation))).collect(), - definitions: definitions.into_iter().collect(), - ..Default::default() - } - } - - const ADD: NetworkId = NetworkId(1); - - fn two_add_instances() -> NodeNetwork { - network_with( - [(NodeId(10), DocumentNodeImplementation::Definition(ADD)), (NodeId(11), DocumentNodeImplementation::Definition(ADD))], - [(ADD, add_network())], - ) - } - - #[test] - fn definitions_inline_into_copies_of_their_network() { - let mut network = two_add_instances(); - network.inline_definitions().unwrap(); - - let inlined = network_with( - [ - (NodeId(10), DocumentNodeImplementation::Network(add_network())), - (NodeId(11), DocumentNodeImplementation::Network(add_network())), - ], - [], - ); - assert_eq!(network, inlined); - } - - #[test] - fn lifted_networks_inline_back_to_the_original() { - let nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []); - let original = network_with( - [ - (NodeId(10), DocumentNodeImplementation::Network(nested)), - (NodeId(11), DocumentNodeImplementation::Network(add_network())), - ], - [], - ); - - let mut network = original.clone(); - let lifted = network.lift_nested_networks(); - - assert_eq!(lifted.len(), 3); - assert_eq!(network.definitions.len(), 3); - let all_nodes = std::iter::once(&network).chain(network.definitions.values()).flat_map(|network| network.nodes.values()); - assert!(all_nodes.into_iter().all(|node| !matches!(node.implementation, DocumentNodeImplementation::Network(_)))); - - let outermost: Vec<_> = lifted.iter().filter(|lifted| lifted.containing.is_none()).map(|lifted| lifted.node_id).collect(); - assert_eq!(outermost.len(), 2); - assert!(lifted.iter().position(|entry| entry.containing.is_some()) > lifted.iter().position(|entry| entry.containing.is_none())); - - network.inline_definitions().unwrap(); - assert_eq!(network, original); - } - - #[test] - fn definitions_referencing_definitions_inline_transitively() { - let outer = NetworkId(2); - let mut network = network_with( - [(NodeId(10), DocumentNodeImplementation::Definition(outer))], - [(ADD, add_network()), (outer, network_with([(NodeId(10), DocumentNodeImplementation::Definition(ADD))], []))], - ); - network.inline_definitions().unwrap(); - - let inner = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []); - assert_eq!(network, network_with([(NodeId(10), DocumentNodeImplementation::Network(inner))], [])); - } - - #[test] - fn invalid_definition_tables_are_rejected() { - let (first, second) = (NetworkId(2), NetworkId(3)); - let mut cyclic = network_with( - [(NodeId(10), DocumentNodeImplementation::Definition(first))], - [ - (first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])), - (second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])), - ], - ); - assert_eq!(cyclic.inline_definitions(), Err(DefinitionError::Cycle(vec![first, second]))); - - let mut missing = network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], []); - assert_eq!(missing.inline_definitions(), Err(DefinitionError::Missing(first))); - - let mut nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(two_add_instances()))], []); - assert_eq!(nested.inline_definitions(), Err(DefinitionError::NestedTable)); - } - - #[test] - fn edits_through_one_instance_reach_every_instance() { - let mut network = two_add_instances(); - let added = node_with(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode"))); - network.nested_network_mut(&[NodeId(10)]).unwrap().nodes.insert(NodeId(2), added.clone()); - - assert_eq!(network.nested_network(&[NodeId(11)]).unwrap().nodes.get(&NodeId(2)), Some(&added)); - assert_eq!( - network.locate(&[NodeId(11)]), - Some(NetworkLocation { - definition: Some(ADD), - inline_path: &[] - }) - ); - assert_eq!(network.implementation_output_count(&DocumentNodeImplementation::Definition(ADD)), 1); - } - - #[test] - fn definition_edits_change_the_network_hash() { - let mut network = two_add_instances(); - let before = network.current_hash(); - - network.definitions.get_mut(&ADD).unwrap().exports.push(NodeInput::node(NodeId(0), 0)); - assert_ne!(network.current_hash(), before); - } - - #[test] - fn recursive_nodes_visit_each_definition_once() { - let network = two_add_instances(); - let body_paths = network.recursive_nodes().map(|(_, _, path)| path).filter(|path| !path.is_empty()).collect::>(); - assert_eq!(body_paths.len(), add_network().nodes.len()); - assert!(body_paths.windows(2).all(|pair| pair[0] == pair[1])); - - let (first, second) = (NetworkId(2), NetworkId(3)); - let cyclic = network_with( - [(NodeId(10), DocumentNodeImplementation::Definition(first))], - [ - (first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])), - (second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])), - ], - ); - assert_eq!(cyclic.recursive_nodes().count(), 3); - } -} +pub(crate) mod document_tests; diff --git a/node-graph/graph-craft/src/document/document_tests.rs b/node-graph/graph-craft/src/document/document_tests.rs new file mode 100644 index 00000000000..e5f1ae15255 --- /dev/null +++ b/node-graph/graph-craft/src/document/document_tests.rs @@ -0,0 +1,252 @@ +use super::*; + +pub(crate) fn add_network() -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0)], + nodes: [ + ( + NodeId(0), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), + ..Default::default() + }, + ), + ( + NodeId(1), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(0), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } +} + +#[test] +fn map_ids() { + let mut network = add_network(); + network.map_ids(|id| NodeId(id.0 + 1)); + let mapped_add = NodeNetwork { + exports: vec![NodeInput::node(NodeId(2), 0)], + nodes: [ + ( + NodeId(1), + DocumentNode { + inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")), + ..Default::default() + }, + ), + ( + NodeId(2), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(1), 0)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + }; + assert_eq!(network, mapped_add); +} + +#[test] +fn output_source_follows_exports_imports_and_hidden_nodes() { + let proto_node = |inputs: Vec| DocumentNode { + inputs, + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")), + ..Default::default() + }; + let network_node = |input: NodeInput, network: NodeNetwork| DocumentNode { + inputs: vec![input], + implementation: DocumentNodeImplementation::Network(network), + ..Default::default() + }; + + // Network 2 passes its import through to its export, network 3 exports its inner node 0, and node 4 is hidden + let passing_network = NodeNetwork { + exports: vec![NodeInput::import(concrete!(i64), 0)], + ..Default::default() + }; + let wrapping_network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(0), 0)], + nodes: [(NodeId(0), proto_node(vec![NodeInput::import(concrete!(i64), 0)]))].into_iter().collect(), + ..Default::default() + }; + let network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(4), 0)], + nodes: [ + (NodeId(1), proto_node(vec![NodeInput::value(TaggedValue::Integer(1), false)])), + (NodeId(2), network_node(NodeInput::node(NodeId(1), 0), passing_network)), + (NodeId(3), network_node(NodeInput::node(NodeId(2), 0), wrapping_network)), + ( + NodeId(4), + DocumentNode { + visible: false, + ..proto_node(vec![NodeInput::node(NodeId(3), 0)]) + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + }; + + assert_eq!(network.output_source(&[NodeId(1)], 0), Some(vec![NodeId(1)])); + assert_eq!( + network.output_source(&[NodeId(2)], 0), + Some(vec![NodeId(1)]), + "A network passing its import through gives what's wired to it" + ); + assert_eq!(network.output_source(&[NodeId(3)], 0), Some(vec![NodeId(3), NodeId(0)]), "A network gives what its export is wired to"); + assert_eq!(network.output_source(&[NodeId(4)], 0), Some(vec![NodeId(3), NodeId(0)]), "A hidden node gives its primary input"); + assert_eq!(network.input_source(&[NodeId(3)], &NodeInput::import(concrete!(i64), 0)), Some(vec![NodeId(1)])); + assert_eq!(network.output_source(&[NodeId(5)], 0), None); +} + +fn node_with(implementation: DocumentNodeImplementation) -> DocumentNode { + DocumentNode { implementation, ..Default::default() } +} + +fn network_with(nodes: impl IntoIterator, definitions: impl IntoIterator) -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: nodes.into_iter().map(|(id, implementation)| (id, node_with(implementation))).collect(), + definitions: definitions.into_iter().collect(), + ..Default::default() + } +} + +pub(crate) const ADD: NetworkId = NetworkId(1); + +fn two_add_instances() -> NodeNetwork { + network_with( + [(NodeId(10), DocumentNodeImplementation::Definition(ADD)), (NodeId(11), DocumentNodeImplementation::Definition(ADD))], + [(ADD, add_network())], + ) +} + +#[test] +fn definitions_inline_into_copies_of_their_network() { + let mut network = two_add_instances(); + network.inline_definitions().unwrap(); + + let inlined = network_with( + [ + (NodeId(10), DocumentNodeImplementation::Network(add_network())), + (NodeId(11), DocumentNodeImplementation::Network(add_network())), + ], + [], + ); + assert_eq!(network, inlined); +} + +#[test] +fn lifted_networks_inline_back_to_the_original() { + let nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []); + let original = network_with( + [ + (NodeId(10), DocumentNodeImplementation::Network(nested)), + (NodeId(11), DocumentNodeImplementation::Network(add_network())), + ], + [], + ); + + let mut network = original.clone(); + let lifted = network.lift_nested_networks(); + + assert_eq!(lifted.len(), 3); + assert_eq!(network.definitions.len(), 3); + let all_nodes = std::iter::once(&network).chain(network.definitions.values()).flat_map(|network| network.nodes.values()); + assert!(all_nodes.into_iter().all(|node| !matches!(node.implementation, DocumentNodeImplementation::Network(_)))); + + let outermost: Vec<_> = lifted.iter().filter(|lifted| lifted.containing.is_none()).map(|lifted| lifted.node_id).collect(); + assert_eq!(outermost.len(), 2); + assert!(lifted.iter().position(|entry| entry.containing.is_some()) > lifted.iter().position(|entry| entry.containing.is_none())); + + network.inline_definitions().unwrap(); + assert_eq!(network, original); +} + +#[test] +fn definitions_referencing_definitions_inline_transitively() { + let outer = NetworkId(2); + let mut network = network_with( + [(NodeId(10), DocumentNodeImplementation::Definition(outer))], + [(ADD, add_network()), (outer, network_with([(NodeId(10), DocumentNodeImplementation::Definition(ADD))], []))], + ); + network.inline_definitions().unwrap(); + + let inner = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []); + assert_eq!(network, network_with([(NodeId(10), DocumentNodeImplementation::Network(inner))], [])); +} + +#[test] +fn invalid_definition_tables_are_rejected() { + let (first, second) = (NetworkId(2), NetworkId(3)); + let mut cyclic = network_with( + [(NodeId(10), DocumentNodeImplementation::Definition(first))], + [ + (first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])), + (second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])), + ], + ); + assert_eq!(cyclic.validate_definitions(), Err(DefinitionError::Cycle(vec![first, second]))); + assert_eq!(cyclic.inline_definitions(), Err(DefinitionError::Cycle(vec![first, second]))); + + let mut missing = network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], []); + assert_eq!(missing.validate_definitions(), Err(DefinitionError::Missing(first))); + assert_eq!(missing.inline_definitions(), Err(DefinitionError::Missing(first))); + + let mut nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(two_add_instances()))], []); + assert_eq!(nested.validate_definitions(), Err(DefinitionError::NestedTable)); + assert_eq!(nested.inline_definitions(), Err(DefinitionError::NestedTable)); + + assert_eq!(two_add_instances().validate_definitions(), Ok(())); +} + +#[test] +fn edits_through_one_instance_reach_every_instance() { + let mut network = two_add_instances(); + let added = node_with(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode"))); + network.nested_network_mut(&[NodeId(10)]).unwrap().nodes.insert(NodeId(2), added.clone()); + + assert_eq!(network.nested_network(&[NodeId(11)]).unwrap().nodes.get(&NodeId(2)), Some(&added)); + assert_eq!(network.locate(&[NodeId(11)]), Some(Some(ADD))); + assert_eq!(network.implementation_output_count(&DocumentNodeImplementation::Definition(ADD)), 1); +} + +#[test] +fn definition_edits_change_the_network_hash() { + let mut network = two_add_instances(); + let before = network.current_hash(); + + network.definitions.get_mut(&ADD).unwrap().exports.push(NodeInput::node(NodeId(0), 0)); + assert_ne!(network.current_hash(), before); +} + +#[test] +fn recursive_nodes_visit_each_definition_once() { + let network = two_add_instances(); + let body_paths = network.recursive_nodes().map(|(_, _, path)| path).filter(|path| !path.is_empty()).collect::>(); + assert_eq!(body_paths.len(), add_network().nodes.len()); + assert!(body_paths.windows(2).all(|pair| pair[0] == pair[1])); + + let (first, second) = (NetworkId(2), NetworkId(3)); + let cyclic = network_with( + [(NodeId(10), DocumentNodeImplementation::Definition(first))], + [ + (first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])), + (second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])), + ], + ); + assert_eq!(cyclic.recursive_nodes().count(), 3); +} diff --git a/node-graph/graph-craft/src/document/migration.rs b/node-graph/graph-craft/src/document/migration.rs new file mode 100644 index 00000000000..5ed106feee3 --- /dev/null +++ b/node-graph/graph-craft/src/document/migration.rs @@ -0,0 +1,177 @@ +use super::*; + +// TODO: Eventually remove this document upgrade code +#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] +/// Represents the implementation of a node, which can be a nested [`NodeNetwork`] or a proto [`ProtoNodeIdentifier`]. +pub enum OldDocumentNodeImplementation { + Network(OldNodeNetwork), + #[serde(alias = "Unresolved")] + ProtoNode(ProtoNodeIdentifier), +} +// TODO: Eventually remove this document upgrade code +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub enum NodeExportVersions { + OldNodeInput(NodeOutput), + NodeInput(NodeInput), +} + +// TODO: Eventually remove this document upgrade code +#[derive(Debug, serde::Deserialize)] +pub struct NodeOutput { + pub node_id: NodeId, + pub node_output_index: usize, +} + +// TODO: Eventually remove this document upgrade code +pub(super) fn deserialize_exports<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + let node_input_versions = Vec::::deserialize(deserializer)?; + + // Convert Vec to Vec + let inputs = node_input_versions + .into_iter() + .map(|node_input_version| { + let node_output = match node_input_version { + NodeExportVersions::OldNodeInput(node_output) => node_output, + NodeExportVersions::NodeInput(node_input) => return node_input, + }; + NodeInput::node(node_output.node_id, node_output.node_output_index) + }) + .collect(); + + Ok(inputs) +} + +/// An instance of a [`DocumentNodeDefinition`] that has been instantiated in a [`NodeNetwork`]. +/// Currently, when an instance is made, it lives all on its own without any lasting connection to the definition. +/// But we will want to change it in the future so it merely references its definition. +#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] +pub struct OldDocumentNode { + /// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the node definition's name is displayed to the user in italics. + /// Ensure the click target in the encapsulating network is updated when this is modified by using network.update_click_target(node_id). + #[serde(default)] + pub alias: String, + // TODO: Replace this name with a reference to the [`DocumentNodeDefinition`] node definition to use the name from there instead. + /// The name of the node definition, as originally set by [`DocumentNodeDefinition`], used to display in the UI and to display the appropriate Inspector layout. + #[serde(deserialize_with = "migrate_layer_to_merge")] + pub name: String, + /// The inputs to a node, which are either: + /// - From other nodes within this graph [`NodeInput::Node`], + /// - A constant value [`NodeInput::Value`], + /// - A [`NodeInput::Import`] which specifies that this input is from outside the graph, which is resolved in the graph flattening step in the case of nested networks. + /// + /// In the root network, it is resolved when evaluating the borrow tree. + /// Ensure the click target in the encapsulating network is updated when the inputs cause the node shape to change (currently only when exposing/hiding an input) by using network.update_click_target(node_id). + #[cfg_attr(target_family = "wasm", serde(alias = "outputs"))] + pub inputs: Vec, + pub manual_composition: Option, + // TODO: Remove once this references its definition instead (see above TODO). + /// Indicates to the UI if a primary output should be drawn for this node. + /// True for most nodes, but the Split Channels node is an example of a node that has multiple secondary outputs but no primary output. + #[serde(default = "return_true")] + pub has_primary_output: bool, + // A nested document network or a proto-node identifier. + pub implementation: OldDocumentNodeImplementation, + /// User chosen state for displaying this as a left-to-right node or bottom-to-top layer. Ensure the click target in the encapsulating network is updated when the node changes to a layer by using network.update_click_target(node_id). + #[serde(default)] + pub is_layer: bool, + /// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step. + #[serde(default = "return_true")] + pub visible: bool, + /// Represents the lock icon for locking/unlocking the node in the graph UI. When locked, a node cannot be moved in the graph UI. + #[serde(default)] + pub locked: bool, + /// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id). + pub metadata: OldDocumentNodeMetadata, + /// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called. + #[serde(skip)] + pub original_location: OriginalLocation, +} + +// TODO: Eventually remove this document upgrade code +#[derive(Clone, Debug, PartialEq, Default, Hash, DynAny, serde::Serialize, serde::Deserialize)] +/// Metadata about the node including its position in the graph UI +pub struct OldDocumentNodeMetadata { + pub position: IVec2, +} + +// TODO: Eventually remove this document upgrade code +#[derive(Clone, Copy, Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +/// Root Node is the "default" export for a node network. Used by document metadata, displaying UI-only "Export" node, and for restoring the default preview node. +pub struct OldRootNode { + pub id: NodeId, + pub output_index: usize, +} + +// TODO: Eventually remove this document upgrade code +#[derive(PartialEq, Debug, Clone, Hash, Default, serde::Serialize, serde::Deserialize)] +pub enum OldPreviewing { + /// If there is a node to restore the connection to the export for, then it is stored in the option. + /// Otherwise, nothing gets restored and the primary export is disconnected. + Yes { root_node_to_restore: Option }, + #[default] + No, +} + +// TODO: Eventually remove this document upgrade code +#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)] +/// A network (subgraph) of nodes containing each [`DocumentNode`] and its ID, as well as list mapping each export to its connected node, or a value if disconnected +pub struct OldNodeNetwork { + /// The list of data outputs that are exported from this network to the parent network. + /// Each export is a reference to a node within this network, paired with its output index, that is the source of the network's exported data. + #[serde(alias = "outputs", deserialize_with = "deserialize_exports")] // TODO: Eventually remove this alias document upgrade code + pub exports: Vec, + /// The list of all nodes in this network. + //cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))] + pub nodes: HashMap, + /// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends. + #[serde(default)] + pub previewing: OldPreviewing, + /// Temporary fields to store metadata for "Import"/"Export" UI-only nodes, eventually will be replaced with lines leading to edges + #[serde(default = "default_import_metadata")] + pub imports_metadata: (NodeId, IVec2), + #[serde(default = "default_export_metadata")] + pub exports_metadata: (NodeId, IVec2), + + /// A network may expose nodes as constants which can by used by other nodes using a `NodeInput::Scope(key)`. + #[serde(default)] + //cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))] + pub scope_injections: HashMap, +} + +// TODO: Eventually remove this document upgrade code +fn migrate_layer_to_merge<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let mut s: String = serde::Deserialize::deserialize(deserializer)?; + if s == "Layer" { + s = "Merge".to_string(); + } + Ok(s) +} +// TODO: Eventually remove this document upgrade code +fn default_import_metadata() -> (NodeId, IVec2) { + (NodeId::new(), IVec2::new(-25, -4)) +} +// TODO: Eventually remove this document upgrade code +fn default_export_metadata() -> (NodeId, IVec2) { + (NodeId::new(), IVec2::new(8, -4)) +} + +pub(super) fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + use serde::Deserialize; + + #[derive(serde::Serialize, serde::Deserialize)] + #[serde(untagged)] + enum CallArg { + New(Type), + Old(Option), + } + + Ok(match CallArg::deserialize(deserializer)? { + CallArg::New(ty) => ty, + CallArg::Old(ty) => ty.unwrap_or_default(), + }) +} diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 905e46818f3..d9dcc3bb311 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -1,4 +1,3 @@ -use super::DocumentNode; use crate::application_io::PlatformEditorApi; use crate::application_io::resource::Resource; use crate::proto::{Any as DAny, AnyInput}; @@ -19,6 +18,7 @@ use graphic_types::vector_types::vector::style::DashPattern; use graphic_types::vector_types::vector::style::{Gradient, GradientRamp}; use graphic_types::vector_types::vector::{self, ReferencePoint}; use graphic_types::{Artboard, Graphic, Vector}; +use rendering::deferred_image::EffectMapPlacement; use rendering::{CanvasImage, RenderMetadata}; use std::fmt::Display; use std::hash::Hash; @@ -59,13 +59,6 @@ macro_rules! for_each_list_type_default { }; } -/// Unranked types routed through [`TaggedValue::TypeDefault`], stored as their concrete type. -macro_rules! for_each_bare_type_default { - ($action:ident) => { - $action!(DocumentNode); - }; -} - /// Macro to generate the tagged value enum. macro_rules! tagged_value { ($ ($( #[$meta:meta] )* $identifier:ident ($ty:ty) ),* $(,)?) => { @@ -109,9 +102,6 @@ macro_rules! tagged_value { /// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes an `Item` at runtime via `to_dynany`/`to_any` during graph flattening, matching the ranked connectors it feeds. #[serde(skip)] NodeIdPath(NodeIdPath), - /// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`. - #[serde(skip)] - DocumentNode(DocumentNode), /// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`. #[serde(skip)] ContextModification(ContextModification), @@ -150,7 +140,6 @@ macro_rules! tagged_value { // NON-SERIALIZED VARIANTS // ======================= Self::NodeIdPath(path) => path.cache_hash(state), - Self::DocumentNode(node) => node.cache_hash(state), Self::ContextModification(modification) => modification.cache_hash(state), Self::SourceId(source) => source.cache_hash(state), Self::Runtime(runtime) => runtime.cache_hash(state), @@ -190,15 +179,6 @@ macro_rules! tagged_value { } for_each_item_type_default!(check); } - Type::Concrete(descriptor) => { - let name = descriptor.name.as_ref(); - macro_rules! check_bare { - ($type_default:ty) => { - if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); } - }; - } - for_each_bare_type_default!(check_bare); - } _ => {} } Self::from_type_or_none(&td).to_dynany() @@ -225,7 +205,6 @@ macro_rules! tagged_value { // ======================= Self::RenderOutput(x) => Box::new(Item::new_from_element(x)), Self::NodeIdPath(path) => Box::new(Item::new_from_element(path)), - Self::DocumentNode(node) => Box::new(node), Self::ContextModification(modification) => Box::new(Item::new_from_element(modification)), Self::SourceId(source) => Box::new(Item::new_from_element(source)), Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)), @@ -260,15 +239,6 @@ macro_rules! tagged_value { } for_each_item_type_default!(check); } - Type::Concrete(descriptor) => { - let name = descriptor.name.as_ref(); - macro_rules! check_bare { - ($type_default:ty) => { - if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); } - }; - } - for_each_bare_type_default!(check_bare); - } _ => {} } Self::from_type_or_none(&td).to_any() @@ -295,7 +265,6 @@ macro_rules! tagged_value { // ======================= Self::RenderOutput(x) => Arc::new(Item::new_from_element(x)), Self::NodeIdPath(path) => Arc::new(Item::new_from_element(path)), - Self::DocumentNode(node) => Arc::new(node), Self::ContextModification(modification) => Arc::new(Item::new_from_element(modification)), Self::SourceId(source) => Arc::new(Item::new_from_element(source)), Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)), @@ -328,7 +297,6 @@ macro_rules! tagged_value { // ======================= Self::RenderOutput(_) => item!(RenderOutput), Self::NodeIdPath(_) => item!(NodeIdPath), - Self::DocumentNode(_) => concrete!(DocumentNode), Self::ContextModification(_) => item!(ContextModification), Self::SourceId(_) => item!(SourceId), Self::Runtime(_) => item!(RuntimeHandle), @@ -428,13 +396,6 @@ macro_rules! tagged_value { $( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )* if name == std::any::type_name::>() { return Some(TaggedValue::Strokes(Vec::new())) } if name == std::any::type_name::() { return Some(TaggedValue::BrushCache(Default::default())) } - // Unranked types without a variant route through `TypeDefault`, with `to_dynany`/`to_any` constructing the actual default at execution time - macro_rules! check_bare { - ($type_default:ty) => { - if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(input.clone())); } - }; - } - for_each_bare_type_default!(check_bare); None } Type::Fn(_, output) => TaggedValue::from_type(output), @@ -494,7 +455,6 @@ macro_rules! tagged_value { // ======================= Self::RenderOutput(_) => "RenderOutput".to_string(), Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"), - Self::DocumentNode(node) => format!("DocumentNode({node:?})"), Self::ContextModification(modification) => format!("ContextModification({modification:?})"), Self::SourceId(source) => format!("SourceId({source:?})"), Self::Runtime(_) => "Runtime".to_string(), @@ -577,6 +537,7 @@ tagged_value! { TonalRange(raster_nodes::adjustments::TonalRange), AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel), HueSaturationRange(raster_nodes::adjustments::HueSaturationRange), + GlowTechnique(graphic_types::GlowTechnique), GridType(vector::misc::GridType), GridTopology(vector::misc::GridTopology), ArcType(vector::misc::ArcType), @@ -628,10 +589,15 @@ impl TaggedValue { } pub fn from_primitive_string(string: &str, ty: &Type) -> Option { + fn to_number(input: &str) -> Option { + // Ignores stringified tokens' spacing (e.g. "- 180.") and digit separators (e.g. "1_000_000") + input.chars().filter(|character| !character.is_whitespace() && *character != '_').collect::().parse().ok() + } + fn to_dvec2(input: &str) -> Option { let mut split = input.split(','); - let x = split.next()?.trim().parse().ok()?; - let y = split.next()?.trim().parse().ok()?; + let x = to_number(split.next()?)?; + let y = to_number(split.next()?)?; Some(DVec2::new(x, y)) } @@ -706,6 +672,22 @@ impl TaggedValue { None } + // The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), rendered at 100% resolution + fn to_footprint(input: &str) -> Option { + let values: Option> = input.split(',').map(to_number).collect(); + let Some(&[x, y, width, height]) = values.as_deref() else { + log::error!("Invalid Footprint default, which needs X, Y, W, H: {input}"); + return None; + }; + let size = DVec2::new(width, height); + + Some(Footprint { + transform: DAffine2::from_scale_angle_translation(size, 0., DVec2::new(x, y)), + resolution: size.as_uvec2(), + ..Default::default() + }) + } + match ty { Type::Generic(_) => None, Type::Concrete(concrete_type) => { @@ -715,8 +697,8 @@ impl TaggedValue { let ty = match () { () if ty == TypeId::of::<()>() => TaggedValue::None, () if ty == TypeId::of::() => TaggedValue::String(string.into()), - () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Number).ok()?, - () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Integer).ok()?, + () if ty == TypeId::of::() => to_number(string).map(TaggedValue::Number)?, + () if ty == TypeId::of::() => to_number(string).map(TaggedValue::Integer)?, () if ty == TypeId::of::() => to_dvec2(string).map(TaggedValue::DVec2)?, () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?, () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, @@ -724,6 +706,7 @@ impl TaggedValue { () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, () if ty == TypeId::of::() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?, () if ty == TypeId::of::() => to_reference_point(string).map(TaggedValue::ReferencePoint)?, + () if ty == TypeId::of::() => to_footprint(string).map(TaggedValue::Footprint)?, () if ty == TypeId::of::() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)), () if ty == TypeId::of::() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)), _ => return None, @@ -938,6 +921,9 @@ pub enum RenderOutputType { svg: String, /// The images the SVG draws to canvases, by the canvas ID their placeholders name. image_data: Vec<(u64, CanvasImage)>, + /// Maps of effects' coverages the GPU rendered for the SVG's filters, which go in place of their placeholders once read back. + #[serde(skip)] + effect_maps: Vec<(EffectMapPlacement, graphene_application_io::Texture)>, }, #[cfg(target_family = "wasm")] CanvasFrame { canvas_id: u64, resolution: DVec2 }, @@ -953,9 +939,13 @@ impl CacheHash for RenderOutputType { width.cache_hash(state); height.cache_hash(state); } - Self::Svg { svg, image_data } => { + Self::Svg { svg, image_data, effect_maps } => { svg.cache_hash(state); image_data.cache_hash(state); + for (placement, texture) in effect_maps { + placement.id.cache_hash(state); + texture.hash(state); + } } #[cfg(target_family = "wasm")] Self::CanvasFrame { canvas_id, resolution } => { @@ -977,7 +967,7 @@ impl CacheHash for RenderOutput { #[cfg(test)] mod typedefault_dispatch { use super::*; - use core_types::{concrete, item, list}; + use core_types::{item, list}; /// Round-trips every type in the type-default lists through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the stored type. /// @@ -1015,14 +1005,8 @@ mod typedefault_dispatch { check!(List<$element>, list!($element)); }; } - macro_rules! check_bare { - ($type_default:ty) => { - check!($type_default, concrete!($type_default)); - }; - } for_each_item_type_default!(check_item); for_each_list_type_default!(check_list); - for_each_bare_type_default!(check_bare); } } @@ -1073,6 +1057,34 @@ mod paint_default_parsing { } } +#[cfg(test)] +mod number_default_parsing { + use super::*; + use core_types::item; + + /// A negative default reaches the parser as stringified tokens, with a space between the minus sign and the digits. + #[test] + fn negative_number_defaults_parse() { + assert_eq!(TaggedValue::from_primitive_string("- 180.", &item!(f64)), Some(TaggedValue::Number(-180.))); + assert_eq!(TaggedValue::from_primitive_string("- 3", &item!(i64)), Some(TaggedValue::Integer(-3))); + assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.)))); + } + + #[test] + fn footprint_defaults_parse_as_x_y_width_height() { + let expected = Footprint { + transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)), + resolution: glam::UVec2::new(10_000, 500), + ..Default::default() + }; + assert_eq!( + TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)), + Some(TaggedValue::Footprint(expected)) + ); + assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None); + } +} + #[cfg(test)] mod gradient_shape_migration { use graphic_types::vector_types::{GradientSpace, GradientSpread}; diff --git a/node-graph/graph-craft/src/graphene_compiler.rs b/node-graph/graph-craft/src/graphene_compiler.rs index a91a48a994d..21defb0d067 100644 --- a/node-graph/graph-craft/src/graphene_compiler.rs +++ b/node-graph/graph-craft/src/graphene_compiler.rs @@ -41,6 +41,7 @@ impl Compiler { for id in node_ids { network.flatten(id); } + network.definitions.clear(); network.remove_all_passthrough_nodes(); // network.remove_dead_nodes(0); let proto_networks = network.into_proto_networks(); diff --git a/node-graph/graph-craft/src/lib.rs b/node-graph/graph-craft/src/lib.rs index 6dbbdf6c4dd..797878b9018 100644 --- a/node-graph/graph-craft/src/lib.rs +++ b/node-graph/graph-craft/src/lib.rs @@ -6,6 +6,7 @@ extern crate core_types; pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic, item, list}; pub mod application_io; +mod compiler; pub mod document; pub mod runtime_delta; pub use document::{DocumentNode, NodeNetwork}; diff --git a/node-graph/graph-craft/src/proto.rs b/node-graph/graph-craft/src/proto.rs index 1b0c1fef54d..2e8697eac03 100644 --- a/node-graph/graph-craft/src/proto.rs +++ b/node-graph/graph-craft/src/proto.rs @@ -124,7 +124,6 @@ pub struct ProtoNode { pub call_argument: Type, pub identifier: ProtoNodeIdentifier, pub original_location: OriginalLocation, - pub skip_deduplication: bool, pub(crate) compile_metadata: NodeCompileMetadata, /// The context features read by this node and everything upstream of it. pub upstream_context_features: ContextFeatures, @@ -137,7 +136,6 @@ impl Default for ProtoNode { construction_args: ConstructionArgs::Value(value::TaggedValue::Integer(0).into()), call_argument: concrete!(()), original_location: OriginalLocation::default(), - skip_deduplication: false, compile_metadata: Default::default(), upstream_context_features: ContextFeatures::empty(), } @@ -146,16 +144,12 @@ impl Default for ProtoNode { impl ProtoNode { /// A stable node ID is a hash of a node that should stay constant. This is used in order to remove duplicates from the graph. - /// In the case of `skip_deduplication`, the `document_node_path` is also hashed in order to avoid duplicate monitor nodes from being removed (which would make it impossible to load thumbnails). pub fn stable_node_id(&self) -> Option { use std::hash::Hasher; let mut hasher = rustc_hash::FxHasher::default(); self.identifier.as_str().hash(&mut hasher); self.construction_args.cache_hash(&mut hasher); - if self.skip_deduplication { - self.original_location.path.hash(&mut hasher); - } std::mem::discriminant(&self.call_argument).hash(&mut hasher); self.call_argument.hash(&mut hasher); @@ -173,7 +167,6 @@ impl ProtoNode { path: Some(path), ..Default::default() }, - skip_deduplication: false, compile_metadata: Default::default(), upstream_context_features: ContextFeatures::empty(), } @@ -355,7 +348,6 @@ impl ProtoNetwork { }, compile_metadata: forwarding, upstream_context_features: features, - ..Default::default() }, )); @@ -387,7 +379,6 @@ impl ProtoNetwork { }, compile_metadata: forwarding, upstream_context_features: features, - ..Default::default() }, )); nullification_node_id @@ -621,6 +612,10 @@ pub enum GraphErrorType { NonConstantInput { index: usize, }, + /// The input's value refers to a resource the document can't resolve to its data. + MissingResource { + index: usize, + }, } impl Debug for GraphErrorType { // TODO: format with the document graph context so the input index is the same as in the graph UI. @@ -669,6 +664,11 @@ impl Debug for GraphErrorType { "Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed" ), GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1), + GraphErrorType::MissingResource { index } => write!( + f, + "Warning: input {} needs a font, image, or other resource that can't be found, so a fallback is used in its place", + index + 1 + ), } } } diff --git a/node-graph/graph-craft/src/runtime_delta.rs b/node-graph/graph-craft/src/runtime_delta.rs index 6df9f1772cf..e4de9d883e3 100644 --- a/node-graph/graph-craft/src/runtime_delta.rs +++ b/node-graph/graph-craft/src/runtime_delta.rs @@ -1,4 +1,4 @@ -use crate::document::{DocumentNode, NetworkId, NodeId, NodeInput, NodeNetwork, OwnedNetworkLocation}; +use crate::document::{DocumentNode, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork}; use core_types::Type; /// One mutation's worth of structural graph change, carrying its post-change data as plain runtime @@ -28,22 +28,22 @@ pub enum RuntimeDelta { }, /// The node's nested network, if it implements one, rides inside the [`DocumentNode`]. AddNode { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, node: Box, }, ReplaceNode { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, node: Box, }, /// Address-only: removal snapshots come from the storage layer's working registry. RemoveNode { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, }, SetInput { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, input_index: usize, input: NodeInput, @@ -51,24 +51,24 @@ pub enum RuntimeDelta { /// A node's whole input list, which is how a change to the number or order of its slots is /// expressed, since [`SetInput`](Self::SetInput) addresses one index and cannot move the others. SetInputs { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, inputs: Vec, }, /// `None` removes the slot, matching the storage op this converts to. SetExport { - network: OwnedNetworkLocation, + network: NetworkLocation, export_index: usize, input: Option, }, SetVisibility { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, visible: bool, }, /// The [`Type`] of argument the node can be evaluated with. SetCallArgument { - network: OwnedNetworkLocation, + network: NetworkLocation, node_id: NodeId, call_argument: Type, }, diff --git a/node-graph/graph-craft/src/util.rs b/node-graph/graph-craft/src/util.rs index e4f0bf0d73d..8d73b3e4509 100644 --- a/node-graph/graph-craft/src/util.rs +++ b/node-graph/graph-craft/src/util.rs @@ -2,23 +2,11 @@ use crate::document::NodeNetwork; use crate::graphene_compiler::Compiler; use crate::proto::ProtoNetwork; -pub fn load_network(document_string: &str) -> NodeNetwork { - let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document"); - let document = (document["network_interface"]["network"].clone()).to_string(); - serde_json::from_str::(&document).expect("Failed to parse document") -} - pub fn compile(network: NodeNetwork) -> ProtoNetwork { let compiler = Compiler {}; compiler.compile_single(network).unwrap().network } -pub fn load_from_name(name: &str) -> NodeNetwork { - let content = std::fs::read(format!("../../demo-artwork/{name}.graphite")).expect("failed to read file"); - let content = std::str::from_utf8(&content).unwrap(); - load_network(content) -} - pub static DEMO_ART: [&str; 7] = [ "changing-seasons", "painted-dreams", diff --git a/node-graph/graphene-cli/Cargo.toml b/node-graph/graphene-cli/Cargo.toml index cb4178fb335..4d3d4677b9a 100644 --- a/node-graph/graphene-cli/Cargo.toml +++ b/node-graph/graphene-cli/Cargo.toml @@ -27,18 +27,21 @@ graph-craft = { workspace = true, features = ["loading"] } preprocessor = { workspace = true } document-format = { workspace = true, features = ["zip", "xz", "migrations"] } document-container = { workspace = true, features = ["zip", "xz"] } -migration-formats = { workspace = true } -migration-nodes = { workspace = true } +document-graph-storage = { workspace = true } +document-live = { workspace = true } +document-loader = { workspace = true } # Workspace dependencies log = { workspace = true } fern = { workspace = true } chrono = { workspace = true } wgpu = { workspace = true } -tokio = { workspace = true } +tokio = { workspace = true, features = ["io-util", "time"] } +winit = { workspace = true } clap = { workspace = true, features = ["cargo", "derive"] } image = { workspace = true } serde_json = { workspace = true } +getrandom = "0.4" wgpu-executor = { workspace = true, optional = true } [package.metadata.cargo-shear] diff --git a/node-graph/graphene-cli/src/dump.rs b/node-graph/graphene-cli/src/dump.rs index d1ee3ed7421..73fd95dd9b4 100644 --- a/node-graph/graphene-cli/src/dump.rs +++ b/node-graph/graphene-cli/src/dump.rs @@ -2,6 +2,7 @@ use graph_craft::ProtoNodeIdentifier; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; +use graphene_std::graphic::write_layer_path; use graphene_std::simplify_identifier_name; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::error::Error; @@ -57,6 +58,7 @@ enum Kind { Nullify, Expand, Scope, + LayerPath, } impl Kind { @@ -68,6 +70,7 @@ impl Kind { Kind::Nullify => "+nullify", Kind::Expand => "+expand", Kind::Scope => "+scope", + Kind::LayerPath => "+layer-path", } } } @@ -234,6 +237,7 @@ fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind { _ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify, _ if proto.original_location.auto_convert_index.is_some() => Kind::Convert, ConstructionArgs::Value(_) => Kind::Value, + _ if proto.identifier == write_layer_path::IDENTIFIER => Kind::LayerPath, _ if origin.is_empty() => Kind::Scope, _ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document, _ => Kind::Expand, diff --git a/node-graph/graphene-cli/src/export.rs b/node-graph/graphene-cli/src/export.rs index c4ee7949821..bee11ebcf62 100644 --- a/node-graph/graphene-cli/src/export.rs +++ b/node-graph/graphene-cli/src/export.rs @@ -7,7 +7,6 @@ use graphene_std::core_types::transform::Footprint; use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::runtime::AsyncRuntime; use graphene_std::vector::{no_paths, paths_from_item_attributes}; -use graphene_std::{Cover, Coverage}; use graphene_std::{NodeError, Poll}; use image::ImageFormat; use interpreted_executor::dynamic_executor::DynamicExecutor; @@ -133,7 +132,7 @@ async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spaw // Metadata only records the first item of a layer, so the other items count through their click targets, without their strokes. let stroked = metadata.vector_data.get(layer).and_then(|item| { let appearance = metadata.appearance_attributes.get(layer); - let stroke = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map(Coverage::stroke_params); + let stroke = appearance.and_then(|appearance| appearance.first_stroke_params()); let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths()); item.element().stroke_inclusive_bounding_box_with_transform(paths, transform, stroke.as_ref()) }); @@ -190,7 +189,10 @@ pub(crate) async fn render_frame( // Execute the graph and extract its output match execute_until_settled(executor, runtime, spawner, render_config).await? { TaggedValue::RenderOutput(output) => match output.data { - RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)), + RenderOutputType::Svg { mut svg, effect_maps, .. } => { + wgpu_executor.resolve_effect_maps(&mut svg, effect_maps).await; + Ok(RenderedFrame::Svg(svg)) + } RenderOutputType::Texture(texture) => { // Convert GPU texture to CPU buffer let gpu_raster = Raster::::new_gpu(texture); @@ -391,7 +393,7 @@ pub async fn export_image_sequence( Ok(()) } -async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result> { +pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result> { let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot())); let mut frame = execute()?; while spawner.join().await { diff --git a/node-graph/graphene-cli/src/lib.rs b/node-graph/graphene-cli/src/lib.rs index 3caaa461aa2..b630c493bf8 100644 --- a/node-graph/graphene-cli/src/lib.rs +++ b/node-graph/graphene-cli/src/lib.rs @@ -1,20 +1,19 @@ -//! Opens, compiles, and renders Graphite documents without the editor. A `.gdd` opens through the format steps and node migrations -//! this crate links, so every binary built on it reads documents the way the current build writes them. +//! Opens, compiles, and renders Graphite documents without the editor. Documents open through `document-loader`, so every binary +//! built on it reads documents the way the current build writes them. pub mod dump; pub mod export; -use document_container::AnyContainer; -use document_container::backends::memory::MemoryBackend; -use document_format::{GddV1, GddV1Layout}; +use document_format::GddV1; +use document_loader::{DocumentOrigin, LoadedDocument}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; -use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork, OwnedNetworkLocation}; +use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork}; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::ProtoNetwork; -use graph_craft::util::load_network; use graphene_std::application_io::ApplicationIo; -use graphene_std::runtime::{AsyncRuntime, Spawn, Task}; +use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task}; use interpreted_executor::dynamic_executor::DynamicExecutor; +use interpreted_executor::layer_paths::write_layer_paths; use interpreted_executor::util::wrap_network_in_scope; use std::collections::HashMap; use std::error::Error; @@ -22,61 +21,43 @@ use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -// Referenced so the linker keeps their self-registering migrations -use migration_formats as _; -use migration_nodes as _; - /// A document as the CLI loads it: the runtime network, plus the `.gdd` it came from, if any. pub struct OpenedDocument { pub gdd: Option, pub network: NodeNetwork, + /// The path of every layer in `network`. + pub layers: Vec>, /// What `dump` shows for each node and network, when asked for. pub names: Option, String>>, } -/// Open a `.gdd` from its archive bytes into memory, running the migrations this crate links. -pub async fn open_gdd(archive: &[u8]) -> Result> { - let container = AnyContainer::Memory(MemoryBackend::new()); - let gdd = GddV1::open_from_archive(archive, container, GddV1Layout) - .await - .map_err(|error| format!("Failed to open document: {error}"))?; - Ok(gdd) -} - -/// Open `path` by extension: `.gdd` as an archive, anything else as a legacy `.graphite` document. `with_names` also collects its display names. +/// Open `path` with [`document_loader::open_document`]. `with_names` also collects its display names. pub async fn open_document(path: &Path, with_names: bool) -> Result> { - let is_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd")); - - if !is_gdd { - let document_string = std::fs::read_to_string(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; - return Ok(OpenedDocument { - gdd: None, - network: load_network(&document_string), - names: with_names.then(|| dump::legacy_names(&document_string)), - }); - } - - let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; - let gdd = open_gdd(&archive).await?; - let declarations = gdd.declarations(&gdd).await; - let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?; - let names = with_names.then(|| { - let references: HashMap<_, _> = networks.into_iter().filter_map(|network| Some((network.network, network.reference?))).collect(); - let display_names: HashMap<_, _> = nodes.into_iter().filter_map(|node| Some(((node.network, node.local_id), node.display_name?))).collect(); - instance_names(&network, &references, &display_names) - }); - Ok(OpenedDocument { gdd: Some(gdd), network, names }) + let LoadedDocument { network, layers, origin } = document_loader::open_document(path).await?; + + let (gdd, names) = match origin { + DocumentOrigin::Legacy(document_string) => (None, with_names.then(|| dump::legacy_names(&document_string))), + DocumentOrigin::Gdd { gdd, nodes, networks } => { + let names = with_names.then(|| { + let references: HashMap<_, _> = networks.into_iter().filter_map(|network| Some((network.network, network.reference?))).collect(); + let display_names: HashMap<_, _> = nodes.into_iter().filter_map(|node| Some(((node.network, node.local_id), node.display_name?))).collect(); + instance_names(&network, &references, &display_names) + }); + (Some(*gdd), names) + } + }; + Ok(OpenedDocument { gdd, network, layers, names }) } /// The name of each node, keyed by the path the dump visits it at. /// This is its display name, or else the reference of the network it implements. -fn instance_names(network: &NodeNetwork, references: &HashMap, display_names: &HashMap<(OwnedNetworkLocation, NodeId), String>) -> HashMap, String> { +fn instance_names(network: &NodeNetwork, references: &HashMap, display_names: &HashMap<(NetworkLocation, NodeId), String>) -> HashMap, String> { network .recursive_nodes() .filter_map(|(id, _, path)| { - let containing = network.locate(&path)?.to_owned_location(); + let containing = network.locate(&path)?; let node_path = [path.as_slice(), &[*id]].concat(); - let implemented = network.locate(&node_path).map(NetworkLocation::to_owned_location); + let implemented = network.locate(&node_path); let display_name = display_names.get(&(containing, *id)).filter(|name| !name.is_empty()); let reference = implemented.and_then(|location| references.get(&location)).filter(|name| !name.is_empty()); @@ -93,11 +74,10 @@ pub struct CompiledDocument { spawner: Arc, } -/// Compile `document` against a fresh GPU context, resolving its resources from its `.gdd`. -pub async fn compile_document(document: OpenedDocument) -> Result> { +pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc, Arc) { log::info!("Creating GPU context"); let mut application_io = PlatformApplicationIo::new().await; - if let Some(gdd) = &document.gdd { + if let Some(gdd) = gdd { application_io.inject_resource_proxy(Box::new(gdd.resource_proxy())); } let application_io = Arc::new(application_io); @@ -109,14 +89,16 @@ pub async fn compile_document(document: OpenedDocument) -> Result], editor_api: Arc, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result> { + write_layer_paths(&mut network, layers); + let mut network = wrap_network_in_scope(network, editor_api, runtime); - // A `.gdd` resolves resource hashes from its registry, while a legacy `.graphite` has no resource store let preprocessor = preprocessor::Preprocessor::new(); - let preprocessed = match &document.gdd { + let preprocessed = match gdd { Some(gdd) => preprocessor.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|resource| resource.hash)), None => preprocessor.preprocess(&mut network, &|_| None), }; @@ -126,9 +108,24 @@ pub async fn compile_document(document: OpenedDocument) -> Result Result> { + DynamicExecutor::new(proto_network).map_err(|errors| { + let messages: Vec = errors.iter().map(|error| format!("{error:?}")).collect(); + messages.join("\n").into() + }) +} + +pub async fn compile_document(document: OpenedDocument) -> Result> { + let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await; + let spawner = Arc::new(TokioSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + let proto_network = compile_graph(document.network, &document.layers, editor_api, document.gdd.as_ref(), runtime.handle())?; Ok(CompiledDocument { - proto_network: compiled_network.network, + proto_network, application_io, runtime, spawner, @@ -137,11 +134,8 @@ pub async fn compile_document(document: OpenedDocument) -> Result Result> { - let executor = DynamicExecutor::new(self.proto_network).map_err(|errors| { - let messages: Vec = errors.iter().map(|error| format!("{error:?}")).collect(); - messages.join("\n") - })?; - self.runtime.retain_sources(executor.sources()); + let executor = create_executor(self.proto_network)?; + self.runtime.update_sources(executor.sources()); let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone(); let polling = Arc::new(AtomicBool::new(true)); diff --git a/node-graph/graphene-cli/src/live.rs b/node-graph/graphene-cli/src/live.rs new file mode 100644 index 00000000000..39ffbaa19da --- /dev/null +++ b/node-graph/graphene-cli/src/live.rs @@ -0,0 +1,75 @@ +use crate::repl; +use document_graph_storage::{PeerId, UserId}; +use document_live::{LiveDocument, SessionToken}; +use std::error::Error; +use std::path::Path; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, BufReader}; + +pub async fn host(signaling: &str, document: Option<&Path>) -> Result<(), Box> { + let (peer, user) = identity()?; + let live = match document { + Some(path) => { + let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; + let mut gdd = document_loader::open_gdd(&archive).await?; + // The source document may be open elsewhere under the peer the archive holds + gdd.set_user(user, peer)?; + let token = SessionToken::for_document(gdd.manifest().document_id); + LiveDocument::host_document(gdd, signaling, token, user, spawn_driver)? + } + // An empty document takes the peer id as its document id + None => LiveDocument::host(signaling, SessionToken::for_document(peer.0), peer, user, spawn_driver).await?, + }; + println!("hosting session {}", live.token()); + drive_from_stdin(live).await; + Ok(()) +} + +pub async fn join(signaling: &str, token: SessionToken) -> Result<(), Box> { + let (peer, user) = identity()?; + let live = LiveDocument::join(signaling, token, peer, user, spawn_driver).await?; + println!("joining session {token}"); + drive_from_stdin(live).await; + Ok(()) +} + +pub async fn watch(signaling: &str, token: SessionToken) -> Result<(), Box> { + let (peer, user) = identity()?; + let live = LiveDocument::join(signaling, token, peer, user, spawn_driver).await?; + crate::watch::run(live).await +} + +async fn drive_from_stdin(mut live: LiveDocument) { + let mut lines = BufReader::new(tokio::io::stdin()).lines(); + let mut tick = tokio::time::interval(Duration::from_millis(100)); + + loop { + tokio::select! { + _ = tick.tick() => { + for event in live.poll().await { + repl::report(&event); + } + } + line = lines.next_line() => { + let Ok(Some(line)) = line else { break }; + if !repl::run_command(&mut live, line.trim()) { + break; + } + } + } + } + live.leave(); +} + +fn spawn_driver(driver: document_live::MessageLoopFuture) { + tokio::spawn(async move { + if let Err(error) = driver.await { + log::error!("Session transport ended: {error}"); + } + }); +} + +fn identity() -> Result<(PeerId, UserId), getrandom::Error> { + let peer = PeerId(getrandom::u64()?); + Ok((peer, UserId(peer.0))) +} diff --git a/node-graph/graphene-cli/src/main.rs b/node-graph/graphene-cli/src/main.rs index c5c8f63b35c..8bf78b11446 100644 --- a/node-graph/graphene-cli/src/main.rs +++ b/node-graph/graphene-cli/src/main.rs @@ -1,6 +1,13 @@ +mod live; +mod repl; +mod watch; + use clap::{Args, Parser, Subcommand}; +use document_container::archive::ArchiveFormat; +use document_live::{DEFAULT_SIGNALING_SERVER, SessionToken}; +use document_loader::open_gdd; use fern::colors::{Color, ColoredLevelConfig}; -use graphene_cli::{compile_document, dump, export, open_document, open_gdd}; +use graphene_cli::{compile_document, dump, export, open_document}; use std::error::Error; use std::path::PathBuf; @@ -80,6 +87,24 @@ enum Command { ExtractLegacyDoc { document: PathBuf, }, + /// Host a collaborative session on a .gdd document, or an empty one, driven from stdin. + Host { + document: Option, + #[clap(long, default_value = DEFAULT_SIGNALING_SERVER)] + signaling: String, + }, + /// Join a collaborative session and drive it from stdin. + Join { + token: SessionToken, + #[clap(long, default_value = DEFAULT_SIGNALING_SERVER)] + signaling: String, + }, + /// Join a collaborative session and show the document in a window. + Watch { + token: SessionToken, + #[clap(long, default_value = DEFAULT_SIGNALING_SERVER)] + signaling: String, + }, } #[derive(Debug, Args)] @@ -96,6 +121,9 @@ async fn main() -> Result<(), Box> { init_logging(app.global_opts.verbose); let document_path = match &app.command { + Command::Host { document, signaling } => return live::host(signaling, document.as_deref()).await, + Command::Join { token, signaling } => return live::join(signaling, *token).await, + Command::Watch { token, signaling } => return live::watch(signaling, *token).await, Command::Compile { document, .. } | Command::Export { document, .. } | Command::ExtractLegacyDoc { document } => document, Command::ListNodeIdentifiers => { let mut nodes: Vec<_> = graphene_std::registry::NODE_METADATA.lock().unwrap().keys().cloned().collect(); @@ -109,15 +137,18 @@ async fn main() -> Result<(), Box> { // Before the document converts to a network, so a registry that can't convert doesn't block recovering the legacy file if let Command::ExtractLegacyDoc { document: path } = &app.command { - if !path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd")) { + let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; + if ArchiveFormat::detect(&archive).is_none() { return Err("ExtractLegacyDoc requires a .gdd document".into()); } - let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; + let gdd = open_gdd(&archive).await?; let Some(legacy_doc) = gdd.read_legacy_document().await else { return Err("gdd file did not contain a legacy .graphite document".into()); }; - let new_path = path.with_extension("graphite"); + + // Saved documents carry the `.graphite` extension too, so the extracted file is named apart from its source + let new_path = path.with_extension("legacy.graphite"); std::fs::write(&new_path, legacy_doc).map_err(|error| format!("Failed to write .graphite file: {error}"))?; eprintln!("Saved file to {}", new_path.to_string_lossy()); return Ok(()); @@ -177,7 +208,7 @@ async fn main() -> Result<(), Box> { export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?; } } - Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } => unreachable!("Handled before compiling"), + Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } | Command::Host { .. } | Command::Join { .. } | Command::Watch { .. } => unreachable!("Handled before compiling"), } Ok(()) diff --git a/node-graph/graphene-cli/src/repl.rs b/node-graph/graphene-cli/src/repl.rs new file mode 100644 index 00000000000..ee83f272dae --- /dev/null +++ b/node-graph/graphene-cli/src/repl.rs @@ -0,0 +1,97 @@ +//! Line commands that drive a live document from stdin. + +use document_graph_storage::{AttributeDelta, RegistryDelta, Rev}; +use document_live::{Event, LiveDocument}; + +pub fn report(event: &Event) { + match event { + Event::PeerJoined { peer, user } => println!("peer {peer:?} joined as {user:?}"), + Event::PeerLeft { peer } => println!("peer {peer:?} left"), + Event::RoleChanged { role } => println!("role is now {role:?}"), + Event::ProfileChanged { peer } => println!("peer {peer:?} announced a name"), + Event::CursorMoved { .. } => {} + Event::MetadataChanged => println!("the record of the document's users changed"), + Event::Synced => println!("synced"), + Event::Changed => println!("document changed"), + Event::ResourceReceived { hash, bytes } => println!("received resource {hash} ({} bytes)", bytes.len()), + Event::ResourceRequested { hash, .. } => println!("peer asked for resource {hash}"), + } +} + +pub fn run_command(live: &mut LiveDocument, line: &str) -> bool { + match split_command(line) { + (Some("set"), Some(key), Some(value)) => { + let Ok(value) = serde_json::from_str(value) else { + println!("value must be JSON"); + return true; + }; + let delta = AttributeDelta { + key: key.to_string(), + value: Some(value), + }; + if let Err(error) = live.document_mut().stage_ops([RegistryDelta::ChangeDocumentAttribute { delta }]) { + println!("stage failed: {error}"); + } + } + (Some("retire"), ..) => match live.document_mut().retire_pending_interaction() { + Ok(revs) => println!("retired {} deltas", revs.len()), + Err(error) => println!("retire failed: {error}"), + }, + (Some("show"), ..) => { + let registry = live.document().registry(); + for (key, value) in registry.attributes.live() { + println!("{key} = {:?} @{}", value.value, value.timestamp.counter); + } + for id in registry.networks.keys() { + println!("network {id:?}"); + } + println!("{} hot ops pending", live.document().session().hot_log().len()); + } + (Some("history"), ..) => { + for delta in live.document().session().history() { + println!("{} by {:?} @{} {}", short_rev(delta.id), delta.author, delta.timestamp.counter, describe(&delta.kind)); + } + } + (Some("quit"), ..) => return false, + _ => println!("commands: set , retire, show, history, quit"), + } + true +} + +/// The command word, the next word and the rest of the line. +fn split_command(line: &str) -> (Option<&str>, Option<&str>, Option<&str>) { + fn next_word(text: &str) -> (Option<&str>, &str) { + let text = text.trim_start(); + let (word, rest) = text.split_once(char::is_whitespace).unwrap_or((text, "")); + ((!word.is_empty()).then_some(word), rest) + } + let (command, rest) = next_word(line); + let (argument, rest) = next_word(rest); + let rest = rest.trim(); + (command, argument, (!rest.is_empty()).then_some(rest)) +} + +fn describe(kind: &RegistryDelta) -> String { + match kind { + RegistryDelta::ChangeDocumentAttribute { delta } => format!("set {} = {:?}", delta.key, delta.value), + RegistryDelta::RegisterPeer { peer, user } => format!("register {peer:?} as {user:?}"), + RegistryDelta::Merge { extra_parents } => format!("merge {} extra parents", extra_parents.len()), + other => format!("{other:?}").chars().take(60).collect(), + } +} + +fn short_rev(rev: Rev) -> String { + format!("{rev}").chars().take(8).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_split_at_any_run_of_whitespace() { + assert_eq!(split_command("set name\t\"a b\" "), (Some("set"), Some("name"), Some("\"a b\""))); + assert_eq!(split_command("\tretire"), (Some("retire"), None, None)); + assert_eq!(split_command(" "), (None, None, None)); + } +} diff --git a/node-graph/graphene-cli/src/watch.rs b/node-graph/graphene-cli/src/watch.rs new file mode 100644 index 00000000000..1dfe1059300 --- /dev/null +++ b/node-graph/graphene-cli/src/watch.rs @@ -0,0 +1,278 @@ +use document_live::{Event, LiveDocument}; +use graph_craft::application_io::resource::ResourceHash; +use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; +use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue, UVec2}; +use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export}; +use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig}; +use graphene_std::runtime::AsyncRuntime; +use interpreted_executor::dynamic_executor::DynamicExecutor; +use std::error::Error; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use wgpu::util::{TextureBlitter, TextureBlitterBuilder}; +use wgpu_executor::{WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface}; +use winit::application::ApplicationHandler; +use winit::event::{StartCause, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::window::{Window, WindowAttributes, WindowId}; + +const POLL_INTERVAL: Duration = Duration::from_millis(50); +const BACKGROUND: wgpu::Color = wgpu::Color { r: 0.015, g: 0.015, b: 0.015, a: 1. }; + +pub async fn run(mut live: LiveDocument) -> Result<(), Box> { + let (application_io, editor_api) = editor_api(Some(live.document())).await; + if application_io.gpu_executor().is_none() { + live.leave(); + return Err("watching a session needs a usable GPU".into()); + } + let event_loop = EventLoop::new().inspect_err(|_| live.leave())?; + let spawner = Arc::new(TokioSpawner::default()); + + let viewer = Viewer { + live, + application_io, + editor_api, + runtime: tokio::runtime::Handle::current(), + spawner: spawner.clone(), + graph_runtime: AsyncRuntime::new(spawner), + window: None, + surface: None, + blitter: None, + executor: None, + dirty: false, + waiting: Vec::new(), + }; + tokio::task::block_in_place(|| event_loop.run_app(viewer))?; + Ok(()) +} + +struct Viewer { + live: LiveDocument, + application_io: Arc, + editor_api: Arc, + runtime: tokio::runtime::Handle, + spawner: Arc, + graph_runtime: AsyncRuntime, + window: Option>, + surface: Option<(WgpuSurface, wgpu::SurfaceConfiguration)>, + blitter: Option, + executor: Option, + dirty: bool, + waiting: Vec, +} + +impl Viewer { + fn wgpu_executor(&self) -> &WgpuExecutor { + self.application_io.gpu_executor().expect("`run` checks for a GPU executor") + } + + fn create_surface(&mut self, window: &Arc) -> Result<(), wgpu::CreateSurfaceError> { + let context = self.wgpu_executor().context(); + let surface = context.instance.create_surface(window.clone())?; + let capabilities = surface.get_capabilities(&context.adapter); + // The bytes are already sRGB encoded, so a non-sRGB target passes them through + let preferred = [wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Rgba8Unorm]; + let format = preferred.into_iter().find(|format| capabilities.formats.contains(format)).unwrap_or(capabilities.formats[0]); + let size = window.surface_size(); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format, + width: size.width.max(1), + height: size.height.max(1), + present_mode: capabilities.present_modes[0], + alpha_mode: capabilities.alpha_modes[0], + view_formats: vec![], + desired_maximum_frame_latency: 1, + color_space: wgpu::SurfaceColorSpace::Auto, + }; + surface.configure(&context.device, &config); + + self.blitter = Some(TextureBlitterBuilder::new(&context.device, format).blend_state(wgpu::BlendState::ALPHA_BLENDING).build()); + self.surface = Some((surface, config)); + Ok(()) + } + + fn quit(&mut self, event_loop: &dyn ActiveEventLoop) { + self.live.leave(); + event_loop.exit(); + } + + fn resize(&mut self) { + let Some(window) = &self.window else { return }; + let size = window.surface_size(); + let device = self.wgpu_executor().context().device.clone(); + if let Some((surface, config)) = &mut self.surface + && size.width > 0 + && size.height > 0 + { + config.width = size.width; + config.height = size.height; + surface.configure(&device, config); + } + } + + fn log_missing_resources(&mut self) { + let missing = self.live.missing_resources(); + if missing == self.waiting { + return; + } + if !missing.is_empty() { + let hashes = missing.iter().map(ToString::to_string).collect::>().join(", "); + log::info!("Waiting for {} resources no peer has sent yet: {hashes}", missing.len()); + } + self.waiting = missing; + } + + fn recompile(&mut self) { + let (network, layers) = match self.runtime.block_on(self.live.network_with_layers()) { + Ok(network_with_layers) => network_with_layers, + Err(error) => return log::error!("Failed to build the runtime network: {error}"), + }; + let proto = match compile_graph(network, &layers, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) { + Ok(proto) => proto, + Err(error) => return log::error!("Compile failed: {error}"), + }; + match create_executor(proto) { + Ok(executor) => { + self.graph_runtime.update_sources(executor.sources()); + log::info!("Document compiled"); + self.executor = Some(executor); + } + Err(error) => log::error!("Executor creation failed: {error}"), + } + } + + fn draw(&mut self) -> Result<(), Box> { + let (Some(window), Some((surface, config)), Some(blitter)) = (&self.window, &self.surface, &self.blitter) else { + return Ok(()); + }; + + // Present even without a frame, since Wayland never shows a surface with no committed buffer + let frame = match &self.executor { + Some(executor) => { + let mut render_config = RenderConfig { + export_format: ExportFormat::Raster, + scale: 1., + ..Default::default() + }; + render_config.viewport.resolution = UVec2::new(config.width, config.height); + match self.runtime.block_on(export::execute_until_settled(executor, &self.graph_runtime, &self.spawner, render_config))? { + TaggedValue::RenderOutput(RenderOutput { + data: RenderOutputType::Texture(texture), + .. + }) => Some(texture), + other => return Err(format!("Expected a GPU texture, got: {other:?}").into()), + } + } + None => None, + }; + + let context = self.wgpu_executor().context(); + let surface_texture = match surface.get_current_texture(&context.queue) { + WgpuCurrentSurfaceTexture::Success(texture) | WgpuCurrentSurfaceTexture::Suboptimal(texture) => texture, + WgpuCurrentSurfaceTexture::Occluded => return Ok(()), + WgpuCurrentSurfaceTexture::Lost | WgpuCurrentSurfaceTexture::Outdated | WgpuCurrentSurfaceTexture::Timeout => { + surface.configure(&context.device, config); + window.request_redraw(); + return Ok(()); + } + other => return Err(format!("surface unavailable: {other:?}").into()), + }; + let target = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default()); + + let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("live view") }); + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("live view clear"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(BACKGROUND), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + occlusion_query_set: None, + timestamp_writes: None, + multiview_mask: None, + }); + if let Some(frame) = &frame { + let source = frame.create_view(&wgpu::TextureViewDescriptor::default()); + blitter.copy(&context.device, &mut encoder, &source, &target); + } + + surface_texture.queue.submit([encoder.finish()]); + window.pre_present_notify(); + surface_texture.present(); + Ok(()) + } +} + +impl ApplicationHandler for Viewer { + fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) { + let attributes = WindowAttributes::default() + .with_title(format!("Graphite live view {}", self.live.token())) + .with_surface_size(winit::dpi::LogicalSize::new(800, 600)); + let window: Arc = match event_loop.create_window(attributes) { + Ok(window) => window.into(), + Err(error) => { + log::error!("Failed to create the window: {error}"); + return self.quit(event_loop); + } + }; + if let Err(error) = self.create_surface(&window) { + log::error!("Failed to create the window surface: {error}"); + return self.quit(event_loop); + } + window.request_redraw(); + self.window = Some(window); + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + POLL_INTERVAL)); + } + + fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, _cause: StartCause) { + for event in self.runtime.block_on(self.live.poll()) { + self.dirty |= match event { + Event::Synced => { + log::info!("Synced with the session"); + true + } + Event::ResourceReceived { hash, bytes } => { + log::info!("Received resource {hash} ({} bytes)", bytes.len()); + true + } + Event::Changed => true, + _ => false, + }; + } + if self.dirty && self.live.is_synced() { + self.log_missing_resources(); + } + if self.dirty && self.live.is_ready() { + self.dirty = false; + self.recompile(); + if let Some(window) = &self.window { + window.request_redraw(); + } + } + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + POLL_INTERVAL)); + } + + fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) { + match event { + WindowEvent::CloseRequested => self.quit(event_loop), + WindowEvent::SurfaceResized(_) => { + self.resize(); + if let Some(window) = &self.window { + window.request_redraw(); + } + } + WindowEvent::RedrawRequested => { + if let Err(error) = self.draw() { + log::error!("Draw failed: {error}"); + } + } + _ => {} + } + } +} diff --git a/node-graph/interpreted-executor/Cargo.toml b/node-graph/interpreted-executor/Cargo.toml index fb198d7c9ee..bb4e3a4a745 100644 --- a/node-graph/interpreted-executor/Cargo.toml +++ b/node-graph/interpreted-executor/Cargo.toml @@ -40,7 +40,9 @@ serde = { workspace = true } graph-craft = { workspace = true, features = ["loading"] } criterion = { workspace = true } gungraun = { workspace = true } +document-loader = { workspace = true } preprocessor = { workspace = true } +wgpu = { workspace = true } # Benchmarks [[bench]] @@ -66,3 +68,8 @@ harness = false [[bench]] name = "run_cached_gungraun" harness = false + +[[bench]] +name = "brush_stroke_gungraun" +harness = false +required-features = ["gpu"] diff --git a/node-graph/interpreted-executor/benches/benchmark_util.rs b/node-graph/interpreted-executor/benches/benchmark_util.rs index ea6fdbd4f97..cb1d15736ed 100644 --- a/node-graph/interpreted-executor/benches/benchmark_util.rs +++ b/node-graph/interpreted-executor/benches/benchmark_util.rs @@ -1,16 +1,19 @@ use criterion::BenchmarkGroup; use criterion::measurement::Measurement; use graph_craft::proto::ProtoNetwork; -use graph_craft::util::{DEMO_ART, compile, load_from_name}; +use graph_craft::util::{DEMO_ART, compile}; use graphene_std::application_io::EditorApi; -use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task}; +use graphene_std::runtime::{AsyncRuntime, Spawn, Task}; use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::util::wrap_network_in_scope; +use std::path::Path; pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) { - let network = load_from_name(name); + let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite")))) + .unwrap() + .network; let editor_api = std::sync::Arc::new(EditorApi::default()); - let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle()); + let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle()); let preprocessor = preprocessor::Preprocessor::new(); preprocessor.preprocess(&mut network, &|_| None).unwrap(); let proto_network = compile(network); @@ -33,10 +36,3 @@ struct DummySpawner; impl Spawn for DummySpawner { fn spawn(&self, _task: Task) {} } - -struct NoClock; -impl Clock for NoClock { - fn now(&self) -> std::time::Duration { - std::time::Duration::ZERO - } -} diff --git a/node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs b/node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs new file mode 100644 index 00000000000..5b22f70a96d --- /dev/null +++ b/node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs @@ -0,0 +1,356 @@ +//! Counts the instructions a document update costs when one stroke is added to its brush layer, the way the Brush tool appends strokes: +//! wrapping and compiling the changed graph, updating the executor and rendering the viewport, as the editor's runtime does for each change. +//! Rendering the same document with an empty brush cache is measured alongside, showing how much of the earlier render the cache saves. +//! +//! The graph renders on a software Vulkan device (lavapipe), so CI runners without a GPU can measure it and the counts include the "GPU" work. + +use core_types::transform::{Footprint, RenderQuality}; +use glam::{DAffine2, DVec2, UVec2}; +use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; +use graph_craft::concrete; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; +use graph_craft::graphene_compiler::Compiler; +use graphene_std::application_io::RenderConfig; +use graphene_std::brush::basic_brush::{basic_brush, basic_brush_pipeline}; +use graphene_std::brush::{BrushCache, Channel, Stroke, brush_strokes}; +use graphene_std::graphic; +use graphene_std::runtime::{AsyncRuntime, Spawn, Task}; +use graphene_std::uuid::NodeId; +use graphene_std::{Color, Context}; +use gungraun::prelude::*; +use gungraun::{Callgrind, EntryPoint}; +use interpreted_executor::dynamic_executor::DynamicExecutor; +use interpreted_executor::util::wrap_network_in_scope; +use std::hint::black_box; +use std::sync::Arc; +use wgpu_executor::{WgpuContextBuilder, WgpuExecutor}; + +/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it. +const VIEWPORT: UVec2 = UVec2::new(960, 540); +/// Samples in the added stroke. +const STROKE_SAMPLES: usize = 128; +/// Samples in each stroke already in the document. +const DOCUMENT_STROKE_SAMPLES: usize = 48; +/// Distance between consecutive pointer samples, about what a quick drag moves between pointer events. +const SAMPLE_SPACING: f64 = 4.; +/// Strokes the Brush tool draws before its settings change. +const STROKES_PER_GROUP: usize = 8; + +pub struct Session { + gpu: WgpuExecutor, + editor_api: Arc, + runtime: AsyncRuntime, + preprocessor: preprocessor::Preprocessor, + executor: DynamicExecutor, + /// The document graph for the measured update. + document: NodeNetwork, +} + +impl Session { + /// Opens lavapipe and renders the finished document once through a brush cache that is then discarded, + /// so that the device's shaders are compiled and its textures allocated before anything is measured. + fn open(after: &[Group]) -> Self { + let gpu = lavapipe(); + let mut session = Self { + editor_api: Arc::new(PlatformEditorApi { + application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))), + }), + gpu, + runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)), + preprocessor: preprocessor::Preprocessor::new(), + executor: DynamicExecutor::default(), + document: NodeNetwork::default(), + }; + session.update(brush_layer(&BrushCache::default(), after)); + session + } + + /// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit. + fn update(&mut self, document: NodeNetwork) { + let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle()); + 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; + self.executor.update(proto_network).expect("Failed to update the executor"); + + let render_config = RenderConfig { + viewport: Footprint { + transform: DAffine2::IDENTITY, + resolution: VIEWPORT, + quality: RenderQuality::Full, + }, + scale: 1., + ..Default::default() + }; + let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context()); + assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}"); + // Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands + let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely()); + let _ = black_box(output); + } +} + +/// A document of `existing` strokes rendered once, so the added stroke meets the caches the editor would have. +fn setup_add_stroke(existing: usize) -> Session { + let (before, after) = document(existing); + let mut session = Session::open(&after); + + // The brush layer's cache lives in the graph, so it carries over between compilations like in the editor + let cache = BrushCache::default(); + session.update(brush_layer(&cache, &before)); + session.document = brush_layer(&cache, &after); + session +} + +/// The same document with the stroke already added, meeting an empty brush cache, as after reopening the document. +fn setup_render_layer(existing: usize) -> Session { + let (_, after) = document(existing); + let mut session = Session::open(&after); + session.document = brush_layer(&BrushCache::default(), &after); + session +} + +/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see. +fn lavapipe() -> WgpuExecutor { + let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build()) + .expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD"); + let info = context.adapter.get_info(); + assert_eq!( + info.device_type, + wgpu::DeviceType::Cpu, + "Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD", + info.name + ); + WgpuExecutor::with_context(context).expect("Failed to create the GPU executor") +} + +/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section. +struct BlockingSpawner; + +impl Spawn for BlockingSpawner { + fn spawn(&self, task: Task) { + futures::executor::block_on(task); + } +} + +/// The `Brush Strokes` settings of a group, as the Brush tool starts a new group whenever its settings change. +#[derive(Clone, Copy)] +struct Style { + color: Color, + diameter: f64, + hardness: f64, + flow: f64, +} + +/// Strokes drawn with the same settings, which the Brush tool keeps in one `Brush Strokes` group. +#[derive(Clone)] +struct Group { + style: Style, + strokes: Vec, +} + +/// The groups of a document of `existing` strokes before and after one more stroke is drawn on top of it, the same on every run. +/// The added stroke continues the top group, as drawing on with the same settings does. +/// The groups' colors go once around the color wheel, and their other settings vary a little around the Brush tool's defaults. +fn document(existing: usize) -> (Vec, Vec) { + let mut random = Random(existing as u64); + let count = existing.div_ceil(STROKES_PER_GROUP).max(1); + let mut before: Vec<_> = (0..count) + .map(|index| Group { + style: random.style(index as f32 / count as f32), + strokes: Vec::new(), + }) + .collect(); + for index in 0..existing { + before[index / STROKES_PER_GROUP].strokes.push(random.stroke(DOCUMENT_STROKE_SAMPLES)); + } + + let mut after = before.clone(); + after.last_mut().expect("A document has at least one group").strokes.push(random.stroke(STROKE_SAMPLES)); + (before, after) +} + +/// The `Basic Brush` node and the layer conversion after it, whose IDs stay put as groups are added. +const BRUSH_NODE: NodeId = NodeId(0); +const LAYER_NODE: NodeId = NodeId(1); + +/// A document holding just a brush layer with its `Brush Strokes` groups, +/// stacked with the nodes the `Merge` layer uses and ending in the conversion the brush layer applies to its content. +/// Each group keeps its node IDs as strokes are added, as in the editor. +fn brush_layer(cache: &BrushCache, groups: &[Group]) -> NodeNetwork { + let node = |implementation, inputs| DocumentNode { + inputs, + call_argument: concrete!(Context), + implementation: DocumentNodeImplementation::ProtoNode(implementation), + ..Default::default() + }; + // Each group's `Brush Strokes`, `Into Group` and `Extend` nodes, numbered after the layer's own + let id = |index: usize, part: u64| NodeId(10 + 3 * index as u64 + part); + + let mut nodes = Vec::new(); + let mut stack = None; + for (index, group) in groups.iter().enumerate() { + let strokes = node( + brush_strokes::IDENTIFIER, + vec![ + NodeInput::value(TaggedValue::Strokes(group.strokes.clone()), false), + NodeInput::value(TaggedValue::Color(group.style.color), false), + NodeInput::value(TaggedValue::Number(group.style.diameter), false), + NodeInput::value(TaggedValue::Number(group.style.hardness), false), + NodeInput::value(TaggedValue::Number(group.style.flow), false), + ], + ); + nodes.push((id(index, 0), strokes)); + nodes.push((id(index, 1), node(graphic::into_group::IDENTIFIER, vec![NodeInput::node(id(index, 0), 0)]))); + stack = Some(match stack { + None => id(index, 1), + Some(below) => { + nodes.push((id(index, 2), node(graphic::extend::IDENTIFIER, vec![NodeInput::node(below, 0), NodeInput::node(id(index, 1), 0)]))); + id(index, 2) + } + }); + } + + let stack = stack.expect("A brush layer has at least one group"); + let brush = node( + basic_brush::IDENTIFIER, + vec![ + NodeInput::node(stack, 0), + NodeInput::value(TaggedValue::BrushCache(cache.clone()), false), + NodeInput::scope(basic_brush_pipeline::IDENTIFIER), + ], + ); + nodes.push((BRUSH_NODE, brush)); + // The layer node takes its content through `Into Group` before merging it into the stack + nodes.push((LAYER_NODE, node(graphic::into_group::IDENTIFIER, vec![NodeInput::node(BRUSH_NODE, 0)]))); + + NodeNetwork { + exports: vec![NodeInput::node(LAYER_NODE, 0)], + nodes: nodes.into_iter().collect(), + ..Default::default() + } +} + +/// Wandering pen strokes and their settings from a fixed seed. +struct Random(u64); + +impl Random { + fn next(&mut self) -> f64 { + // SplitMix64 + self.0 = self.0.wrapping_add(0x9E3779B97F4A7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB); + ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64 + } + + /// A value in `center ± spread`. + fn around(&mut self, center: f64, spread: f64) -> f64 { + center + (self.next() * 2. - 1.) * spread + } + + fn style(&mut self, hue: f32) -> Style { + Style { + color: Color::from_hsva(hue, 0.7, 0.9, 1.), + diameter: self.around(24., 4.), + hardness: self.around(50., 10.), + flow: self.around(80., 10.), + } + } + + fn stroke(&mut self, samples: usize) -> Stroke { + let viewport = VIEWPORT.as_dvec2(); + let mut position = DVec2::new(self.next(), self.next()) * viewport; + let mut heading = self.next() * std::f64::consts::TAU; + let mut positions = Vec::with_capacity(samples); + let mut pressures = Vec::with_capacity(samples); + for index in 0..samples { + positions.push(position); + pressures.push((0.4 + 0.6 * (index as f64 / samples as f64 * std::f64::consts::PI).sin()) as f32); + heading += (self.next() - 0.5) * 0.6; + position = (position + DVec2::from_angle(heading) * SAMPLE_SPACING).clamp(DVec2::ZERO, viewport); + } + Stroke { + position: positions, + pressure: Channel::Samples(pressures), + seed: (self.next() * u32::MAX as f64) as u64, + ..Default::default() + } + } +} + +/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread. +/// Outside Valgrind these are a few no-op rotations. +mod callgrind { + /// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT` + const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4; + const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1; + + pub fn start() { + request(START_INSTRUMENTATION); + } + + pub fn stop() { + request(STOP_INSTRUMENTATION); + } + + /// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn). + #[cfg(target_arch = "x86_64")] + fn request(code: u64) { + let args = [code, 0, 0, 0, 0, 0]; + // SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx` + unsafe { + std::arch::asm!( + "rol rdi, 3", + "rol rdi, 13", + "rol rdi, 61", + "rol rdi, 51", + "xchg rbx, rbx", + in("rax") args.as_ptr(), + inout("rdx") 0_u64 => _, + out("rdi") _, + options(nostack), + ); + } + } + + #[cfg(not(target_arch = "x86_64"))] + fn request(_code: u64) { + panic!("This benchmark only knows how to reach Valgrind on x86-64"); + } +} + +#[library_benchmark] +#[benches::existing_strokes(args = [0, 16, 256], setup = setup_add_stroke)] +pub fn add_stroke(session: Session) -> Session { + measure(session) +} + +#[library_benchmark] +#[benches::existing_strokes(args = [0, 16, 256], setup = setup_render_layer)] +pub fn render_layer(session: Session) -> Session { + measure(session) +} + +fn measure(mut session: Session) -> Session { + let document = std::mem::take(&mut session.document); + callgrind::start(); + session.update(document); + callgrind::stop(); + + // Return the session so its teardown happens outside the measured section + session +} + +library_benchmark_group!(name = brush_stroke_group; benchmarks = add_stroke, render_layer); + +main!( + // Only what runs between `callgrind::start` and `callgrind::stop` is measured, on every thread, + // since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out + config = LibraryBenchmarkConfig::default() + .pass_through_env("VK_DRIVER_FILES") + // Rasterizing on the queue thread alone keeps the counts independent of the runner's core count + .env("LP_NUM_THREADS", "0") + .tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None)); + library_benchmark_groups = brush_stroke_group +); diff --git a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs index 048abcbda32..bad9e2c4242 100644 --- a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs +++ b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs @@ -2,12 +2,15 @@ use criterion::measurement::Measurement; use criterion::{BenchmarkGroup, Criterion, criterion_group, criterion_main}; use graph_craft::graphene_compiler::Executor; use graph_craft::proto::ProtoNetwork; -use graph_craft::util::{DEMO_ART, compile, load_from_name}; +use graph_craft::util::{DEMO_ART, compile}; use graphene_std::transform::Footprint; use interpreted_executor::dynamic_executor::DynamicExecutor; +use std::path::Path; fn update_executor(name: &str, c: &mut BenchmarkGroup) { - let network = load_from_name(name); + let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite")))) + .unwrap() + .network; let proto_network = compile(network); let empty = ProtoNetwork::default(); @@ -30,7 +33,9 @@ fn update_executor_demo(c: &mut Criterion) { } fn run_once(name: &str, c: &mut BenchmarkGroup) { - let network = load_from_name(name); + let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite")))) + .unwrap() + .network; let proto_network = compile(network); let executor = DynamicExecutor::new(proto_network).unwrap(); diff --git a/node-graph/interpreted-executor/src/dynamic_executor.rs b/node-graph/interpreted-executor/src/dynamic_executor.rs index 51a9131f9d4..68185553e9f 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor.rs @@ -113,11 +113,6 @@ impl DynamicExecutor { Ok(ResolvedDocumentNodeTypesDelta { add, remove }) } - /// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. - pub fn introspect(&self, node_path: &[NodeId]) -> Result, IntrospectError> { - self.tree.introspect(node_path) - } - pub fn input_type(&self) -> Option { self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone()) } @@ -311,13 +306,6 @@ impl BorrowTree { self.nodes.insert(id, (node, path, inputs)); } - /// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. - pub fn introspect(&self, node_path: &[NodeId]) -> Result, IntrospectError> { - let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; - let (node, _path, _) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; - node.node().serialize().ok_or(IntrospectError::NoData) - } - pub fn get(&self, id: NodeId) -> Option { self.nodes.get(&id).map(|(node, _, _)| node.clone() as SharedNodeContainer) } @@ -333,10 +321,19 @@ impl BorrowTree { self.context_features.get(&id).copied().unwrap_or_default() } + /// The node feeding an input of the proto node at this path, looking past the nodes wrapping it under the same path such as 'Memoize'. pub fn input_node(&self, node_path: &[NodeId], input_index: usize) -> Result { - let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; - let (_, _, inputs) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; - inputs.get(input_index).copied().ok_or(IntrospectError::NoData) + let (mut id, _) = *self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; + + loop { + let (_, _, inputs) = self.nodes.get(&id).ok_or(IntrospectError::ProtoNodeNotFound(id))?; + let wrapped = inputs.first().filter(|first| self.nodes.get(first).is_some_and(|(_, path, _)| **path == *node_path)); + + match wrapped { + Some(&wrapped) => id = wrapped, + None => return inputs.get(input_index).copied().ok_or(IntrospectError::NoData), + } + } } /// The context this node was last evaluated with in the graph. diff --git a/node-graph/interpreted-executor/src/layer_paths.rs b/node-graph/interpreted-executor/src/layer_paths.rs new file mode 100644 index 00000000000..931719a1d4b --- /dev/null +++ b/node-graph/interpreted-executor/src/layer_paths.rs @@ -0,0 +1,316 @@ +//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer. + +use crate::node_registry::NODE_REGISTRY; +use graph_craft::ProtoNodeIdentifier; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork}; +use graphene_std::NodeParameter; +use graphene_std::graphic::{extend, write_layer_path}; +use graphene_std::list::NodeIdPath; +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; + +/// What a layer adds to the document, which is what its thumbnail shows and what its path is written onto. +pub enum LayerContent { + /// What the Extend node the layer ends in is given to add, with the path of the network the node is in. + Added { network_path: Vec, extend: NodeId }, + /// Everything the layer outputs, from the node at this path. + Output(Vec), +} + +/// The content of the layer at this path, unless it's hidden or passes through what's below it and so has none of its own. +pub fn layer_content(layer_path: &[NodeId], network: &NodeNetwork) -> Option { + let output = network.output_source(layer_path, 0)?; + if !output.starts_with(layer_path) { + return None; + } + + let (node_id, network_path) = output.split_last()?; + let node = network.nested_network(network_path)?.nodes.get(node_id)?; + if node.implementation != DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) { + return Some(LayerContent::Output(output)); + } + + Some(LayerContent::Added { + network_path: network_path.to_vec(), + extend: *node_id, + }) +} + +impl LayerContent { + /// The path of the node producing the content once compiled. + pub fn source(&self, network: &NodeNetwork) -> Option> { + match self { + Self::Added { network_path, extend } => { + let added = network.nested_network(network_path)?.nodes.get(extend)?.inputs.get(extend::NewInput::INDEX)?; + network.input_source(network_path, added) + } + Self::Output(output) => Some(output.clone()), + } + } +} + +/// Puts a node after each layer's content that writes the layer's path onto it. +/// A layer has none if its content may be of a type that can't carry the path. +pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) { + let mut carries_layer_path = HashMap::new(); + + // O(layers * depth) + for layer_path in layer_paths { + let Some((layer, parent_path)) = layer_path.split_last() else { continue }; + let Some(content) = layer_content(layer_path, network) else { continue }; + + // An Extend node nested deeper than the layer may be in a network that other layers share. + // So the writer goes after the layer's output, and the Extend node only decides if the content can carry the path. + let content = match content { + LayerContent::Added { network_path, extend } if network_path.len() > layer_path.len() => LayerContent::Output([network_path.as_slice(), &[extend]].concat()), + content => content, + }; + + let Some(source) = content.source(network) else { continue }; + if !source_can_carry_layer_path(source, network, &mut carries_layer_path) { + continue; + } + + match content { + // The writer goes between the Extend node and what it's given to add, inside the layer or beside it if the layer is that node + LayerContent::Added { network_path, extend } => { + let writer = layer_path_writer_id(extend); + let layer_beside = if network_path.len() == layer_path.len() { Vec::new() } else { vec![*layer] }; + let Some(holder) = network_mut(network, &network_path) else { continue }; + let Some(added) = holder.nodes.get_mut(&extend).and_then(|node| node.inputs.get_mut(extend::NewInput::INDEX)) else { + continue; + }; + + // Every layer made from the same network shares the writer + if *added == NodeInput::node(writer, 0) { + continue; + } + + let content = std::mem::replace(added, NodeInput::node(writer, 0)); + holder.nodes.insert(writer, layer_path_writer(content, layer_beside)); + } + // The writer goes beside the layer, taking over everything its output feeds + LayerContent::Output(_) => { + let writer = layer_path_writer_id(*layer); + let Some(holder) = network_mut(network, parent_path) else { continue }; + if holder.nodes.contains_key(&writer) { + continue; + } + + let (output, written) = (NodeInput::node(*layer, 0), NodeInput::node(writer, 0)); + let inputs = holder.nodes.values_mut().flat_map(|node| &mut node.inputs).chain(&mut holder.exports); + inputs.filter(|input| **input == output).for_each(|input| *input = written.clone()); + + holder.nodes.insert(writer, layer_path_writer(output, vec![*layer])); + } + } + } +} + +/// How the layer path writer fares with what a proto node outputs. +#[derive(Clone, Copy)] +enum CarriesLayerPath { + Always, + /// The node outputs the type its one input is given, so that decides it. + AsItsInput, + Never, +} + +/// Whether the layer path writer can take everything the proto node at this path may output. +fn source_can_carry_layer_path(mut source: Vec, network: &NodeNetwork, carries_layer_path: &mut HashMap) -> bool { + loop { + let Some((node_id, network_path)) = source.split_last() else { return false }; + let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else { + return false; + }; + let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false }; + + match *carries_layer_path.entry(identifier.clone()).or_insert_with(|| output_can_carry_layer_path(identifier)) { + CarriesLayerPath::Always => return true, + CarriesLayerPath::Never => return false, + CarriesLayerPath::AsItsInput => { + let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else { + return false; + }; + source = input_source; + } + } + } +} + +fn output_can_carry_layer_path(identifier: &ProtoNodeIdentifier) -> CarriesLayerPath { + let (Some(outputs), Some(writers)) = (NODE_REGISTRY.get(identifier), NODE_REGISTRY.get(&write_layer_path::IDENTIFIER)) else { + return CarriesLayerPath::Never; + }; + + let writes_type = |output: &graph_craft::Type| { + let content = |writer: &graphene_std::NodeIOTypes| writer.inputs.get(write_layer_path::ContentInput::INDEX).is_some_and(|content| content.nested_type() == output); + writers.keys().any(content) + }; + if outputs.keys().all(|output| writes_type(output.return_value.nested_type())) { + return CarriesLayerPath::Always; + } + + let as_its_input = |output: &graphene_std::NodeIOTypes| matches!(output.inputs.as_slice(), [input] if input.nested_type() == output.return_value.nested_type()); + if outputs.keys().all(as_its_input) { + CarriesLayerPath::AsItsInput + } else { + CarriesLayerPath::Never + } +} + +/// The network at this path, which is either an entry of the definitions table or held by its node. +fn network_mut<'a>(network: &'a mut NodeNetwork, path: &[NodeId]) -> Option<&'a mut NodeNetwork> { + // The last table entry along the path, which holds any networks after it + let mut table_entry = None; + let mut current = &*network; + for (index, node_id) in path.iter().enumerate() { + current = match ¤t.nodes.get(node_id)?.implementation { + DocumentNodeImplementation::Definition(id) => { + table_entry = Some((*id, index + 1)); + network.definitions.get(id)? + } + DocumentNodeImplementation::Network(held) => held, + _ => return None, + }; + } + + let (mut current, held_path) = match table_entry { + Some((id, held_from)) => (network.definitions.get_mut(&id)?, &path[held_from..]), + None => (network, path), + }; + for node_id in held_path { + let DocumentNodeImplementation::Network(held) = &mut current.nodes.get_mut(node_id)?.implementation else { + return None; + }; + current = held; + } + + Some(current) +} + +/// The ID of the node writing the layer path onto what the node with this ID outputs or is given, which stays the same between compilations. +pub fn layer_path_writer_id(node_id: NodeId) -> NodeId { + let mut hasher = DefaultHasher::new(); + "layer path writer".hash(&mut hasher); + node_id.hash(&mut hasher); + NodeId(hasher.finish()) +} + +fn layer_path_writer(content: NodeInput, layer_beside: Vec) -> DocumentNode { + DocumentNode { + inputs: vec![ + content, + // The writer is directly inside the layer or beside it, so removing only its own ID gives the path + NodeInput::value(TaggedValue::Integer(1), false), + NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false), + NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath), + ], + implementation: DocumentNodeImplementation::ProtoNode(write_layer_path::IDENTIFIER), + ..Default::default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use graph_craft::document::NetworkId; + + #[test] + fn content_that_cannot_carry_a_layer_path_is_left_alone() { + let path_node = DocumentNode { + inputs: vec![NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath)], + implementation: DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER), + ..Default::default() + }; + let mut network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0)], + nodes: [(NodeId(1), path_node)].into_iter().collect(), + ..Default::default() + }; + let unchanged = network.clone(); + + write_layer_paths(&mut network, &[vec![NodeId(1)]]); + + assert_eq!(network, unchanged); + } + + fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec) -> DocumentNode { + DocumentNode { + inputs, + implementation: DocumentNodeImplementation::ProtoNode(identifier), + ..Default::default() + } + } + + fn definition_node(id: NetworkId) -> DocumentNode { + DocumentNode { + implementation: DocumentNodeImplementation::Definition(id), + ..Default::default() + } + } + + /// A network shaped like 'Merge', where an Extend node adds what the node beside it gives. + fn merge_like(added: DocumentNode) -> NodeNetwork { + let extend = proto_node(extend::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(2), 0)]); + NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0)], + nodes: [(NodeId(1), extend), (NodeId(2), added)].into_iter().collect(), + ..Default::default() + } + } + + // One network is shared by a layer at the root and by a layer inside another layer, so the one writer inside it has to suit both + #[test] + fn a_network_shared_by_layers_at_different_depths_writes_each_layer_path() { + let (merge, group) = (NetworkId(1), NetworkId(2)); + let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new()); + let group_network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(30), 0)], + nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(), + ..Default::default() + }; + let network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(group))].into_iter().collect(), + definitions: [(merge, merge_like(rectangle)), (group, group_network)].into_iter().collect(), + ..Default::default() + }; + + // The outer layer comes first in one order and last in the other + let orders = [ + [vec![NodeId(20)], vec![NodeId(10)], vec![NodeId(20), NodeId(30)]], + [vec![NodeId(10)], vec![NodeId(20), NodeId(30)], vec![NodeId(20)]], + ]; + let written = orders.map(|layer_paths| { + let mut network = network.clone(); + write_layer_paths(&mut network, &layer_paths); + network + }); + assert_eq!(written[0], written[1], "The order the layers are given in should not change what's written"); + + // The writer writes the path of the layer holding its network, whichever layer that is + let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))]; + let (levels_up, layer_beside) = (writer.input(write_layer_path::LevelsUpInput), writer.input(write_layer_path::LayerBesideInput)); + assert_eq!(levels_up, Some(&NodeInput::value(TaggedValue::Integer(1), false))); + assert_eq!(layer_beside, Some(&NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false))); + } + + // Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer + #[test] + fn a_network_writing_its_own_layer_path_is_left_alone() { + let write_attribute = proto_node(graphene_std::graphic::write_attribute::IDENTIFIER, Vec::new()); + let mut network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: [(NodeId(10), definition_node(NetworkId(1)))].into_iter().collect(), + definitions: [(NetworkId(1), merge_like(write_attribute))].into_iter().collect(), + ..Default::default() + }; + let unchanged = network.clone(); + + write_layer_paths(&mut network, &[vec![NodeId(10)]]); + + assert_eq!(network, unchanged); + } +} diff --git a/node-graph/interpreted-executor/src/lib.rs b/node-graph/interpreted-executor/src/lib.rs index 6b59d5ad987..050d8d3a55c 100644 --- a/node-graph/interpreted-executor/src/lib.rs +++ b/node-graph/interpreted-executor/src/lib.rs @@ -2,6 +2,7 @@ #![recursion_limit = "256"] pub mod dynamic_executor; +pub mod layer_paths; pub mod node_registry; pub mod util; diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index fc49f8a8c53..f65d160d2b3 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::document::value::RenderOutput; use graph_craft::proto::{NodeConstructor, TypeErasedBox}; use graphene_animation::AnimationCurve; +use graphene_std::GlowTechnique; use graphene_std::animation::RealTimeMode; use graphene_std::any::DynAnyNode; use graphene_std::brush::Stroke; @@ -34,50 +35,6 @@ use std::sync::Arc; // TODO: turn into hashmap fn node_registry() -> HashMap> { let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ - // ============= - // MONITOR NODES - // ============= - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List>]), - #[cfg(feature = "gpu")] - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List>]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item>]), - #[cfg(feature = "gpu")] - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item>]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]), - async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List]), // Context nullification #[cfg(feature = "gpu")] async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item>, Context => Item]), @@ -298,8 +255,8 @@ fn node_registry() -> HashMap { $register!( @@ -329,6 +286,7 @@ fn node_registry() -> HashMap HashMap HashMap)); - // The memoize + monitor + context-nullification triple for each value type in the shared list above: the compiler wraps - // a ranked connector's broadcast sibling in a Memoize + context-nullification pair, and test instrumentation monitors any wire. + // The memoize + context-nullification pair the compiler wraps a ranked connector's broadcast sibling in, for each value type in the shared list above. // Node identifiers are passed explicitly since `stringify!` would mangle the path's whitespace through this nested macro. macro_rules! cache_chain_nodes { (each: $value:ty) => {{ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]), - async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]), async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item]), ]; entries @@ -549,6 +505,7 @@ fn node_registry() -> HashMap>), attribute_value_node!(List), + attribute_value_node!(List), ]; node_types.extend(attribute_value_rows); // Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item @@ -607,7 +564,7 @@ fn node_registry() -> HashMap) or similar -pub static NODE_REGISTRY: once_cell::sync::Lazy>> = once_cell::sync::Lazy::new(|| node_registry()); +pub static NODE_REGISTRY: once_cell::sync::Lazy>> = once_cell::sync::Lazy::new(node_registry); mod node_registry_macros { macro_rules! async_node { diff --git a/node-graph/interpreted-executor/src/util.rs b/node-graph/interpreted-executor/src/util.rs index 420ba4a0848..afac28c095d 100644 --- a/node-graph/interpreted-executor/src/util.rs +++ b/node-graph/interpreted-executor/src/util.rs @@ -42,7 +42,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc>); impl CanvasHandle { pub fn new() -> Self { @@ -75,6 +75,7 @@ pub async fn create_wgpu_executor() -> Option { } #[cfg(feature = "wgpu")] +#[derive(Default)] pub struct CanvasSurfaceHandle { canvas: CanvasHandle, surface: Option>, @@ -181,7 +182,7 @@ impl CanvasImpl { let image_canvases_key = JsValue::from_str(CANVASES_OBJECT_KEY); let mut canvases = Reflect::get(&window_obj, &image_canvases_key); - if canvases.is_err() || canvases.as_ref().map_or(false, |v| v.is_undefined() || v.is_null()) { + if canvases.is_err() || canvases.as_ref().is_ok_and(|v| v.is_undefined() || v.is_null()) { Reflect::set(&window_obj.clone(), &image_canvases_key, &Object::new()).unwrap(); canvases = Reflect::get(&window_obj, &image_canvases_key); } diff --git a/node-graph/libraries/core-types/Cargo.toml b/node-graph/libraries/core-types/Cargo.toml index 0697f399c40..c0b1ef71fb7 100644 --- a/node-graph/libraries/core-types/Cargo.toml +++ b/node-graph/libraries/core-types/Cargo.toml @@ -52,6 +52,7 @@ log = { workspace = true } base64 = { workspace = true } polycool = { workspace = true } futures = { workspace = true } +web-time = { workspace = true } # Optional workspace dependencies serde = { workspace = true, optional = true } diff --git a/node-graph/libraries/core-types/src/color/color_types.rs b/node-graph/libraries/core-types/src/color/color_types.rs index a01f6e1f752..aa8f6ba263b 100644 --- a/node-graph/libraries/core-types/src/color/color_types.rs +++ b/node-graph/libraries/core-types/src/color/color_types.rs @@ -81,7 +81,7 @@ impl Pixel for RGBA16F {} /// bijective with hex codes, byte-identical to CSS/SVG/PNG/peniko conventions. Internal computations use /// the linear-light [`Color`] type. Convert via [`From for Color`] and [`From for SRGBA8`]. #[repr(C)] -#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SRGBA8 { @@ -697,9 +697,9 @@ impl Color { /// Per-channel "Vivid Light" blend. pub fn blend_vivid_light(c_b: f32, c_s: f32) -> f32 { if c_s <= 0.5 { - Color::blend_color_burn(2. * c_s, c_b) + Color::blend_color_burn(c_b, 2. * c_s) } else { - Color::blend_color_dodge(2. * c_s - 1., c_b) + Color::blend_color_dodge(c_b, 2. * c_s - 1.) } } @@ -1016,6 +1016,18 @@ impl Color { mod tests { use super::*; + #[test] + fn vivid_light_burns_and_dodges_the_backdrop_by_the_doubled_source() { + // The darker half is Color Burn of the backdrop by twice the source: 1 - (1 - 0.8) / 0.5 + assert!((Color::blend_vivid_light(0.8, 0.25) - 0.6).abs() < 1e-6); + // The lighter half is Color Dodge of the backdrop by twice the source less one: 0.4 / (1 - 0.5) + assert!((Color::blend_vivid_light(0.4, 0.75) - 0.8).abs() < 1e-6); + // A mid-gray source leaves the backdrop unchanged, and the extremes saturate + assert!((Color::blend_vivid_light(0.3, 0.5) - 0.3).abs() < 1e-6); + assert_eq!(Color::blend_vivid_light(0.3, 0.), 0.); + assert_eq!(Color::blend_vivid_light(0.3, 1.), 1.); + } + #[test] fn oklab_lightness_spans_black_to_white() { assert!(Color::BLACK.lightness_oklab().abs() < 1e-4); diff --git a/node-graph/libraries/core-types/src/lib.rs b/node-graph/libraries/core-types/src/lib.rs index e8531118d6c..f9e93aa84a3 100644 --- a/node-graph/libraries/core-types/src/lib.rs +++ b/node-graph/libraries/core-types/src/lib.rs @@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations; pub use graphene_hash; pub use graphene_hash::CacheHash; 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_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_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_TYPE, + 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_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_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_TYPE, }; pub use memo::MemoHash; pub use num_traits; @@ -55,11 +56,6 @@ pub trait Node { fn node_name(&self) -> &'static str { std::any::type_name::() } - /// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes. - fn serialize(&self) -> Option> { - log::warn!("Node::serialize not implemented for {}", std::any::type_name::()); - None - } } mod types; @@ -107,9 +103,6 @@ impl + ?Sized> Node for &N { fn node_name(&self) -> &'static str { (**self).node_name() } - fn serialize(&self) -> Option> { - (**self).serialize() - } } impl + ?Sized> Node for Box { type Output = N::Output; @@ -120,9 +113,6 @@ impl + ?Sized> Node for Box { fn node_name(&self) -> &'static str { (**self).node_name() } - fn serialize(&self) -> Option> { - (**self).serialize() - } } impl + ?Sized> Node for std::sync::Arc { type Output = N::Output; @@ -133,9 +123,6 @@ impl + ?Sized> Node for std::sync::Arc { fn node_name(&self) -> &'static str { (**self).node_name() } - fn serialize(&self) -> Option> { - (**self).serialize() - } } /// A compile-time symbol naming one parameter of one proto node. diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 1c75ea823ad..510df7f96d0 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -80,6 +80,9 @@ pub const ATTR_POSITION: &str = "position"; pub const ATTR_MIDPOINT: &str = "midpoint"; /// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones. pub const ATTR_APPEARANCE: &str = "appearance"; +/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to. +/// Unlike the appearance, it doesn't cascade to descendants. +pub const ATTR_EFFECTS: &str = "effects"; // TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships /// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the /// `List` inside an `Appearance`. @@ -124,6 +127,21 @@ pub const ATTR_SMOOTH: &str = "smooth"; /// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List` /// inside a `Path` at the anchor reference the segment departs from. pub const ATTR_ID: &str = "id"; +/// Point's `i64` count of the `[` branches the turtle was nested in when drawing it, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_DEPTH: &str = "depth"; +/// Point's `f64` distance the turtle traveled from its start to reach it, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_DISTANCE: &str = "distance"; +/// Point's `f64` direction in degrees the turtle faced arriving at it (`0.` along +X, clockwise on screen), on a `Vector`'s +/// point pool from Turtle Path. +pub const ATTR_HEADING: &str = "heading"; +/// Point's `f64` width the turtle drew with there, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_WIDTH: &str = "width"; +/// Point's `DVec2` U and V numbers, counted up by `'` and `#`, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_UV: &str = "uv"; +/// Point's `f64` turtle step length, scaled by `"` and `_`, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_STEP: &str = "step"; +/// Point's `i64` kind set by a `.` outside a shape (default `1`), or `0` for a drawn point, on a `Vector`'s point pool from Turtle Path. +pub const ATTR_KIND: &str = "kind"; /// Text item's font size in document-space units (`f64`, implicit default `24.`). pub const ATTR_FONT_SIZE: &str = "font_size"; /// Text item's font, as a `Resource` of the loaded font file. diff --git a/node-graph/libraries/core-types/src/math/midpoint.rs b/node-graph/libraries/core-types/src/math/midpoint.rs new file mode 100644 index 00000000000..45c7f4fffe9 --- /dev/null +++ b/node-graph/libraries/core-types/src/math/midpoint.rs @@ -0,0 +1,78 @@ +/// The effective midpoint domain: NaN reads as the linear default, and extremes are bounded to `0.01..=0.99` so curves stay finite and cheap to subdivide. +pub fn sanitized_midpoint(midpoint: f64) -> f64 { + if midpoint.is_nan() { 0.5 } else { midpoint.clamp(0.01, 0.99) } +} + +/// Apply the midpoint curve to a normalized parameter `t` (0 to 1) given a `midpoint` (0 to 1, where 0.5 is linear). +pub fn apply_midpoint(t: f64, midpoint: f64) -> f64 { + let midpoint = sanitized_midpoint(midpoint); + if (midpoint - 0.5).abs() < 1e-6 { + return t; + } + + if midpoint < 0.5 { + let q = -1. / (1. - midpoint).log2(); + 1. - (1. - t).powf(q) + } else { + let p = -1. / midpoint.log2(); + t.powf(p) + } +} + +/// The inverse of [`apply_midpoint`], which lands a halfway parameter (0.5) at the midpoint. +/// Applied to uniformly distributed values, this makes the midpoint their median. +pub fn apply_midpoint_inverse(t: f64, midpoint: f64) -> f64 { + let midpoint = sanitized_midpoint(midpoint); + if (midpoint - 0.5).abs() < 1e-6 { + return t; + } + + if midpoint < 0.5 { 1. - (1. - t).powf(-(1. - midpoint).log2()) } else { t.powf(-midpoint.log2()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MIDPOINTS: [f64; 7] = [0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99]; + + #[test] + fn inverse_undoes_the_curve() { + for midpoint in MIDPOINTS { + for step in 0..=20 { + let t = step as f64 / 20.; + let round_trip = apply_midpoint(apply_midpoint_inverse(t, midpoint), midpoint); + assert!((round_trip - t).abs() < 1e-9, "midpoint {midpoint} took {t} to {round_trip}"); + } + } + } + + #[test] + fn inverse_lands_halfway_at_the_midpoint() { + for midpoint in MIDPOINTS { + assert!((apply_midpoint_inverse(0.5, midpoint) - midpoint).abs() < 1e-9); + assert!((apply_midpoint(midpoint, midpoint) - 0.5).abs() < 1e-9); + } + } + + #[test] + fn opposite_midpoints_mirror_each_other() { + for midpoint in MIDPOINTS { + for step in 0..=20 { + let t = step as f64 / 20.; + let mirrored = 1. - apply_midpoint_inverse(1. - t, 1. - midpoint); + assert!((apply_midpoint_inverse(t, midpoint) - mirrored).abs() < 1e-9); + } + } + } + + #[test] + fn curves_keep_their_endpoints() { + for midpoint in [0., 0.25, 0.5, 0.75, 1., f64::NAN] { + for curve in [apply_midpoint, apply_midpoint_inverse] { + assert_eq!(curve(0., midpoint), 0.); + assert_eq!(curve(1., midpoint), 1.); + } + } + } +} diff --git a/node-graph/libraries/core-types/src/math/mod.rs b/node-graph/libraries/core-types/src/math/mod.rs index bf8af5a78ad..0bafaa76258 100644 --- a/node-graph/libraries/core-types/src/math/mod.rs +++ b/node-graph/libraries/core-types/src/math/mod.rs @@ -1,5 +1,7 @@ pub mod bbox; pub mod float_noise; +pub mod midpoint; pub mod polynomial; pub mod quad; pub mod rect; +pub mod spread; diff --git a/node-graph/libraries/core-types/src/math/spread.rs b/node-graph/libraries/core-types/src/math/spread.rs new file mode 100644 index 00000000000..8a98513172e --- /dev/null +++ b/node-graph/libraries/core-types/src/math/spread.rs @@ -0,0 +1,45 @@ +use rand::{RngExt, SeedableRng}; + +/// Gives each of `count` items a factor from 0 to 1, either spread evenly in item order or drawn at random from the `seed`. +/// The even spread restarts after every `repeat_every` items, unless it is 0 to span all the items once. +pub fn spread_factors(count: usize, randomize: bool, seed: u64, repeat_every: u64) -> impl Iterator { + let mut rng = rand::rngs::StdRng::seed_from_u64(seed); + + (0..count).map(move |index| match (randomize, repeat_every) { + (true, _) => rng.random::(), + (false, 0) => index as f64 / count.saturating_sub(1).max(1) as f64, + (false, 1) => 0., + (false, _) => (index as u64 % repeat_every) as f64 / (repeat_every - 1) as f64, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn even_spread_spans_the_range_once() { + let factors: Vec = spread_factors(5, false, 0, 0).collect(); + assert_eq!(factors, [0., 0.25, 0.5, 0.75, 1.]); + + assert_eq!(spread_factors(1, false, 0, 0).collect::>(), [0.]); + assert_eq!(spread_factors(0, false, 0, 0).count(), 0); + } + + #[test] + fn even_spread_repeats() { + let factors: Vec = spread_factors(7, false, 0, 3).collect(); + assert_eq!(factors, [0., 0.5, 1., 0., 0.5, 1., 0.]); + + assert!(spread_factors(4, false, 0, 1).all(|factor| factor == 0.)); + } + + #[test] + fn random_spread_follows_the_seed() { + let draws = |seed| spread_factors(8, true, seed, 0).collect::>(); + + assert_eq!(draws(42), draws(42)); + assert_ne!(draws(42), draws(43)); + assert!(draws(42).iter().all(|factor| (0. ..1.).contains(factor))); + } +} diff --git a/node-graph/libraries/core-types/src/memo.rs b/node-graph/libraries/core-types/src/memo.rs index 80766fc860b..64cff1a1242 100644 --- a/node-graph/libraries/core-types/src/memo.rs +++ b/node-graph/libraries/core-types/src/memo.rs @@ -4,13 +4,6 @@ use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::sync::Arc; -/// Stores both what a node was called with and what it returned. -#[derive(Clone, Debug)] -pub struct IORecord { - pub input: I, - pub output: O, -} - #[derive(Clone, Debug)] pub struct MemoHash { hash: u64, diff --git a/node-graph/libraries/core-types/src/ops.rs b/node-graph/libraries/core-types/src/ops.rs index f5c06e7febc..525a03b514d 100644 --- a/node-graph/libraries/core-types/src/ops.rs +++ b/node-graph/libraries/core-types/src/ops.rs @@ -17,10 +17,6 @@ where fn eval(&self, input: &I) -> Poll { self.0.eval(input) } - - fn serialize(&self) -> Option> { - self.0.serialize() - } } impl, I> TypeNode>::Output> { pub fn new(node: N) -> Self { @@ -44,7 +40,6 @@ pub trait Convert: Sized { /// Asynchronous version of [`Convert`] pub trait ConvertAsync: Sized { - #[must_use] fn convert(self, footprint: Footprint, converter: C) -> impl std::future::Future + Send + 'static; } diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index 0858d6c0d41..6413e878627 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -76,6 +76,7 @@ pub enum RegistryValueSource { Default(&'static str), Scope(&'static str), SourceId, + NodePath, } #[derive(Clone, Debug)] @@ -350,10 +351,6 @@ where .unwrap_or_else(|_| panic!("DowncastBothNode wrong output type: expected {} in: \n{}", std::any::type_name::(), self.node.node().node_name())) }) } - - fn serialize(&self) -> Option> { - self.node.node().serialize() - } } impl DowncastBothNode { pub const fn new(node: SharedNodeContainer) -> Self { @@ -385,10 +382,6 @@ where .unwrap_or_else(|| panic!("DynAnyNode Input: expected {} in:\n{}", std::any::type_name::(), std::any::type_name::())); self.node.eval(input).map(|output| Box::new(output) as Any) } - - fn serialize(&self) -> Option> { - self.node.serialize() - } } impl DynAnyNode { pub const fn new(node: N) -> Self { diff --git a/node-graph/libraries/core-types/src/runtime.rs b/node-graph/libraries/core-types/src/runtime.rs index 3f5e8b40a2c..c0dcd9b624d 100644 --- a/node-graph/libraries/core-types/src/runtime.rs +++ b/node-graph/libraries/core-types/src/runtime.rs @@ -1,16 +1,14 @@ use crate::poll::Poll; use crate::uuid::NodeId; use dyn_any::WasmNotSend; -pub use futures::future::AbortHandle; -use futures::future::Abortable; +use futures::future::{AbortHandle, Abortable}; use std::collections::HashMap; use std::future::Future; use std::hash::{Hash, Hasher}; use std::pin::Pin; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::task::{Context, Waker}; -use std::time::Duration; +pub use web_time::Instant; #[cfg(not(target_family = "wasm"))] pub type Task = Pin + Send + 'static>>; @@ -21,36 +19,6 @@ pub trait Spawn { fn spawn(&self, task: Task); } -/// Monotonic time since an arbitrary origin. -pub trait Clock: Send + Sync { - fn now(&self) -> Duration; -} - -#[cfg(not(target_family = "wasm"))] -impl Clock for std::time::Instant { - fn now(&self) -> Duration { - self.elapsed() - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Scheduling { - /// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it. - pub frame_budget: Option, -} - -impl Scheduling { - pub const UNLIMITED: Self = Self { frame_budget: None }; -} - -impl Default for Scheduling { - fn default() -> Self { - Self { - frame_budget: Some(Duration::from_millis(16)), - } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)] pub struct SourceId(pub u64); @@ -66,22 +34,15 @@ impl SourceId { pub type Generations = Arc<[(SourceId, u64)]>; pub trait Runtime { - /// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first. - fn spawn(&self, source: SourceId, task: Task) -> AbortHandle; + fn spawn(&self, source: SourceId, task: Task); } #[derive(Clone, dyn_any::DynAny)] pub struct RuntimeHandle(Arc); -impl RuntimeHandle { - pub fn clock(&self) -> &dyn Clock { - &*self.0.clock - } -} - impl Runtime for RuntimeHandle { - fn spawn(&self, source: SourceId, task: Task) -> AbortHandle { - self.0.spawn(source, task) + fn spawn(&self, source: SourceId, task: Task) { + self.0.spawn(source, task); } } @@ -104,43 +65,28 @@ impl graphene_hash::CacheHash for RuntimeHandle { pub struct AsyncRuntime(Arc); impl AsyncRuntime { - pub fn new(spawner: Arc, clock: Arc) -> Self { + pub fn new(spawner: Arc) -> Self { Self(Arc::new(RuntimeInner { - sources: Mutex::default(), - next_task: AtomicU64::new(0), - bumped: AtomicBool::new(false), + generations: Mutex::default(), spawner, - clock, })) } - /// Aborts the unfinished tasks of removed sources. - pub fn retain_sources(&self, live: &[SourceId]) { - let mut sources = self.0.lock(); - for (_, state) in sources.extract_if(|source, _| !live.contains(source)) { - state.tasks.values().for_each(AbortHandle::abort); - } + pub fn update_sources(&self, live: &[SourceId]) { + let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner); + generations.retain(|source, _| live.contains(source)); for source in live { - sources.entry(*source).or_default(); + generations.entry(*source).or_insert(0); } } pub fn snapshot(&self) -> Generations { - let sources = self.0.lock(); - let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect(); + let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner); + let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect(); snapshot.sort_unstable(); snapshot.into() } - /// Whether any generation was bumped since the last call. - pub fn take_bumped(&self) -> bool { - self.0.bumped.swap(false, Ordering::AcqRel) - } - - pub fn clock(&self) -> &dyn Clock { - &*self.0.clock - } - #[must_use] pub fn handle(&self) -> RuntimeHandle { RuntimeHandle(Arc::clone(&self.0)) @@ -148,50 +94,25 @@ impl AsyncRuntime { } impl Runtime for AsyncRuntime { - fn spawn(&self, source: SourceId, task: Task) -> AbortHandle { - self.0.spawn(source, task) + fn spawn(&self, source: SourceId, task: Task) { + self.0.spawn(source, task); } } -/// A live source's generation and its unfinished tasks. -#[derive(Default)] -struct SourceState { - generation: u64, - tasks: HashMap, -} - struct RuntimeInner { - sources: Mutex>, - next_task: AtomicU64, - bumped: AtomicBool, + generations: Mutex>, spawner: Arc, - clock: Arc, } impl RuntimeInner { - fn lock(&self) -> MutexGuard<'_, HashMap> { - self.sources.lock().unwrap_or_else(PoisonError::into_inner) - } - - fn spawn(self: &Arc, source: SourceId, task: Task) -> AbortHandle { - let (handle, registration) = AbortHandle::new_pair(); - let id = self.next_task.fetch_add(1, Ordering::Relaxed); - if let Some(state) = self.lock().get_mut(&source) { - state.tasks.insert(id, handle.clone()); - } - + fn spawn(self: &Arc, source: SourceId, task: Task) { let inner = Arc::clone(self); self.spawner.spawn(Box::pin(async move { - let finished = Abortable::new(task, registration).await.is_ok(); - if let Some(state) = inner.lock().get_mut(&source) - && state.tasks.remove(&id).is_some() - && finished - { - state.generation += 1; - inner.bumped.store(true, Ordering::Release); + task.await; + if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) { + *generation += 1; } })); - handle } } @@ -247,12 +168,14 @@ impl Slots { return state; } + let (handle, registration) = AbortHandle::new_pair(); let slots = Arc::downgrade(&self.0); - let handle = runtime.spawn( + runtime.spawn( source, Box::pin(async move { - let state = future.await; - if let Some(slots) = slots.upgrade() { + if let Ok(state) = Abortable::new(future, registration).await + && let Some(slots) = slots.upgrade() + { slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state)); } }), @@ -271,14 +194,7 @@ impl Slots { #[cfg(test)] mod tests { use super::*; - - struct NoClock; - - impl Clock for NoClock { - fn now(&self) -> Duration { - Duration::ZERO - } - } + use std::sync::atomic::{AtomicBool, Ordering}; fn poll_once(task: &mut Task) -> bool { task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready() @@ -331,8 +247,8 @@ mod tests { #[test] fn a_completion_bumps_its_generation() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.update_sources(&[SOURCE]); runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false))); assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); @@ -342,25 +258,25 @@ mod tests { } #[test] - fn retaining_sources_keeps_live_generations() { + fn updating_sources_keeps_live_generations() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.update_sources(&[SOURCE]); runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); spawner.drain(); - runtime.retain_sources(&[SOURCE, SourceId(9)]); + runtime.update_sources(&[SOURCE, SourceId(9)]); assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1), (SourceId(9), 0)]); - runtime.retain_sources(&[SourceId(9)]); + runtime.update_sources(&[SourceId(9)]); assert_eq!(&*runtime.snapshot(), &[(SourceId(9), 0)]); } #[test] fn an_inline_completion_and_a_dropped_source_bump_nothing() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.update_sources(&[SOURCE]); let slots = Slots::default(); assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1)); @@ -368,7 +284,7 @@ mod tests { assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); - runtime.retain_sources(&[]); + runtime.update_sources(&[]); assert_eq!(spawner.drain(), 1); assert!(runtime.snapshot().is_empty()); } @@ -376,8 +292,8 @@ mod tests { #[test] fn a_slot_serves_the_placeholder_until_the_response_lands() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.update_sources(&[SOURCE]); let slots = Slots::default(); let fetch = || async { YieldOnce(false).await; @@ -393,8 +309,8 @@ mod tests { #[test] fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() { - let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner)); + runtime.update_sources(&[SOURCE]); let slots = Slots::default(); let fetch = || async { YieldOnce(false).await; @@ -408,7 +324,7 @@ mod tests { #[test] fn a_clone_keeps_the_task_running() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); + let runtime = AsyncRuntime::new(spawner.clone()); let slots = Slots::default(); let fetch = || async { YieldOnce(false).await; @@ -425,7 +341,7 @@ mod tests { #[test] fn dropping_the_last_clone_aborts_the_task() { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); + let runtime = AsyncRuntime::new(spawner.clone()); let slots = Slots::default(); let finished = Arc::new(AtomicBool::new(false)); let fetch = || { @@ -442,32 +358,4 @@ mod tests { assert_eq!(spawner.drain(), 1); assert!(!finished.load(Ordering::Relaxed)); } - - #[test] - fn finished_tasks_bump_once() { - let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE]); - runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); - runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); - - assert_eq!(spawner.drain(), 2); - assert!(runtime.take_bumped()); - assert!(!runtime.take_bumped()); - } - - #[test] - fn aborted_tasks_bump_nothing() { - let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock)); - runtime.retain_sources(&[SOURCE, SourceId(9)]); - runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort(); - let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending())); - runtime.retain_sources(&[SOURCE]); - - assert!(removed.is_aborted()); - assert_eq!(spawner.drain(), 2); - assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); - assert!(!runtime.take_bumped()); - } } diff --git a/node-graph/libraries/core-types/src/transform.rs b/node-graph/libraries/core-types/src/transform.rs index 5ccf50f8643..9f121951c21 100644 --- a/node-graph/libraries/core-types/src/transform.rs +++ b/node-graph/libraries/core-types/src/transform.rs @@ -188,6 +188,14 @@ impl Footprint { quality: RenderQuality::Full, }; + pub fn from_bounds(bounds: [DVec2; 2], quality: RenderQuality) -> Self { + Footprint { + transform: DAffine2::from_translation(bounds[0].min(bounds[1])), + resolution: (bounds[1] - bounds[0]).abs().ceil().as_uvec2().max(UVec2::ONE), + quality, + } + } + pub fn viewport_bounds_in_local_space(&self) -> AxisAlignedBbox { // A singular or non-finite transform, like `BOUNDLESS`, can't map the viewport back into local space let Some(inverse_matrix2) = self.transform.matrix2.try_inverse() else { diff --git a/node-graph/libraries/core-types/src/uuid.rs b/node-graph/libraries/core-types/src/uuid.rs index 838d7da8cef..b34389f6753 100644 --- a/node-graph/libraries/core-types/src/uuid.rs +++ b/node-graph/libraries/core-types/src/uuid.rs @@ -42,7 +42,7 @@ mod u64_string { mod uuid_generation { use rand_chacha::ChaCha20Rng; - use rand_chacha::rand_core::{RngCore, SeedableRng}; + use rand_chacha::rand_core::{Rng, SeedableRng}; use std::cell::Cell; use std::sync::Mutex; diff --git a/node-graph/libraries/graphic-types/Cargo.toml b/node-graph/libraries/graphic-types/Cargo.toml index 2b9274be11d..a0af59d7487 100644 --- a/node-graph/libraries/graphic-types/Cargo.toml +++ b/node-graph/libraries/graphic-types/Cargo.toml @@ -21,6 +21,7 @@ wasm = [ "core-types/wasm", "vector-types/wasm", "raster-types/wasm", + "tsify", "wasm-bindgen", ] @@ -28,6 +29,7 @@ wasm = [ # Local dependencies core-types = { workspace = true } graphene-hash = { workspace = true } +graphene-resource = { workspace = true } brush-types = { workspace = true } raster-types = { workspace = true, features = ["wgpu"] } vector-types = { workspace = true } @@ -40,4 +42,5 @@ serde_json = { workspace = true } # Optional workspace dependencies serde = { workspace = true, optional = true } +tsify = { workspace = true, optional = true } wasm-bindgen = { workspace = true, optional = true } diff --git a/node-graph/libraries/graphic-types/src/adjustment.rs b/node-graph/libraries/graphic-types/src/adjustment.rs new file mode 100644 index 00000000000..ab2cccc7fde --- /dev/null +++ b/node-graph/libraries/graphic-types/src/adjustment.rs @@ -0,0 +1,296 @@ +//! Color adjustments as plain data, each holding its node's settings in the node's own units, carried out by the kernels of the `raster-kernels` crate. + +use core_types::Color; +use core_types::blending::BlendMode; +use core_types::graphene_hash::CacheHash; +use core_types::list::Item; +use core_types::transfer_curve::TransferCurve; +use dyn_any::DynAny; +use graphene_resource::Resource; +use vector_types::Gradient; + +/// A color adjustment applied to each color on its own, with no regard for its neighbors. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub enum Adjustment { + Desaturate { + method: DesaturateMethod, + }, + GammaCorrection { + gamma: f64, + inverse: bool, + }, + MakeOpaque, + BrightnessContrast { + /// Percent. + brightness: f64, + /// Percent. + contrast: f64, + use_classic: bool, + /// On a scale of 0 to 255. + classic_pivot: f64, + }, + Levels(Box), + Curves(Box), + BlackAndWhite(BlackAndWhiteSettings), + HueSaturation(Box), + Invert, + Threshold { + /// Percent. + min_luminance: f64, + /// Percent. + max_luminance: f64, + }, + GradientMap { + /// The gradient, with its whole-ramp settings as its attributes. + gradient: Item, + reverse: bool, + }, + Vibrance { + /// Percent. + vibrance: f64, + /// Percent. + saturation: f64, + }, + ChannelMixer(Box), + SelectiveColor(Box), + Posterize { + levels: i64, + }, + Exposure { + exposure: f64, + offset: f64, + gamma_correction: f64, + }, + ColorBalance(ColorBalanceSettings), + PhotoFilter { + color: Color, + /// Percent. + density: f64, + preserve_luminosity: bool, + }, + ColorLookup { + /// The file the lookup table is read from. + lut_file: Resource, + }, + ColorOverlay { + color: Color, + blend_mode: BlendMode, + /// Percent. + opacity: f64, + }, +} + +impl std::fmt::Display for Adjustment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Desaturate { .. } => "Desaturate", + Self::GammaCorrection { .. } => "Gamma Correction", + Self::MakeOpaque => "Make Opaque", + Self::BrightnessContrast { .. } => "Brightness/Contrast", + Self::Levels(_) => "Levels", + Self::Curves(_) => "Curves", + Self::BlackAndWhite(_) => "Black & White", + Self::HueSaturation(_) => "Hue/Saturation", + Self::Invert => "Invert", + Self::Threshold { .. } => "Threshold", + Self::GradientMap { .. } => "Gradient Map", + Self::Vibrance { .. } => "Vibrance", + Self::ChannelMixer(_) => "Channel Mixer", + Self::SelectiveColor(_) => "Selective Color", + Self::Posterize { .. } => "Posterize", + Self::Exposure { .. } => "Exposure", + Self::ColorBalance(_) => "Color Balance", + Self::PhotoFilter { .. } => "Photo Filter", + Self::ColorLookup { .. } => "Color Lookup", + Self::ColorOverlay { .. } => "Color Overlay", + }) + } +} + +/// Conversion from a color to grayscale. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum DesaturateMethod { + /// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`. + /// + /// Accessibility contrast ratios and SVG luminance masks use this. + #[default] + #[label("Luminance (Rec. 709)")] + #[cfg_attr(feature = "serde", serde(alias = "SRGB"))] + LuminanceRec709, + /// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`. + /// + /// CSS filter functions such as `grayscale()` use this. + #[label("Luma (Rec. 709)")] + LumaRec709, + /// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`. + /// + /// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`. + #[label("Luma (Rec. 601)")] + LumaRec601, + /// Perceptually uniform scale from black to white, the L (lightness) of OkLab. + #[label("Lightness (OkLab)")] + #[cfg_attr(feature = "serde", serde(alias = "Perceptual"))] + LightnessOkLab, + /// Mean of the three linear-light RGB channels. + #[menu_separator] + #[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))] + ChannelsAverage, + /// Smallest of the three linear-light RGB channels. + #[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))] + ChannelsMinimum, + /// Largest of the three linear-light RGB channels, the V (value) of HSV. + #[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))] + ChannelsMaximum, + /// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL. + /// + /// The classic "Desaturate" command of many image editors uses this. + #[label("Lightness (HSL)")] + LightnessHsl, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Radio)] +pub enum RelativeAbsolute { + #[default] + Relative, + Absolute, +} + +/// One channel's Levels record: percentage input and output points and the midtones gamma. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct LevelsRecord { + pub shadows: f64, + pub midtones: f64, + pub highlights: f64, + pub output_minimums: f64, + pub output_maximums: f64, +} + +/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct LevelsSettings { + pub composite: LevelsRecord, + pub red: LevelsRecord, + pub green: LevelsRecord, + pub blue: LevelsRecord, + pub alpha: LevelsRecord, +} + +/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct CurvesSettings { + pub composite: TransferCurve, + pub red: TransferCurve, + pub green: TransferCurve, + pub blue: TransferCurve, + pub alpha: TransferCurve, +} + +/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct BlackAndWhiteSettings { + pub use_tint: bool, + pub tint: Color, + pub reds: f64, + pub yellows: f64, + pub greens: f64, + pub cyans: f64, + pub blues: f64, + pub magentas: f64, +} + +/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct HueSaturationSliders { + pub hue: f64, + pub saturation: f64, + pub lightness: f64, +} + +/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct HueRangeSettings { + pub sliders: HueSaturationSliders, + pub falloff_start: f64, + pub range_start: f64, + pub range_end: f64, + pub falloff_end: f64, +} + +/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct HueSaturationSettings { + pub master: HueSaturationSliders, + pub colorize: bool, + pub colorize_sliders: HueSaturationSliders, + pub reds: HueRangeSettings, + pub yellows: HueRangeSettings, + pub greens: HueRangeSettings, + pub cyans: HueRangeSettings, + pub blues: HueRangeSettings, + pub magentas: HueRangeSettings, +} + +/// The percentages of each source channel, plus a constant, that sum to one output channel. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct ChannelMixerRow { + pub red: f64, + pub green: f64, + pub blue: f64, + pub constant: f64, +} + +/// A row for each output channel, or for the single gray channel when monochrome. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct ChannelMixerSettings { + pub monochrome: bool, + pub monochrome_mix: ChannelMixerRow, + pub red: ChannelMixerRow, + pub green: ChannelMixerRow, + pub blue: ChannelMixerRow, +} + +/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors. +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] +pub struct SelectiveColorInks { + pub cyan: f64, + pub magenta: f64, + pub yellow: f64, + pub black: f64, +} + +/// The ink offsets of each group of colors, and whether they are relative to the inks already present. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct SelectiveColorSettings { + pub mode: RelativeAbsolute, + pub reds: SelectiveColorInks, + pub yellows: SelectiveColorInks, + pub greens: SelectiveColorInks, + pub cyans: SelectiveColorInks, + pub blues: SelectiveColorInks, + pub magentas: SelectiveColorInks, + pub whites: SelectiveColorInks, + pub neutrals: SelectiveColorInks, + pub blacks: SelectiveColorInks, +} + +/// Percentage shifts along the three opponent color axes for one tonal range. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct ColorBalanceShifts { + pub cyan_red: f64, + pub magenta_green: f64, + pub yellow_blue: f64, +} + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct ColorBalanceSettings { + pub shadows: ColorBalanceShifts, + pub midtones: ColorBalanceShifts, + pub highlights: ColorBalanceShifts, + pub preserve_luminosity: bool, +} diff --git a/node-graph/libraries/graphic-types/src/appearance.rs b/node-graph/libraries/graphic-types/src/appearance.rs index 164dfa0694a..8808a7037b6 100644 --- a/node-graph/libraries/graphic-types/src/appearance.rs +++ b/node-graph/libraries/graphic-types/src/appearance.rs @@ -1,10 +1,12 @@ //! The appearance model: an ordered list of paint passes ("coverages") stored in the `ATTR_APPEARANCE` attribute. -//! Data uniform across all covers (the paint) rides the outer `List` so columnar presence holds, -//! while cover-specific data rides the inner `Item`, reusing `ATTR_TRANSFORM` for the stroke-authoring space. +//! Data uniform across all covers rides the outer `List` so columnar presence holds: the paint, and the transform the content had +//! when the coverage was stamped, like an effect's. Cover-specific data rides the inner `Item`. +use crate::effects::{rebased_stamped_transform, stamped_transform}; use crate::graphic::Graphic; use core_types::graphene_hash::CacheHash; use core_types::list::{ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List}; +use glam::DAffine2; use vector_types::vector::style::{DashPattern, Stroke}; /// The geometry-to-region operator a coverage applies before painting: @@ -80,9 +82,6 @@ impl Coverage { if stroke.align != defaults.align { item.set_attribute(ATTR_ALIGN, stroke.align); } - if stroke.transform != defaults.transform { - item.set_attribute(ATTR_TRANSFORM, stroke.transform); - } Self(item) } @@ -93,7 +92,7 @@ impl Coverage { } /// Extracts the stroke parameters into a [`Stroke`], falling back to the default for any absent attribute. - /// Dash lengths are clamped to non-negative, matching what rendering accepts. + /// Dash lengths are clamped to non-negative, matching what rendering accepts. The transform rides the coverage's row (see [`Appearance::stroke_params_at`]). pub fn stroke_params(&self) -> Stroke { // A single walk of the attribute pairs instead of one keyed scan per parameter, since this runs per item per render pass let mut stroke = Stroke::default(); @@ -106,7 +105,6 @@ impl Coverage { ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join), ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit), ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align), - ATTR_TRANSFORM => stroke.transform = value.downcast_ref().copied().unwrap_or(stroke.transform), _ => {} } } @@ -114,9 +112,9 @@ impl Coverage { } } -/// Builds an appearance row, eliding the paint attribute when it is the default none-paint. -fn cover_row(coverage: Coverage, paint: Graphic) -> Item { - let mut row = Item::new_from_element(coverage); +/// Builds an appearance row, eliding the paint attribute when it is the default none-paint, with the `transform` the coverage was stamped at. +fn cover_row(coverage: Coverage, paint: Graphic, transform: DAffine2) -> Item { + let mut row = Item::new_from_element(coverage).with_attribute(ATTR_TRANSFORM, transform); if paint != Graphic::default() { row.set_attribute(ATTR_PAINT, paint); } @@ -124,9 +122,9 @@ fn cover_row(coverage: Coverage, paint: Graphic) -> Item { } impl Appearance { - /// Creates an appearance holding a single coverage with the given paint. + /// Creates an appearance holding a single coverage with the given paint, stamped on untransformed content. pub fn new_single(coverage: Coverage, paint: Graphic) -> Self { - Self(List::new_from_item(cover_row(coverage, paint))) + Self(List::new_from_item(cover_row(coverage, paint, DAffine2::IDENTITY))) } /// The number of coverages in this appearance. @@ -165,6 +163,30 @@ impl Appearance { self.0.attribute::(ATTR_PAINT, index) } + /// The transform the coverage at the given index was stamped at, which sets the space its lengths are measured in. + pub fn transform_at(&self, index: usize) -> DAffine2 { + self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index) + } + + /// The stroke parameters of the coverage at the given index, measured in the space it was stamped at. + pub fn stroke_params_at(&self, index: usize) -> Option { + let mut stroke = self.cover_at(index)?.stroke_params(); + stroke.transform = self.transform_at(index); + Some(stroke) + } + + /// The stroke parameters of the first stroke coverage, measured in the space it was stamped at. + pub fn first_stroke_params(&self) -> Option { + self.first_index_of(Cover::Stroke).and_then(|index| self.stroke_params_at(index)) + } + + /// Moves the transforms the coverages were stamped at onto content whose `baked` transform went into its geometry. + pub fn rebase_stamped_transforms(&mut self, baked: DAffine2) { + if let Some(transforms) = self.0.iter_attribute_values_mut::(ATTR_TRANSFORM) { + transforms.for_each(|transform| *transform = rebased_stamped_transform(*transform, baked)); + } + } + /// The index of the first coverage of the given cover in paint order. pub fn first_index_of(&self, cover: Cover) -> Option { self.covers().position(|coverage| coverage.cover() == cover) @@ -199,7 +221,10 @@ impl Appearance { let painted = |index| self.paint_at(index).filter(|paint| !paint.is_empty()); FillAndStroke { - stroke: first_stroke.map(|(_, coverage)| coverage.stroke_params()), + stroke: first_stroke.map(|(index, coverage)| Stroke { + transform: self.transform_at(index), + ..coverage.stroke_params() + }), fill_paint: first_fill.and_then(painted), stroke_paint: first_stroke.and_then(|(index, _)| painted(index)), stroke_below: first_stroke.zip(first_fill).is_some_and(|((stroke_index, _), fill_index)| stroke_index < fill_index), @@ -220,17 +245,18 @@ impl Appearance { } /// Replaces the first coverage of the incoming cover in place (keeping its position in the paint order), - /// or inserts a new row at the requested end of the paint order if none exists. - pub fn replace_or_insert(&mut self, coverage: Coverage, paint: Graphic, placement: CoverPlacement) { + /// or inserts a new row at the requested end of the paint order if none exists, either way stamped at `transform`. + pub fn replace_or_insert(&mut self, coverage: Coverage, paint: Graphic, transform: DAffine2, placement: CoverPlacement) { if let Some(index) = self.first_index_of(coverage.cover()) { if let Some(element) = self.0.element_mut(index) { *element = coverage; } self.0.set_attribute(ATTR_PAINT, index, paint); + self.0.set_attribute(ATTR_TRANSFORM, index, transform); return; } - let row = cover_row(coverage, paint); + let row = cover_row(coverage, paint, transform); match placement { CoverPlacement::Above => self.0.push(row), CoverPlacement::Below => { @@ -266,10 +292,12 @@ pub struct FillAndStroke<'a> { pub stroke_below: bool, } -/// Stamps a coverage into the item's `ATTR_APPEARANCE` cell, creating the attribute if absent. +/// Stamps a coverage into the item's `ATTR_APPEARANCE` cell, creating the attribute if absent, recording the item's transform at that point. /// The coverage replaces the first same-cover one in place, or lands at the placement end of the paint order. pub fn stamp_coverage(item: &mut Item, coverage: Coverage, paint: Graphic, placement: CoverPlacement) { - item.attribute_mut_or_insert_default::(ATTR_APPEARANCE).replace_or_insert(coverage, paint, placement); + let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM)); + item.attribute_mut_or_insert_default::(ATTR_APPEARANCE) + .replace_or_insert(coverage, paint, transform, placement); } #[cfg(test)] @@ -299,7 +327,7 @@ mod tests { join: StrokeJoin::Bevel, join_miter_limit: 7., align: StrokeAlign::Inside, - transform: DAffine2::from_scale(DVec2::new(2., 3.)), + transform: DAffine2::IDENTITY, }; let coverage = Coverage::new_stroke(&stroke); @@ -313,7 +341,42 @@ mod tests { assert_eq!(extracted.join, StrokeJoin::Bevel); assert_eq!(extracted.join_miter_limit, 7.); assert_eq!(extracted.align, StrokeAlign::Inside); - assert_eq!(extracted.transform, DAffine2::from_scale(DVec2::new(2., 3.))); + } + + #[test] + fn coverages_record_the_content_transform_on_their_row() { + // Fill and stroke rows alike record the linear part of the transform the content had when they were stamped + let mut item = Item::new_from_element(()).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale_angle_translation(DVec2::new(2., 3.), 0., DVec2::splat(5.))); + stamp_coverage(&mut item, Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Above); + stamp_coverage(&mut item, Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above); + + let Some(appearance) = item.attribute::(ATTR_APPEARANCE) else { + panic!("stamping should add the appearance attribute"); + }; + let scale = DAffine2::from_scale(DVec2::new(2., 3.)); + assert_eq!(appearance.transform_at(0), scale); + assert_eq!(appearance.first_stroke_params().map(|stroke| stroke.transform), Some(scale)); + assert_eq!(appearance.fill_and_stroke().stroke.map(|stroke| stroke.transform), Some(scale)); + } + + #[test] + fn coverages_keep_measuring_in_the_same_space_once_their_content_is_baked() { + let stamped_at = |transform: DAffine2| { + let mut item = Item::new_from_element(()).with_attribute(ATTR_TRANSFORM, transform); + stamp_coverage(&mut item, Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above); + item.attribute::(ATTR_APPEARANCE).cloned().unwrap_or_default() + }; + let tripled = DAffine2::from_scale(DVec2::splat(3.)); + + // Stamped on content scaled by 3, the stroke measured as viewed, which is the identity space the baked geometry now lies in + let mut appearance = stamped_at(tripled); + appearance.rebase_stamped_transforms(tripled); + assert!(appearance.transform_at(0).abs_diff_eq(DAffine2::IDENTITY, 1e-12)); + + // Stamped before the scale, the stroke was scaled by it, and keeps being once the scale goes into the geometry + let mut appearance = stamped_at(DAffine2::IDENTITY); + appearance.rebase_stamped_transforms(tripled); + assert!(appearance.transform_at(0).abs_diff_eq(DAffine2::from_scale(DVec2::splat(1. / 3.)), 1e-12)); } #[test] @@ -346,10 +409,10 @@ mod tests { #[test] fn replace_keeps_position_and_the_other_rows_paint() { let mut appearance = Appearance::default(); - appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Above); - appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), DAffine2::IDENTITY, CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), DAffine2::IDENTITY, CoverPlacement::Above); - appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::BLUE), CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::BLUE), DAffine2::IDENTITY, CoverPlacement::Above); assert_eq!(appearance.len(), 2, "replacement should not add a row"); assert_eq!(appearance.cover_at(0).map(Coverage::cover), Some(Cover::Fill), "the fill should keep its position"); @@ -360,8 +423,8 @@ mod tests { #[test] fn below_insertion_prepends_and_preserves_paint_columns() { let mut appearance = Appearance::default(); - appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above); - appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Below); + appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), DAffine2::IDENTITY, CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), DAffine2::IDENTITY, CoverPlacement::Below); let covers: Vec<_> = appearance.covers().map(Coverage::cover).collect(); assert_eq!(covers, vec![Cover::Fill, Cover::Stroke], "a below-placed fill should paint before the stroke"); @@ -372,14 +435,14 @@ mod tests { #[test] fn painted_cover_distinguishes_none_paint_from_absence() { let mut appearance = Appearance::default(); - appearance.replace_or_insert(Coverage::new_fill(), Graphic::default(), CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_fill(), Graphic::default(), DAffine2::IDENTITY, CoverPlacement::Above); assert!(appearance.has_cover(Cover::Fill), "a none-painted coverage still exists"); assert!(!appearance.has_painted_cover(Cover::Fill), "a none-painted coverage draws nothing"); assert!(!appearance.has_cover(Cover::Stroke)); assert!(!appearance.has_painted_cover(Cover::Stroke)); - appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Above); + appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), DAffine2::IDENTITY, CoverPlacement::Above); assert!(appearance.has_painted_cover(Cover::Fill)); } } diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs new file mode 100644 index 00000000000..cd167a8b87f --- /dev/null +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -0,0 +1,705 @@ +//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute. +//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent. +//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render. + +use crate::Graphic; +use core_types::ATTR_TRANSFORM; +use core_types::Color; +use core_types::color::SRGBA8; +use core_types::graphene_hash::CacheHash; +use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List}; +use core_types::transfer_curve::TransferCurve; +use dyn_any::DynAny; +use glam::{DAffine2, DMat2, DVec2}; +use std::borrow::Cow; +use std::fmt::Debug; +use std::ops::Range; +use vector_types::gradient::GradientEvaluator; +use vector_types::{Gradient, GradientSettings}; + +/// The image operation an [`Effect`] carries out. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)] +pub enum EffectKind { + /// Softens the content by blurring it. + #[default] + Blur, + /// Casts the content's silhouette as a soft shadow beneath it. + DropShadow, + /// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface. + InnerShadow, + /// Surrounds the content with a soft glow of its silhouette. + OuterGlow, +} + +impl std::fmt::Display for EffectKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Blur => "Blur", + Self::DropShadow => "Drop Shadow", + Self::InnerShadow => "Inner Shadow", + Self::OuterGlow => "Outer Glow", + }) + } +} + +/// How a glow fades away from the content's edges. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Radio)] +pub enum GlowTechnique { + /// Fades like a blur of the content, rounding away its finer details. + #[default] + Softer, + /// Fades evenly with the distance from the content's edges, following its details. + Precise, +} + +/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EffectCapture { + /// The effect's place in its item's list, or in its run of that list once a renderer splits the list into runs. + pub index: usize, + /// Which of the effect's coverages, for an effect drawn from more than one. + pub plane: usize, +} + +/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space. +pub fn shadow_offset(angle: f64, distance: f64) -> DVec2 { + let angle = angle.to_radians(); + DVec2::new(-angle.cos(), angle.sin()) * distance +} + +/// How a shadow or glow of `size` splits into the round grow its `spread` percentage hardens and the tent blur softening the rest, both lengths in the same units. +/// The grow is whole units, and a tent narrower than two units widens to two, so that any softening shows. +pub fn grow_and_tent(size: f64, spread: f64) -> (f64, f64) { + let size = size.max(0.); + let grow = (size * spread.clamp(0., 100.) / 100. + 0.5).floor().min(size); + let tent = size - grow; + + // Narrower tents are scaled up to two units, joining the identity at zero without a jump + let tent = if tent >= 2. { tent } else { (2. * tent).min(2.) }; + (grow, tent) +} + +/// The strength, from 0 to 1, of a precise glow at `distance` from the content (zero within it), given the `grow` and `size` it was cast with, all in the same units. +/// It falls in a straight line through half strength at the grown edge, reaching nothing a unit past the size. +pub fn precise_falloff(distance: f64, grow: f64, size: f64) -> f64 { + (0.5 - 0.5 * (distance - grow) / (size - grow + 1.)).clamp(0., 1.) +} + +/// Maps a shadow or glow's strength from 0 to 1 through its `range` percentage, which strengthens it so it reaches full strength at that fraction, and then its `contour`. +pub fn shape_strength(strength: f64, range: f64, contour: &impl Fn(f64) -> f64) -> f64 { + let range = range.clamp(1., 100.) / 100.; + contour((strength / range).clamp(0., 1.)).clamp(0., 1.) +} + +/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item. +/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored. +#[derive(Clone, Debug, Default, PartialEq, CacheHash)] +pub struct Effect(pub Item); + +impl Effect { + /// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults. + pub fn new(operation: &EffectOperation) -> Self { + let mut item = Item::new_from_element(operation.kind()); + operation.clone().visit_parameters(&mut WriteParameters(&mut item)); + Self(item) + } + + /// This effect's kind. + pub fn kind(&self) -> EffectKind { + *self.0.element() + } + + /// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute and to zero for any length that isn't finite. + pub fn operation(&self) -> EffectOperation { + let mut operation = EffectOperation::placeholder(self.kind()); + operation.visit_parameters(&mut ReadParameters(&self.0)); + operation.with_finite_lengths() + } +} + +/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow). +#[derive(Clone, Debug, Default, PartialEq, CacheHash)] +pub struct Effects(pub List); + +impl Effects { + /// Creates the list of rows carrying out the given operations in order, stamped on untransformed content. + pub fn from_operations(operations: impl IntoIterator) -> Self { + let mut effects = Self::default(); + for operation in operations { + effects.0.push(Item::new_from_element(Effect::new(&operation)).with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY)); + } + effects + } + + /// The effects in the order they're carried out. + pub fn effects(&self) -> impl Iterator { + self.0.iter_element_values() + } + + /// The effects decoded into the operations renderers carry out, in order. + pub fn operations(&self) -> impl Iterator + '_ { + self.effects().map(Effect::operation) + } + + /// Whether carrying out the effects leaves the content as it is, like a blur of no radius, so renderers can skip them. + pub fn change_nothing(&self) -> bool { + self.operations().all(|operation| operation.changes_nothing()) + } + + /// The effects of the given range of rows decoded into operations, in order. + pub fn operations_in(&self, rows: Range) -> impl Iterator + '_ { + self.effects().skip(rows.start).take(rows.len()).map(Effect::operation) + } + + /// How far past the content the effects together can paint, in the effect space of a run of them. + pub fn reach(&self) -> f64 { + self.operations().map(|operation| operation.painted_reach()).sum() + } + + /// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at. + /// A transform applied between two effects starts a new run, which renders around the result of those before it. + /// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect. + pub fn runs(&self) -> Vec<(DAffine2, Range)> { + let mut runs: Vec<(DAffine2, Range)> = Vec::new(); + let mut run_changes_something = false; + for (index, effect) in self.effects().enumerate() { + let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index); + let changes_something = !effect.operation().changes_nothing(); + + if let Some((transform, rows)) = runs.last_mut() + && (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2)) + { + if changes_something && !run_changes_something { + *transform = stamped_transform; + } + rows.end = index + 1; + run_changes_something |= changes_something; + } else { + runs.push((stamped_transform, index..index + 1)); + run_changes_something = changes_something; + } + } + runs + } + + /// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry. + pub fn rebase_stamped_transforms(&mut self, baked: DAffine2) { + if let Some(transforms) = self.0.iter_attribute_values_mut::(ATTR_TRANSFORM) { + transforms.for_each(|transform| *transform = rebased_stamped_transform(*transform, baked)); + } + } + + /// The effects of a run of rows, borrowed when the run is every row. + pub fn run(&self, rows: Range) -> Cow<'_, Effects> { + match rows == (0..self.len()) { + true => Cow::Borrowed(self), + false => Cow::Owned(Effects(rows.filter_map(|index| self.0.clone_item(index)).collect())), + } + } + + /// How far past the content the effects together can paint along each axis of the space `content_transform` places the content in. + pub fn reach_along_axes(&self, content_transform: DAffine2) -> DVec2 { + self.reach_along_axes_by(content_transform, EffectOperation::painted_reach) + } + + /// Like [`Self::reach_along_axes`], measuring how far each effect reaches in its effect space by `reach`. + pub fn reach_along_axes_by(&self, content_transform: DAffine2, reach: impl Fn(&EffectOperation) -> f64) -> DVec2 { + (self.runs().into_iter()) + .map(|(stamped_transform, rows)| self.operations_in(rows).map(|operation| reach(&operation)).sum::() * spans_along_axes(effect_space(content_transform, stamped_transform).matrix2)) + .sum() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +/// The most that a length in one space spans along each axis of another, given the linear map between them. +pub fn spans_along_axes(linear_map: DMat2) -> DVec2 { + DVec2::new(linear_map.row(0).length(), linear_map.row(1).length()) +} + +/// Whether two linear maps agree to within rounding, as two transforms meant to be the same do after a turn and its undoing. +fn same_linear_part(first: DMat2, second: DMat2) -> bool { + let scale = first.x_axis.abs().max_element().max(first.y_axis.abs().max_element()); + first.abs_diff_eq(second, 1e-9 * scale) +} + +/// For PSD interop, an outer glow filled with a gradient fades out once its strength before range and contour falls below this. +pub const GRADIENT_GLOW_FADE: f64 = 0.12; + +/// What fills a glow: a solid color its strength fades, or a gradient its strength runs across, from the gradient's start at full strength to its end at none. +pub enum GlowFill { + Solid(Color), + Gradient { + evaluator: Box, + visible: bool, + /// The gradient item's opacity, which fades the glow after the gradient's own alpha. + opacity: f32, + }, +} + +impl GlowFill { + /// The fill a glow's `paint` makes, or `None` for a paint other than a color or a gradient, which fills nothing. + pub fn of(paint: &Graphic) -> Option { + // Faded by the paint's opacity attributes, like any paint + let opacity = |item_opacity: Option<&f64>, fill_opacity: Option<&f64>| (item_opacity.copied().unwrap_or(1.) * fill_opacity.copied().unwrap_or(1.)) as f32; + let solid = |item: &Item| { + let color = *item.element(); + Self::Solid(color.with_alpha(color.a() * opacity(item.attribute(ATTR_OPACITY), item.attribute(ATTR_OPACITY_FILL)))) + }; + let gradient = |item: &Item| Self::Gradient { + evaluator: Box::new(item.element().evaluator(GradientSettings::from_item_attributes(item))), + visible: item.element().0.iter_element_values().any(|stop| stop.a() > 0.), + opacity: opacity(item.attribute(ATTR_OPACITY), item.attribute(ATTR_OPACITY_FILL)), + }; + + match paint { + Graphic::Color(item) => Some(solid(item)), + Graphic::ColorList(list) => list.clone_item(0).map(|item| solid(&item)), + Graphic::Gradient(item) => Some(gradient(item)), + Graphic::GradientList(list) => list.clone_item(0).map(|item| gradient(&item)), + _ => None, + } + } + + /// Whether the fill paints nothing anywhere. + pub fn is_invisible(&self) -> bool { + match self { + Self::Solid(color) => color.a() <= 0., + Self::Gradient { visible, opacity, .. } => !visible || *opacity <= 0., + } + } + + /// For a gradient, its straight gamma-encoded colors with alpha at `count` evenly spaced positions from its start to its end, and its opacity. + pub fn gradient_samples(&self, count: usize) -> Option<(Vec<[f32; 4]>, f32)> { + let Self::Gradient { evaluator, opacity, .. } = self else { return None }; + let samples = (0..count).map(|index| evaluator.evaluate(index as f64 / (count - 1).max(1) as f64).to_gamma_srgb_channels()).collect(); + Some((samples, *opacity)) + } + + /// The color with its alpha that a glow paints where its `strength` is, after its range and contour, given its `raw` strength before them. + /// For PSD interop, a gradient's own alpha is the glow's, which an outer glow (if `fades`) fades out by as its raw strength nears none. + pub fn color_at(&self, strength: f64, raw: f64, fades: bool) -> Color { + match self { + Self::Solid(color) => color.with_alpha(color.a() * strength as f32), + Self::Gradient { evaluator, opacity, .. } => { + let color = evaluator.evaluate(1. - strength); + let fade = if fades { (raw / GRADIENT_GLOW_FADE).min(1.) } else { 1. }; + color.with_alpha(color.a().min(fade as f32) * opacity) + } + } + } +} + +/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point. +/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect. +pub fn stamp_effect(item: &mut Item, effect: Effect) { + let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM)); + item.attribute_mut_or_insert_default::(ATTR_EFFECTS) + .0 + .push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform)); +} + +/// The part of a content transform a coverage or effect records, its linear part, since the content's position cancels out wherever it's used. +pub fn stamped_transform(content_transform: DAffine2) -> DAffine2 { + DAffine2::from_mat2(content_transform.matrix2) +} + +/// The space effects stamped at `stamped_transform` are carried out in, placed by the content's current `content_transform`. +/// Its origin is the content's, and its lengths are as viewed when stamped, carried and scaled by any transform applied since. +pub fn effect_space(content_transform: DAffine2, stamped_transform: DAffine2) -> DAffine2 { + let stamped_linear = stamped_transform.matrix2; + + // Content left as it was stamped measures exactly as viewed, which the product with the inverse only approximates + let since_stamped = if content_transform.matrix2 == stamped_linear || !stamped_linear.determinant().is_normal() { + DMat2::IDENTITY + } else { + content_transform.matrix2 * stamped_linear.inverse() + }; + DAffine2::from_mat2_translation(since_stamped, content_transform.translation) +} + +/// The transform a coverage or effect was stamped at, moved onto content whose `baked` transform went into its geometry, so it keeps measuring in the same space. +pub fn rebased_stamped_transform(stamped_transform: DAffine2, baked: DAffine2) -> DAffine2 { + match baked.matrix2.determinant().is_normal() { + true => DAffine2::from_mat2(stamped_transform.matrix2 * baked.matrix2.inverse()), + false => stamped_transform, + } +} + +/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in its [`effect_space`]. +#[derive(Clone, Debug, PartialEq)] +pub enum EffectOperation { + Blur { + /// The standard deviation of the Gaussian, or the half width of the box. + radius: f64, + /// Whether to average a box of pixels rather than weighting them by a Gaussian. + box_blur: bool, + /// Whether to blend the colors with their gamma encoding rather than in linear light. + gamma: bool, + }, + DropShadow { + /// With the shadow's opacity. + color: Color, + /// The direction the light comes from, in degrees counterclockwise from the right. + angle: f64, + distance: f64, + /// The percentage of the size that hardens into a grow of the silhouette rather than softening. + spread: f64, + size: f64, + contour: TransferCurve, + /// Whether the content hides the shadow where it covers it, even where a fill fades the content. + knockout: bool, + }, + InnerShadow { + color: Color, + angle: f64, + distance: f64, + /// The percentage of the size that hardens into a grow inward from the edges rather than softening. + choke: f64, + size: f64, + contour: TransferCurve, + }, + OuterGlow { + /// A solid color with the glow's opacity, or a gradient running from the content's edge outward. + color: Graphic, + technique: GlowTechnique, + spread: f64, + size: f64, + /// The percentage of the glow's strength it reaches full opacity at. + range: f64, + contour: TransferCurve, + }, +} + +impl EffectOperation { + /// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it. + pub fn default_for(kind: EffectKind) -> Self { + Effect(Item::new_from_element(kind)).operation() + } + + pub fn kind(&self) -> EffectKind { + match self { + Self::Blur { .. } => EffectKind::Blur, + Self::DropShadow { .. } => EffectKind::DropShadow, + Self::InnerShadow { .. } => EffectKind::InnerShadow, + Self::OuterGlow { .. } => EffectKind::OuterGlow, + } + } + + /// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity. + pub fn changes_nothing(&self) -> bool { + match self { + Self::Blur { radius, .. } => *radius <= 0., + Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } => color.a() <= 0., + Self::OuterGlow { color, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible()), + } + } + + /// How far past the content this operation paints, which is nowhere for an operation that changes nothing. + pub fn painted_reach(&self) -> f64 { + if self.changes_nothing() { 0. } else { self.reach() } + } + + /// How far past the content this operation can paint, or reads from, in its effect space. + pub fn reach(&self) -> f64 { + match self { + // A Gaussian is negligible past three standard deviations + Self::Blur { radius, .. } => 3. * radius.max(0.), + // An inner shadow paints within the content but reads this far out to find the edges it casts from. + // Shadows and glows end within their size, past which a precise glow fades over one more unit. + Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1., + Self::OuterGlow { size, .. } => size.max(0.) + 1., + } + } + + /// This operation with each length that isn't finite (like one computed by dividing by zero) made zero, since no renderer can carry it out. + fn with_finite_lengths(mut self) -> Self { + let finite = |length: &mut f64| { + if !length.is_finite() { + *length = 0.; + } + }; + + match &mut self { + Self::Blur { radius, .. } => finite(radius), + Self::DropShadow { angle, distance, spread, size, .. } + | Self::InnerShadow { + angle, distance, choke: spread, size, .. + } => { + [angle, distance, spread, size].into_iter().for_each(finite); + } + Self::OuterGlow { spread, size, range, .. } => [spread, size, range].into_iter().for_each(finite), + } + self + } + + /// An operation of this kind with arbitrary parameters, for a visitor to fill in. + fn placeholder(kind: EffectKind) -> Self { + match kind { + EffectKind::Blur => Self::Blur { + radius: 0., + box_blur: false, + gamma: false, + }, + EffectKind::DropShadow => Self::DropShadow { + color: Color::TRANSPARENT, + angle: 0., + distance: 0., + spread: 0., + size: 0., + contour: TransferCurve::default(), + knockout: false, + }, + EffectKind::InnerShadow => Self::InnerShadow { + color: Color::TRANSPARENT, + angle: 0., + distance: 0., + choke: 0., + size: 0., + contour: TransferCurve::default(), + }, + EffectKind::OuterGlow => Self::OuterGlow { + color: Graphic::default(), + technique: GlowTechnique::default(), + spread: 0., + size: 0., + range: 0., + contour: TransferCurve::default(), + }, + } + } + + /// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share. + /// For PSD interop, the defaults are those of layer styles, so imported ones that leave a setting out read the same. + fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) { + let shadow_color = Color::from(SRGBA8::new(0, 0, 0, 0xbf)); + let glow_color = Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)); + + match self { + Self::Blur { radius, box_blur, gamma } => { + visitor.parameter("radius", radius, 0.); + visitor.parameter("box_blur", box_blur, false); + visitor.parameter("gamma", gamma, false); + } + Self::DropShadow { + color, + angle, + distance, + spread, + size, + contour, + knockout, + } => { + visitor.parameter("color", color, shadow_color); + visitor.parameter("angle", angle, 120.); + visitor.parameter("distance", distance, 5.); + visitor.parameter("spread", spread, 0.); + visitor.parameter("size", size, 5.); + visitor.parameter("contour", contour, TransferCurve::default()); + visitor.parameter("knockout", knockout, true); + } + Self::InnerShadow { + color, + angle, + distance, + choke, + size, + contour, + } => { + visitor.parameter("color", color, shadow_color); + visitor.parameter("angle", angle, 120.); + visitor.parameter("distance", distance, 5.); + visitor.parameter("choke", choke, 0.); + visitor.parameter("size", size, 5.); + visitor.parameter("contour", contour, TransferCurve::default()); + } + Self::OuterGlow { + color, + technique, + spread, + size, + range, + contour, + } => { + visitor.parameter("color", color, Graphic::from(glow_color)); + visitor.parameter("technique", technique, GlowTechnique::default()); + visitor.parameter("spread", spread, 0.); + visitor.parameter("size", size, 5.); + visitor.parameter("range", range, 50.); + visitor.parameter("contour", contour, TransferCurve::default()); + } + } + } +} + +/// What a value needs to ride an attribute. +pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {} +impl ParameterValue for T {} + +/// Handles each parameter of an operation, given the attribute key it rides and its implicit default. +pub(crate) trait ParameterVisitor { + fn parameter(&mut self, key: &str, value: &mut T, default: T); +} + +/// Stamps each parameter that differs from its default onto a row. +struct WriteParameters<'a>(&'a mut Item); + +impl ParameterVisitor for WriteParameters<'_> { + fn parameter(&mut self, key: &str, value: &mut T, default: T) { + if *value != default { + self.0.set_attribute(key, value.clone()); + } + } +} + +/// Reads each parameter from a row, or its default where the row lacks it. +struct ReadParameters<'a>(&'a Item); + +impl ParameterVisitor for ReadParameters<'_> { + fn parameter(&mut self, key: &str, value: &mut T, default: T) { + *value = self.0.attribute::(key).cloned().unwrap_or(default); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_round_trip_their_operations_eliding_defaults() { + let operations = [ + EffectOperation::Blur { + radius: 6., + box_blur: true, + gamma: false, + }, + EffectOperation::default_for(EffectKind::DropShadow), + EffectOperation::InnerShadow { + color: Color::RED, + angle: 30., + distance: 3., + choke: 25., + size: 6., + contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.5, 1.), DVec2::ONE]), + }, + EffectOperation::OuterGlow { + color: Graphic::from(Color::BLUE), + technique: GlowTechnique::Precise, + spread: 10., + size: 8., + range: 75., + contour: TransferCurve::default(), + }, + ]; + + for operation in operations { + assert_eq!(Effect::new(&operation).operation(), operation); + } + + let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow)); + assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters"); + } + + #[test] + fn lengths_that_arent_finite_decode_as_zero() { + let row = Effect::new(&EffectOperation::DropShadow { + color: Color::BLACK, + angle: 90., + distance: f64::NAN, + spread: 3., + size: f64::INFINITY, + contour: TransferCurve::default(), + knockout: true, + }); + + let EffectOperation::DropShadow { distance, spread, size, .. } = row.operation() else { + panic!("the row changed kind") + }; + assert_eq!((distance, spread, size), (0., 3., 0.)); + } + + #[test] + fn shadows_fall_away_from_the_light() { + // Light from the upper left casts the shadow down and to the right + let offset = shadow_offset(120., 10.); + assert!((offset - DVec2::new(5., 10. * 60_f64.to_radians().sin())).length() < 1e-9); + assert!((shadow_offset(90., 5.) - DVec2::new(0., 5.)).length() < 1e-9); + } + + #[test] + fn spread_hardens_whole_units_of_the_size() { + assert_eq!(grow_and_tent(16., 0.), (0., 16.)); + assert_eq!(grow_and_tent(16., 50.), (8., 8.)); + // Growing by 3.3 rounds to 3, and by 3.5 rounds up to 4 + assert_eq!(grow_and_tent(10., 33.), (3., 7.)); + assert_eq!(grow_and_tent(7., 50.), (4., 3.)); + assert_eq!(grow_and_tent(16., 100.), (16., 0.)); + // A tent of one unit softens like one of two + assert_eq!(grow_and_tent(1., 0.), (0., 2.)); + assert_eq!(grow_and_tent(3., 50.), (2., 2.)); + } + + #[test] + fn precise_glows_fall_through_half_strength_at_the_grown_edge() { + assert_eq!(precise_falloff(8., 8., 16.), 0.5); + assert!((precise_falloff(1., 0., 16.) - 16. / 34.).abs() < 1e-12); + assert_eq!(precise_falloff(17., 0., 16.), 0.); + assert_eq!(precise_falloff(0., 16., 16.), 1.); + } + + #[test] + fn only_effects_that_show_change_something() { + assert!(Effects::from_operations([EffectOperation::default_for(EffectKind::Blur)]).change_nothing()); + assert!(!Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow)]).change_nothing()); + } + + #[test] + fn effects_on_content_left_as_stamped_measure_exactly_as_viewed() { + // An image's pixel scale times its inverse rounds away from the identity, which would otherwise set up an effect space of its own + let content = DAffine2::from_scale_angle_translation(DVec2::new(4000., 3000.), 10_f64.to_radians(), DVec2::new(250., 100.)); + let space = effect_space(content, stamped_transform(content)); + assert_eq!(space.matrix2, DMat2::IDENTITY); + assert_eq!(space.translation, content.translation); + + // A transform applied since stamping carries the space along + let scaled = DAffine2::from_scale(DVec2::splat(0.5)) * content; + let space = effect_space(scaled, stamped_transform(content)); + assert!(space.matrix2.abs_diff_eq(DMat2::from_diagonal(DVec2::splat(0.5)), 1e-12)); + } + + #[test] + fn runs_join_effects_stamped_rounding_apart_and_those_changing_nothing() { + let blur = |radius: f64| EffectOperation::Blur { + radius, + box_blur: false, + gamma: false, + }; + let mut item = Item::new_from_element(()); + let mut stamp_at = |transform: DAffine2, operation: EffectOperation| { + item.set_attribute(ATTR_TRANSFORM, transform); + stamp_effect(&mut item, Effect::new(&operation)); + }; + + // A turn and its undoing land back where they started only to within rounding, and a blur of no radius changes nothing wherever it's stamped + let turned_back = DAffine2::from_angle(30_f64.to_radians()) * DAffine2::from_angle(-30_f64.to_radians()); + stamp_at(DAffine2::IDENTITY, blur(2.)); + stamp_at(turned_back, blur(3.)); + stamp_at(DAffine2::from_scale(DVec2::splat(2.)), blur(0.)); + stamp_at(DAffine2::from_scale(DVec2::splat(2.)), blur(4.)); + + let Some(effects) = item.attribute::(ATTR_EFFECTS) else { + panic!("stamping should add the effects attribute"); + }; + let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect(); + assert_eq!(runs, vec![0..3, 3..4]); + } +} diff --git a/node-graph/libraries/graphic-types/src/generator.rs b/node-graph/libraries/graphic-types/src/generator.rs new file mode 100644 index 00000000000..87581787469 --- /dev/null +++ b/node-graph/libraries/graphic-types/src/generator.rs @@ -0,0 +1,113 @@ +//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate. + +use core_types::graphene_hash::CacheHash; +use dyn_any::DynAny; + +/// Style of noise pattern. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum NoiseType { + #[default] + Perlin, + #[label("OpenSimplex2")] + OpenSimplex2, + #[label("OpenSimplex2S")] + OpenSimplex2S, + Cellular, + ValueCubic, + Value, + WhiteNoise, +} + +/// Style of layered levels of the noise pattern. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum FractalType { + #[default] + None, + #[label("Fractional Brownian Motion")] + FBm, + Ridged, + PingPong, + #[label("Progressive (Domain Warp Only)")] + DomainWarpProgressive, + #[label("Independent (Domain Warp Only)")] + DomainWarpIndependent, +} + +/// Distance function used by the cellular noise. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum CellularDistanceFunction { + #[default] + Euclidean, + #[label("Euclidean Squared (Faster)")] + EuclideanSq, + Manhattan, + Hybrid, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum CellularReturnType { + CellValue, + #[default] + #[label("Nearest (F1)")] + Nearest, + #[label("Next Nearest (F2)")] + NextNearest, + #[label("Average (F1 / 2 + F2 / 2)")] + Average, + #[label("Difference (F2 - F1)")] + Difference, + #[label("Product (F2 * F1 / 2)")] + Product, + #[label("Division (F1 / F2)")] + Division, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum DomainWarpType { + #[default] + None, + #[label("OpenSimplex2")] + OpenSimplex2, + #[label("OpenSimplex2 Reduced")] + OpenSimplex2Reduced, + BasicGrid, +} + +/// The settings of a noise pattern, with lengths measured in the document units of the space it's sampled in. +#[derive(Debug, Clone, PartialEq, CacheHash)] +pub struct NoiseSettings { + pub seed: i64, + pub scale: f64, + pub noise_type: NoiseType, + pub domain_warp_type: DomainWarpType, + pub domain_warp_amplitude: f64, + pub fractal_type: FractalType, + pub fractal_octaves: i64, + pub fractal_lacunarity: f64, + pub fractal_gain: f64, + pub fractal_weighted_strength: f64, + pub fractal_ping_pong_strength: f64, + pub cellular_distance_function: CellularDistanceFunction, + pub cellular_return_type: CellularReturnType, + pub cellular_jitter: f64, +} + +/// A procedural pattern, a function of position in its own space that renders across any area at any resolution. +#[derive(Debug, Clone, PartialEq, CacheHash)] +pub enum GeneratorPattern { + Noise(NoiseSettings), + /// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis. + Mandelbrot, +} diff --git a/node-graph/libraries/graphic-types/src/graphic.rs b/node-graph/libraries/graphic-types/src/graphic.rs index 2b2ea8b9b74..ac9f2b5f981 100644 --- a/node-graph/libraries/graphic-types/src/graphic.rs +++ b/node-graph/libraries/graphic-types/src/graphic.rs @@ -1,8 +1,9 @@ use crate::appearance::{Appearance, Cover, Coverage}; +use crate::effects::Effects; use brush_types::Stroke; use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::graphene_hash::CacheHash; -use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath}; +use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath}; use core_types::math::quad::Quad; use core_types::none; use core_types::ops::FromAnchorPosition; @@ -292,8 +293,19 @@ pub fn is_paint_present(graphic_list: &List) -> bool { graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty()) } -/// Bake the provided transform into the per-item transforms of the appearance's paint graphics. -pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) { +/// Moves the transforms an item's coverages and effects were stamped at onto its geometry, which its `baked` transform went into, so they keep measuring in the same space. +pub fn rebase_stamped_transforms(attributes: &mut ItemAttributeValues, baked: DAffine2) { + if let Some(appearance) = attributes.get_mut::(ATTR_APPEARANCE) { + appearance.rebase_stamped_transforms(baked); + } + if let Some(effects) = attributes.get_mut::(ATTR_EFFECTS) { + effects.rebase_stamped_transforms(baked); + } +} + +/// Moves the provided transform, which went into an item's geometry, into what its attributes place: the per-item transforms of the appearance's +/// paint graphics, and the transforms its coverages and effects were stamped at (see [`rebase_stamped_transforms`]). +pub fn bake_transform_into_attributes(attributes: &mut ItemAttributeValues, transform: DAffine2) { fn bake_item_transform(item: &mut Item, transform: DAffine2) { let baked = transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM); item.set_attribute(ATTR_TRANSFORM, baked); @@ -325,6 +337,7 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA } } + rebase_stamped_transforms(attributes, transform); if let Some(appearance) = attributes.get_mut::(ATTR_APPEARANCE) && let Some(paints) = appearance.0.iter_attribute_values_mut::(ATTR_PAINT) { @@ -418,7 +431,7 @@ impl IntoGraphicList for List { impl IntoGraphicList for List { fn into_graphic_list(self) -> List { // A synthetic container, not a real group layer, so it carries no `editor:layer_path` that would - // overwrite the inner items' own stamps when flattened back out + // overwrite the inner items' own layer paths when flattened back out List::new_from_element(Graphic::VectorList(self)) } } @@ -946,7 +959,7 @@ mod tests { Graphic::VectorList(List::new_from_element(Vector::default())) } - fn vector_list_stamped_with_layers(layers: [u64; 2]) -> List { + fn vector_list_with_layer_paths(layers: [u64; 2]) -> List { let mut list = List::new(); for layer in layers { @@ -961,13 +974,13 @@ mod tests { // The wrapper minted for a typed list is a container rather than a layer, so it must never claim a layer path #[test] fn wrapping_a_typed_list_leaves_the_wrapper_anonymous() { - let graphic_list = vector_list_stamped_with_layers([7, 9]).into_graphic_list(); + let graphic_list = vector_list_with_layer_paths([7, 9]).into_graphic_list(); assert_eq!(graphic_list.len(), 1); assert!(!graphic_list.attribute_keys().any(|key| key == ATTR_EDITOR_LAYER_PATH)); } - fn layer_stamps(flattened: &List) -> Vec> { + fn item_layers(flattened: &List) -> Vec> { (0..flattened.len()) .map(|index| { flattened @@ -980,22 +993,22 @@ mod tests { .collect() } - // Round-tripping through that wrapper must not collapse the items' distinct stamps onto item 0's + // Round-tripping through that wrapper must not collapse the items' distinct layer paths onto item 0's #[test] fn round_trip_through_the_wrapper_preserves_per_item_layer_paths() { - let flattened: List = vector_list_stamped_with_layers([7, 9]).into_flattened_list(); + let flattened: List = vector_list_with_layer_paths([7, 9]).into_flattened_list(); - assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]); + assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]); } - // The embedding adapter reaches the same flattened stamps as the wrapper, each item carrying its own inside its variant + // The embedding adapter reaches the same flattened layer paths as the wrapper, each item carrying its own inside its variant #[test] fn embedding_each_item_preserves_per_item_layer_paths() { - let embedded: List = vector_list_stamped_with_layers([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect(); + let embedded: List = vector_list_with_layer_paths([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect(); let flattened: List = embedded.into_flattened_list(); - assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]); + assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]); } // Flattening must not invent attributes that neither the parent graphic nor the child carried diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index 82a375bdbdb..65a4ec7c80e 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -1,5 +1,8 @@ +pub mod adjustment; pub mod appearance; pub mod artboard; +pub mod effects; +pub mod generator; pub mod graphic; // Re-export all transitive dependencies so downstream crates only need to depend on graphic-types @@ -8,8 +11,10 @@ pub use raster_types; pub use vector_types; // Re-export commonly used types at the crate root +pub use adjustment::Adjustment; pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage}; pub use artboard::Artboard; +pub use effects::{Effect, EffectKind, EffectOperation, Effects, GlowTechnique, stamp_effect, stamped_transform}; pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector}; pub mod migrations { diff --git a/node-graph/libraries/raster-kernels/Cargo.toml b/node-graph/libraries/raster-kernels/Cargo.toml new file mode 100644 index 00000000000..083f0ca4a98 --- /dev/null +++ b/node-graph/libraries/raster-kernels/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "raster-kernels" +description = "The kernels carrying out Graphene's raster operations, such as each color adjustment" +version.workspace = true +license.workspace = true +authors.workspace = true +edition.workspace = true +repository.workspace = true +readme.workspace = true +homepage.workspace = true +rust-version.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +# Local dependencies +core-types = { workspace = true } +graphene-resource = { workspace = true } +graphic-types = { workspace = true } +raster-types = { workspace = true } +vector-types = { workspace = true } + +# Workspace dependencies +fastnoise-lite = { workspace = true } +glam = { workspace = true } +log = { workspace = true } +thiserror = { workspace = true } diff --git a/node-graph/libraries/raster-kernels/src/adjustments.rs b/node-graph/libraries/raster-kernels/src/adjustments.rs new file mode 100644 index 00000000000..efb035cf114 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/adjustments.rs @@ -0,0 +1,1432 @@ +//! The kernels carrying out each [`Adjustment`], with its settings turned into what its kernel reads by [`visit_kernel`]. + +use crate::MapColor; +use crate::blending::ColorOverlay; +use crate::color_lookup_table::{Lut, parse_cached}; +use core_types::Color; +use core_types::color::{linear_to_srgb, set_luminosity, srgb_to_linear}; +use core_types::transfer_curve::TransferCurveEvaluator; +use glam::Vec3; +use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute}; +use raster_types::parallel_rows::fill_rows; +use std::sync::Arc; +use vector_types::GradientSettings; +use vector_types::gradient::GradientEvaluator; + +/// How many colors each thread band handles at a time when a long slice is split across threads. +const COLORS_PER_ROW: usize = 4096; + +/// Adjusts each color in place, on threads for long slices on native platforms. O(n). +pub fn adjust_colors(adjustment: &Adjustment, colors: &mut [Color]) { + struct AdjustColors<'a>(&'a mut [Color]); + + impl AdjustmentVisitor for AdjustColors<'_> { + type Output = (); + + fn visit(self, kernel: K) { + fill_rows(self.0, COLORS_PER_ROW, |_, row| row.iter_mut().for_each(|color| *color = kernel.map_cpu(*color))); + } + + fn unchanged(self) {} + } + + visit_kernel(adjustment, AdjustColors(colors)); +} + +/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead. +pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color { + struct AdjustColor(Color); + + impl AdjustmentVisitor for AdjustColor { + type Output = Color; + + fn visit(self, kernel: K) -> Color { + kernel.map_cpu(self.0) + } + + fn unchanged(self) -> Color { + self.0 + } + } + + visit_kernel(adjustment, AdjustColor(color)) +} + +/// An adjustment with its kernel prepared from its settings, which carries it out on any number of colors without preparing it again. +pub struct PreparedAdjustment(Option>); + +impl PreparedAdjustment { + pub fn new(adjustment: &Adjustment) -> Self { + struct Prepare; + + impl AdjustmentVisitor for Prepare { + type Output = Option>; + + fn visit(self, kernel: K) -> Self::Output { + Some(Box::new(kernel)) + } + + fn unchanged(self) -> Self::Output { + None + } + } + + Self(visit_kernel(adjustment, Prepare)) + } + + /// The color with the adjustment carried out on it. + pub fn adjust(&self, color: Color) -> Color { + self.0.as_ref().map_or(color, |kernel| kernel.map_cpu(color)) + } +} + +/// Receives the kernel carrying out an [`Adjustment`], which has its own type for each adjustment. +pub trait AdjustmentVisitor { + type Output; + fn visit(self, kernel: K) -> Self::Output; + /// Stands in for the kernel of an adjustment that leaves every color as it is, such as a lookup table with a file that can't be read. + fn unchanged(self) -> Self::Output; +} + +/// Hands `visitor` the kernel carrying out `adjustment`, with what the kernel reads worked out once from the adjustment's settings. +/// Settings past their nodes' bounds that would divide by zero are clamped to those bounds, so a description from anywhere stays finite. +pub fn visit_kernel(adjustment: &Adjustment, visitor: V) -> V::Output { + match adjustment { + Adjustment::Desaturate { method } => visitor.visit(Desaturate { method: *method }), + Adjustment::GammaCorrection { gamma, inverse } => { + let gamma = gamma.max(0.0001); + let exponent = if *inverse { 1. / gamma } else { gamma }; + visitor.visit(GammaCorrection { exponent: exponent as f32 }) + } + Adjustment::MakeOpaque => visitor.visit(MakeOpaque), + Adjustment::BrightnessContrast { + brightness, + contrast, + use_classic, + classic_pivot, + } => { + let classic_pivot = (classic_pivot / 255.) as f32; + + // Each algorithm has its own slider range, matched here and in the Inspector + let (brightness_extent, contrast_minimum) = if *use_classic { (100., -100.) } else { (150., -50.) }; + let brightness = (*brightness as f32).clamp(-brightness_extent, brightness_extent); + let contrast = (*contrast as f32).clamp(contrast_minimum, 100.) / 100.; + + // Beyond a magnitude of 100, the curve for 100 is applied first and the curve for the remainder after it + let magnitude = brightness.abs(); + let first_curve = BrightnessCurve::new(magnitude.min(100.)); + let second_curve = BrightnessCurve::new((magnitude - 100.).max(0.)); + + visitor.visit(BrightnessContrast { + use_classic: *use_classic, + brightness, + contrast, + classic_pivot, + first_curve, + second_curve, + }) + } + Adjustment::Levels(levels) => { + let record = |record: &settings::LevelsRecord| { + LevelsRecord::new( + record.shadows as f32, + record.midtones as f32, + record.highlights as f32, + record.output_minimums as f32, + record.output_maximums as f32, + ) + }; + let composite = record(&levels.composite); + + // Alpha stands apart from the composite record that the three color channels pass through + let alpha = record(&levels.alpha); + + visitor.visit(Levels { + red: LevelsChain::new(record(&levels.red), composite), + green: LevelsChain::new(record(&levels.green), composite), + blue: LevelsChain::new(record(&levels.blue), composite), + alpha: alpha.stage(alpha.midtones), + }) + } + Adjustment::Curves(curves) => visitor.visit(Curves { + composite: curves.composite.evaluator(), + red: curves.red.evaluator(), + green: curves.green.evaluator(), + blue: curves.blue.evaluator(), + alpha: curves.alpha.evaluator(), + }), + Adjustment::BlackAndWhite(black_and_white) => visitor.visit(BlackAndWhite { + use_tint: black_and_white.use_tint, + tint: black_and_white.tint, + reds: (black_and_white.reds / 100.) as f32, + yellows: (black_and_white.yellows / 100.) as f32, + greens: (black_and_white.greens / 100.) as f32, + cyans: (black_and_white.cyans / 100.) as f32, + blues: (black_and_white.blues / 100.) as f32, + magentas: (black_and_white.magentas / 100.) as f32, + }), + Adjustment::HueSaturation(hue_saturation) => { + let sliders = |sliders: &settings::HueSaturationSliders| PreparedHueSaturationSliders::new(sliders.hue as f32, sliders.saturation as f32, sliders.lightness as f32); + let range = |range: &settings::HueRangeSettings| { + HueSaturationRangeSettings::new( + range.falloff_start as f32, + range.range_start as f32, + range.range_end as f32, + range.falloff_end as f32, + sliders(&range.sliders), + ) + }; + + visitor.visit(HueSaturation { + master: sliders(&hue_saturation.master), + colorize: hue_saturation.colorize, + colorize_settings: sliders(&hue_saturation.colorize_sliders), + reds: range(&hue_saturation.reds), + yellows: range(&hue_saturation.yellows), + greens: range(&hue_saturation.greens), + cyans: range(&hue_saturation.cyans), + blues: range(&hue_saturation.blues), + magentas: range(&hue_saturation.magentas), + }) + } + Adjustment::Invert => visitor.visit(Invert), + Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold { + min_luminance: (min_luminance / 100.) as f32, + max_luminance: (max_luminance / 100.) as f32, + }), + Adjustment::GradientMap { gradient, reverse } => visitor.visit(GradientMap { + evaluator: gradient.element().evaluator(GradientSettings::from_item_attributes(gradient)), + reverse: *reverse, + }), + Adjustment::Vibrance { vibrance, saturation } => visitor.visit(Vibrance { + vibrance: (vibrance / 100.) as f32, + saturation_scale: (1. + saturation / 100.) as f32, + }), + Adjustment::ChannelMixer(channel_mixer) => { + // Weights and constants are 10-bit fixed point truncated toward zero, which PSD interop depends on + let weight = |percent: f64| (percent as f32 * 1024. / 100.).trunc() / 1024.; + let settings::ChannelMixerSettings { + monochrome, + monochrome_mix, + red, + green, + blue, + } = &**channel_mixer; + + visitor.visit(ChannelMixer { + monochrome: *monochrome, + monochrome_r: weight(monochrome_mix.red), + monochrome_g: weight(monochrome_mix.green), + monochrome_b: weight(monochrome_mix.blue), + monochrome_c: weight(monochrome_mix.constant), + red_r: weight(red.red), + red_g: weight(red.green), + red_b: weight(red.blue), + red_c: weight(red.constant), + green_r: weight(green.red), + green_g: weight(green.green), + green_b: weight(green.blue), + green_c: weight(green.constant), + blue_r: weight(blue.red), + blue_g: weight(blue.green), + blue_b: weight(blue.blue), + blue_c: weight(blue.constant), + }) + } + Adjustment::SelectiveColor(selective_color) => { + let mode = selective_color.mode; + + // For PSD interop, the combined percent (c + k + c k / 100) rounds half up to an integer + let ink = |color: f32, k: f32| { + let percent = ((2. * (100. * (color + k) + color * k) + 100.) / 200.).floor(); + match mode { + // The multiplier is stored as one byte, 255 / b above 1 and b / 255 below, so 99% and 100% both act as 127/128 + RelativeAbsolute::Relative => { + let multiplier = 1. + percent / 100.; + if multiplier >= 1. { + 255. / (255. / multiplier).round() - 1. + } else { + (255. * multiplier).round() / 255. - 1. + } + } + RelativeAbsolute::Absolute => percent / 100., + } + }; + + let groups = [ + (SelectiveColorGroup::Reds, &selective_color.reds), + (SelectiveColorGroup::Yellows, &selective_color.yellows), + (SelectiveColorGroup::Greens, &selective_color.greens), + (SelectiveColorGroup::Cyans, &selective_color.cyans), + (SelectiveColorGroup::Blues, &selective_color.blues), + (SelectiveColorGroup::Magentas, &selective_color.magentas), + (SelectiveColorGroup::Whites, &selective_color.whites), + (SelectiveColorGroup::Neutrals, &selective_color.neutrals), + (SelectiveColorGroup::Blacks, &selective_color.blacks), + ] + .map(|(group, inks)| { + let [c, m, y, k] = [inks.cyan, inks.magenta, inks.yellow, inks.black].map(|percent| percent as f32); + SelectiveColorGroupInks { + group, + cmyk: [c, m, y, k], + inks: [ink(c, k), ink(m, k), ink(y, k)], + } + }); + + visitor.visit(SelectiveColor { mode, groups }) + } + Adjustment::Posterize { levels } => visitor.visit(Posterize { levels: (*levels).max(2) as f32 }), + Adjustment::Exposure { exposure, offset, gamma_correction } => visitor.visit(Exposure { + exposure: *exposure as f32, + offset: *offset as f32, + gamma_correction: gamma_correction.max(0.0001) as f32, + }), + Adjustment::ColorBalance(color_balance) => { + let preserve_luminosity = color_balance.preserve_luminosity; + + // The derivation below is integer arithmetic, so the sliders round to whole percentages first + let shifts = |shifts: &settings::ColorBalanceShifts| [shifts.cyan_red, shifts.magenta_green, shifts.yellow_blue].map(|value| (value as f32).round() as i32); + let [s_r, s_g, s_b] = shifts(&color_balance.shadows); + let [m_r, m_g, m_b] = shifts(&color_balance.midtones); + let [h_r, h_g, h_b] = shifts(&color_balance.highlights); + + let s_max = s_r.max(s_g).max(s_b); + let m_max = m_r.max(m_g).max(m_b); + let m_min = m_r.min(m_g).min(m_b); + let h_min = h_r.min(h_g).min(h_b); + let red = color_balance_curve(s_r, m_r, h_r, s_max, m_max, m_min, h_min, preserve_luminosity); + let green = color_balance_curve(s_g, m_g, h_g, s_max, m_max, m_min, h_min, preserve_luminosity); + let blue = color_balance_curve(s_b, m_b, h_b, s_max, m_max, m_min, h_min, preserve_luminosity); + + visitor.visit(ColorBalance { red, green, blue }) + } + Adjustment::PhotoFilter { color, density, preserve_luminosity } => { + let density = (density / 100.) as f32; + + // The image is multiplied in XYZ by the filter color normalized to the white point, with density easing that multiplier toward 1 + let filter_xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [color.r(), color.g(), color.b()]); + let factor = [ + 1. + density * (filter_xyz[0] / WHITE_XYZ_D50[0] - 1.), + 1. + density * (filter_xyz[1] / WHITE_XYZ_D50[1] - 1.), + 1. + density * (filter_xyz[2] / WHITE_XYZ_D50[2] - 1.), + ]; + + visitor.visit(PhotoFilter { + factor, + preserve_luminosity: *preserve_luminosity, + }) + } + Adjustment::ColorLookup { lut_file } => match parse_cached(lut_file) { + Ok(lut) => visitor.visit(ColorLookup { lut }), + Err(_) => visitor.unchanged(), + }, + Adjustment::ColorOverlay { color, blend_mode, opacity } => visitor.visit(ColorOverlay { + color: *color, + blend_mode: *blend_mode, + opacity: (opacity / 100.) as f32, + }), + } +} + +struct Desaturate { + method: DesaturateMethod, +} + +impl MapColor for Desaturate { + fn map_cpu(&self, color: Color) -> Color { + // Gamma-encoded formulas are decoded as if they were a gray + let gamma = || color.to_gamma_srgb_channels(); + let luminance = match self.method { + DesaturateMethod::LuminanceRec709 => color.luminance_rec_709(), + DesaturateMethod::LumaRec709 => { + let [r, g, b, _] = gamma(); + srgb_to_linear(0.2126 * r + 0.7152 * g + 0.0722 * b) + } + DesaturateMethod::LumaRec601 => { + let [r, g, b, _] = gamma(); + srgb_to_linear(0.299 * r + 0.587 * g + 0.114 * b) + } + DesaturateMethod::LightnessOkLab => { + // A gray's OkLab lightness is the cube root of its linear value, so cubing gives the gray of equal lightness + let lightness = color.lightness_oklab(); + lightness * lightness * lightness + } + DesaturateMethod::ChannelsAverage => color.average_rgb_channels(), + DesaturateMethod::ChannelsMinimum => color.minimum_rgb_channels(), + DesaturateMethod::ChannelsMaximum => color.maximum_rgb_channels(), + DesaturateMethod::LightnessHsl => { + // The transfer curve is monotonic, so the extremes are found first and only they are encoded + let max = linear_to_srgb(color.maximum_rgb_channels()); + let min = linear_to_srgb(color.minimum_rgb_channels()); + srgb_to_linear((max + min) / 2.) + } + }; + color.map_rgb(|_| luminance) + } +} + +struct GammaCorrection { + exponent: f32, +} + +impl MapColor for GammaCorrection { + fn map_cpu(&self, color: Color) -> Color { + color.apply_gamma_exponent(self.exponent) + } +} + +struct MakeOpaque; + +impl MapColor for MakeOpaque { + fn map_cpu(&self, color: Color) -> Color { + color.with_alpha(1.) + } +} + +/// Remaps a gamma-space channel through the stages of a Levels adjustment: the input range, the midtones gamma, and the output range. +fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, inverse_gamma: f32, output_minimum: f32, output_maximum: f32) -> f32 { + let highlights_minus_shadows = (input_highlights - input_shadows).clamp(f32::EPSILON, 1.); + let value = ((value - input_shadows).max(0.) / highlights_minus_shadows).min(1.); + let value = value.powf(inverse_gamma); + + value * (output_maximum - output_minimum) + output_minimum +} + +/// The classic Brightness/Contrast algorithm: a Levels remap around the pivot, adding the brightness before a positive +/// contrast stretch and after a negative contrast squeeze. +fn brightness_contrast_classic(value: f32, brightness: f32, contrast: f32, pivot: f32) -> f32 { + // Full contrast is a hard step, sending values at the pivot or above to white (with half a 16-bit step of slack for float ties) + if contrast >= 1. { + return if value + brightness >= pivot - 1. / 65536. { 1. } else { 0. }; + } + + let result = if contrast > 0. { + let input_shadows = pivot * contrast - brightness; + apply_levels(value, input_shadows, input_shadows + 1. - contrast, 1., 0., 1.) + } else { + let output_minimum = brightness - pivot * contrast; + apply_levels(value, 0., 1., 1., output_minimum, output_minimum + 1. + contrast) + }; + + result.clamp(0., 1.) +} + +/// One brightness curve of the current algorithm, for a magnitude in 0..100: a line of slope 2^(b/110) up to an output of 0.5, +/// continued by a cubic Hermite segment that eases into (1, 1). +#[derive(Clone, Copy)] +struct BrightnessCurve { + slope: f32, + knee: f32, + end_slope: f32, +} + +impl BrightnessCurve { + fn new(brightness: f32) -> Self { + let slope = 2_f32.powf(brightness / 110.); + let knee = 0.5 / slope; + let end_slope = (1. / (1. + 12. * (slope - 1.))).max(0.1); + + Self { slope, knee, end_slope } + } + + /// Evaluates the Hermite segment at its parameter t in 0..1, returning the value and its derivative with respect to x. + fn hermite(&self, t: f32) -> (f32, f32) { + let length = 1. - self.knee; + let start_tangent = length * self.slope; + let end_tangent = length * self.end_slope; + let t2 = t * t; + let t3 = t2 * t; + + let value = (2. * t3 - 3. * t2 + 1.) * 0.5 + (t3 - 2. * t2 + t) * start_tangent + (-2. * t3 + 3. * t2) + (t3 - t2) * end_tangent; + let derivative = ((6. * t2 - 6. * t) * 0.5 + (3. * t2 - 4. * t + 1.) * start_tangent + (-6. * t2 + 6. * t) + (3. * t2 - 2. * t) * end_tangent) / length; + + (value, derivative) + } + + fn forward(&self, x: f32) -> f32 { + if x < self.knee { + return self.slope * x; + } + + let t = ((x - self.knee) / (1. - self.knee)).min(1.); + self.hermite(t).0.min(1.) + } + + /// Inverts the curve, solving the monotone Hermite segment with a bracketed Newton iteration. + fn inverse(&self, y: f32) -> f32 { + if y <= 0.5 { + return y / self.slope; + } + + let mut low = 0.; + let mut high = 1.; + let mut t = (y - 0.5) * 2.; + for _ in 0..8 { + let (value, derivative) = self.hermite(t); + let error = value - y; + if error > 0. { + high = t; + } else { + low = t; + } + + let step = t - error / (derivative * (1. - self.knee)); + t = if step >= low && step <= high { step } else { (low + high) * 0.5 }; + } + + self.knee + t * (1. - self.knee) + } +} + +struct BrightnessContrast { + use_classic: bool, + brightness: f32, + contrast: f32, + classic_pivot: f32, + first_curve: BrightnessCurve, + second_curve: BrightnessCurve, +} + +impl MapColor for BrightnessContrast { + fn map_cpu(&self, color: Color) -> Color { + color.map_gamma_rgb(|c| { + if self.use_classic { + return brightness_contrast_classic(c, self.brightness / 255., self.contrast, self.classic_pivot); + } + + // Negative brightness runs the same curves in reverse + let brightened = if self.brightness >= 0. { + self.second_curve.forward(self.first_curve.forward(c)) + } else { + self.first_curve.inverse(self.second_curve.inverse(c)) + }; + + // Contrast pushes away from (or pulls toward) the midpoint, most strongly at the quarter tones + let contrasted = brightened + 0.76 * self.contrast * (2. * brightened - 1.) * brightened.min(1. - brightened); + contrasted.clamp(0., 1.) + }) + } +} + +/// One Levels record in the node's units: percentage input and output points and the gamma value. +#[derive(Clone, Copy)] +struct LevelsRecord { + shadows: f32, + midtones: f32, + highlights: f32, + output_minimums: f32, + output_maximums: f32, +} + +/// A record's input curve followed by its output range. +#[derive(Clone, Copy)] +struct LevelsStage { + curve: LevelsCurve, + output_minimum: f32, + output_maximum: f32, +} + +impl LevelsRecord { + fn new(shadows: f32, midtones: f32, highlights: f32, output_minimums: f32, output_maximums: f32) -> Self { + Self { + shadows, + midtones, + highlights, + output_minimums, + output_maximums, + } + } + + fn stage(&self, gamma: f32) -> LevelsStage { + LevelsStage { + curve: LevelsCurve::from_points(self.shadows * 2.55, self.highlights * 2.55, gamma), + output_minimum: self.output_minimums / 100., + output_maximum: self.output_maximums / 100., + } + } +} + +impl LevelsStage { + fn apply(&self, value: f32) -> f32 { + self.curve.apply(value) * (self.output_maximum - self.output_minimum) + self.output_minimum + } +} + +/// A channel's record followed by the composite record. +#[derive(Clone, Copy)] +struct LevelsChain { + first: LevelsStage, + second: LevelsStage, + two_stages: bool, +} + +impl LevelsChain { + fn new(channel: LevelsRecord, composite: LevelsRecord) -> Self { + // For PSD interop, two power functions with nothing between them (the composite's input points and the + // channel's output range at their defaults) merge into one curve with the product of the gammas, toe included + let nothing_between = composite.shadows == 0. && composite.highlights == 100. && channel.output_minimums == 0. && channel.output_maximums == 100.; + if nothing_between { + let merged = LevelsRecord { + output_minimums: composite.output_minimums, + output_maximums: composite.output_maximums, + ..channel + }; + let stage = merged.stage(channel.midtones * composite.midtones); + Self { + first: stage, + second: stage, + two_stages: false, + } + } else { + Self { + first: channel.stage(channel.midtones), + second: composite.stage(composite.midtones), + two_stages: true, + } + } + } + + fn apply(&self, value: f32) -> f32 { + let value = self.first.apply(value); + if self.two_stages { self.second.apply(value) } else { value } + } +} + +struct Levels { + red: LevelsChain, + green: LevelsChain, + blue: LevelsChain, + alpha: LevelsStage, +} + +impl MapColor for Levels { + fn map_cpu(&self, color: Color) -> Color { + // Levels math operates in gamma space + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + Color::from_gamma_srgb_channels(self.red.apply(r), self.green.apply(g), self.blue.apply(b), self.alpha.apply(a)) + } +} + +struct Curves { + composite: TransferCurveEvaluator, + red: TransferCurveEvaluator, + green: TransferCurveEvaluator, + blue: TransferCurveEvaluator, + alpha: TransferCurveEvaluator, +} + +impl Curves { + fn apply(&self, [r, g, b, a]: [f32; 4]) -> [f32; 4] { + let map = |channel: &TransferCurveEvaluator, value: f32| self.composite.evaluate(channel.evaluate(value as f64).clamp(0., 1.)).clamp(0., 1.) as f32; + + // Alpha stands apart from the composite curve that the three color channels pass through + let a = self.alpha.evaluate(a as f64).clamp(0., 1.) as f32; + + [map(&self.red, r), map(&self.green, g), map(&self.blue, b), a] + } +} + +impl MapColor for Curves { + fn map_cpu(&self, color: Color) -> Color { + // Curves math operates in gamma space + let [r, g, b, a] = self.apply(color.to_gamma_srgb_channels()); + Color::from_gamma_srgb_channels(r, g, b, a) + } +} + +struct BlackAndWhite { + use_tint: bool, + tint: Color, + reds: f32, + yellows: f32, + greens: f32, + cyans: f32, + blues: f32, + magentas: f32, +} + +impl MapColor for BlackAndWhite { + fn map_cpu(&self, color: Color) -> Color { + let BlackAndWhite { + use_tint, + tint, + reds, + yellows, + greens, + cyans, + blues, + magentas, + } = *self; + + // Black & White channel weights are tuned for gamma-space values + let [r, g, b, alpha_part] = color.to_gamma_srgb_channels(); + + let gray_base = r.min(g).min(b); + + let red_part = r - gray_base; + let green_part = g - gray_base; + let blue_part = b - gray_base; + + let additional = if red_part == 0. { + let cyan_part = green_part.min(blue_part); + cyan_part * cyans + (green_part - cyan_part) * greens + (blue_part - cyan_part) * blues + } else if green_part == 0. { + let magenta_part = red_part.min(blue_part); + magenta_part * magentas + (red_part - magenta_part) * reds + (blue_part - magenta_part) * blues + } else { + let yellow_part = red_part.min(green_part); + yellow_part * yellows + (red_part - yellow_part) * reds + (green_part - yellow_part) * greens + }; + + let luminance = (gray_base + additional).clamp(0., 1.); + if !use_tint { + return Color::from_gamma_srgb_channels(luminance, luminance, luminance, alpha_part); + } + + // The tint takes on the gray's luminosity the way the Luminosity blend mode would + let [tint_r, tint_g, tint_b, _] = tint.to_gamma_srgb_channels(); + let tint_luma = luma_rec_601_fixed_point(tint_r, tint_g, tint_b); + let [tinted_r, tinted_g, tinted_b] = set_luminosity(tint_r, tint_g, tint_b, tint_luma, luminance); + + Color::from_gamma_srgb_channels(tinted_r, tinted_g, tinted_b, alpha_part) + } +} + +/// HSL of gamma-encoded channels: hue in degrees, saturation and lightness in 0..1. +fn gamma_rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { + let maximum = r.max(g).max(b); + let minimum = r.min(g).min(b); + let chroma = maximum - minimum; + let lightness = (maximum + minimum) / 2.; + if chroma <= 0. { + return [0., 0., lightness]; + } + + let saturation = chroma / (1. - (2. * lightness - 1.).abs()).max(1e-6); + [hexagon_hue_degrees(r, g, b), saturation.min(1.), lightness] +} + +/// Hexagon hue in degrees of three channels in any encoding, 0 for gray. +fn hexagon_hue_degrees(r: f32, g: f32, b: f32) -> f32 { + let maximum = r.max(g).max(b); + let chroma = maximum - r.min(g).min(b); + if chroma <= 0. { + return 0.; + } + + let sector = if maximum == r { + wrap_positive((g - b) / chroma, 6.) + } else if maximum == g { + (b - r) / chroma + 2. + } else { + (r - g) / chroma + 4. + }; + sector * 60. +} + +/// `value` wrapped into the range from 0 to `modulus`. +fn wrap_positive(value: f32, modulus: f32) -> f32 { + value - (value / modulus).floor() * modulus +} + +/// Gamma-encoded channels from a hue in degrees and saturation and lightness in 0..1. +fn hsl_to_gamma_rgb(hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { + let chroma = (1. - (2. * lightness - 1.).abs()) * saturation; + let sector = wrap_positive(hue, 360.) / 60.; + let x = chroma * (1. - (wrap_positive(sector, 2.) - 1.).abs()); + let (r, g, b) = if sector < 1. { + (chroma, x, 0.) + } else if sector < 2. { + (x, chroma, 0.) + } else if sector < 3. { + (0., chroma, x) + } else if sector < 4. { + (0., x, chroma) + } else if sector < 5. { + (x, 0., chroma) + } else { + (chroma, 0., x) + }; + let m = lightness - chroma / 2.; + + [(r + m).clamp(0., 1.), (g + m).clamp(0., 1.), (b + m).clamp(0., 1.)] +} + +/// One set of Hue/Saturation sliders: a hue shift in degrees and saturation and lightness amounts in -1..1. +#[derive(Clone, Copy)] +struct PreparedHueSaturationSliders { + hue: f32, + saturation: f32, + saturation_gain: f32, + lightness: f32, +} + +impl PreparedHueSaturationSliders { + fn new(hue: f32, saturation_percent: f32, lightness_percent: f32) -> Self { + let saturation = saturation_percent / 100.; + Self { + hue, + saturation, + saturation_gain: saturation_gain(saturation), + lightness: lightness_percent / 100., + } + } +} + +/// A hue range with its falloff: full weight from `range_start` to `range_end`, fading linearly to zero at the falloff ends. +#[derive(Clone, Copy)] +struct HueSaturationRangeSettings { + falloff_start: f32, + range_start: f32, + range_end: f32, + falloff_end: f32, + settings: PreparedHueSaturationSliders, +} + +impl HueSaturationRangeSettings { + fn new(falloff_start: f32, range_start: f32, range_end: f32, falloff_end: f32, settings: PreparedHueSaturationSliders) -> Self { + // For PSD interop, each edge rounds to 1536 hue units per turn over 359 rather than 360 degrees, landing up to a degree late + let edge = |degrees: f32| (degrees * 1536. / 359.).round() * 360. / 1536.; + + Self { + falloff_start: edge(falloff_start), + range_start: edge(range_start), + range_end: edge(range_end), + falloff_end: edge(falloff_end), + settings, + } + } + + fn weight(&self, hue: f32) -> f32 { + let distance = |from: f32, to: f32| wrap_positive(to - from, 360.); + if distance(self.range_start, hue) <= distance(self.range_start, self.range_end) { + return 1.; + } + let start_falloff = distance(self.falloff_start, self.range_start); + let end_falloff = distance(self.range_end, self.falloff_end); + if distance(self.falloff_start, hue) < start_falloff { + return distance(self.falloff_start, hue) / start_falloff; + } + if distance(self.range_end, hue) < end_falloff { + return 1. - distance(self.range_end, hue) / end_falloff; + } + 0. + } +} + +/// The six ranges' combined effect on one pixel, gathered before the master sliders apply. +struct HueSaturationRangeEffect { + hue_shift: f32, + saturation_factor: f32, + fully_saturate: bool, + rgb: [f32; 3], +} + +impl HueSaturationRangeEffect { + fn apply(&mut self, range: &HueSaturationRangeSettings, original_hue: f32, original_saturation: f32) { + // Range weights come from the original hue, and grays belong to no range + let weight = if original_saturation > 0. { range.weight(original_hue) } else { 0. }; + if weight <= 0. { + return; + } + + self.hue_shift += range.settings.hue * weight; + // For PSD interop, +100 saturates fully from the very edge of the falloff rather than scaling with the weight + if range.settings.saturation >= 1. { + self.fully_saturate = true; + } else { + self.saturation_factor *= 1. + (range.settings.saturation_gain - 1.) * weight; + } + self.rgb = lightness_toward_max_or_min(self.rgb, range.settings.lightness * weight); + } +} + +/// The factor a saturation amount in -1..1 applies to HSL saturation, quantized for PSD interop: 1 - trunc(256 a) / 256 below zero and floor(65280 / (255 - trunc(254 a))) / 256 above. +fn saturation_gain(amount: f32) -> f32 { + if amount < 0. { + 1. - (-amount * 256.).trunc() / 256. + } else { + (65280. / (255. - (amount * 254.).trunc())).floor() / 256. + } +} + +/// Blends toward white for a positive amount and toward black for a negative one, as the master lightness slider does. +fn lightness_toward_white_or_black(value: f32, amount: f32) -> f32 { + if amount >= 0. { value + (1. - value) * amount } else { value * (1. + amount) } +} + +/// A range's lightness moves the channels toward the color's own maximum (positive) or minimum (negative) instead. +fn lightness_toward_max_or_min(rgb: [f32; 3], amount: f32) -> [f32; 3] { + let maximum = rgb[0].max(rgb[1]).max(rgb[2]); + let minimum = rgb[0].min(rgb[1]).min(rgb[2]); + let toward = if amount >= 0. { maximum } else { minimum }; + let blend = |value: f32| value + (toward - value) * amount.abs(); + [blend(rgb[0]), blend(rgb[1]), blend(rgb[2])] +} + +struct HueSaturation { + master: PreparedHueSaturationSliders, + colorize: bool, + colorize_settings: PreparedHueSaturationSliders, + reds: HueSaturationRangeSettings, + yellows: HueSaturationRangeSettings, + greens: HueSaturationRangeSettings, + cyans: HueSaturationRangeSettings, + blues: HueSaturationRangeSettings, + magentas: HueSaturationRangeSettings, +} + +impl MapColor for HueSaturation { + fn map_cpu(&self, color: Color) -> Color { + let Self { + master, + colorize, + colorize_settings, + reds, + yellows, + greens, + cyans, + blues, + magentas, + } = *self; + let [r, g, b, alpha] = color.to_gamma_srgb_channels(); + + if colorize { + let [_, _, lightness] = gamma_rgb_to_hsl(r, g, b); + let lightness = lightness_toward_white_or_black(lightness, colorize_settings.lightness); + let [r, g, b] = hsl_to_gamma_rgb(colorize_settings.hue, colorize_settings.saturation, lightness); + return Color::from_gamma_srgb_channels(r, g, b, alpha); + } + + // Each range weights its sliders by its falloff around the original hue: hue shifts add and saturation gains multiply + let [original_hue, original_saturation, _] = gamma_rgb_to_hsl(r, g, b); + let mut effect = HueSaturationRangeEffect { + hue_shift: master.hue, + saturation_factor: 1., + fully_saturate: false, + rgb: [r, g, b], + }; + effect.apply(&reds, original_hue, original_saturation); + effect.apply(&yellows, original_hue, original_saturation); + effect.apply(&greens, original_hue, original_saturation); + effect.apply(&cyans, original_hue, original_saturation); + effect.apply(&blues, original_hue, original_saturation); + effect.apply(&magentas, original_hue, original_saturation); + let HueSaturationRangeEffect { + hue_shift, + mut saturation_factor, + mut fully_saturate, + rgb, + } = effect; + if master.saturation >= 1. { + fully_saturate = true; + } else { + saturation_factor *= master.saturation_gain; + } + + // The master lightness blends toward white or black before the hue and saturation, which work in HSL of the gamma channels + let rgb = [ + lightness_toward_white_or_black(rgb[0], master.lightness), + lightness_toward_white_or_black(rgb[1], master.lightness), + lightness_toward_white_or_black(rgb[2], master.lightness), + ]; + let [hue, saturation, lightness] = gamma_rgb_to_hsl(rgb[0], rgb[1], rgb[2]); + let saturation = if saturation <= 0. { + 0. + } else if fully_saturate { + 1. + } else { + (saturation * saturation_factor).min(1.) + }; + let [r, g, b] = hsl_to_gamma_rgb(hue + hue_shift, saturation, lightness); + + Color::from_gamma_srgb_channels(r, g, b, alpha) + } +} + +struct Invert; + +impl MapColor for Invert { + fn map_cpu(&self, color: Color) -> Color { + color.map_gamma_rgb(|channel| 1. - channel) + } +} + +struct Threshold { + min_luminance: f32, + max_luminance: f32, +} + +impl MapColor for Threshold { + fn map_cpu(&self, color: Color) -> Color { + // For PSD interop, we compare this 14-bit fixed-point Rec. 601 luma against the level unrounded + let [r, g, b, _] = color.to_gamma_srgb_channels(); + let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.; + + let output = if luminance >= self.min_luminance && luminance <= self.max_luminance { + Color::WHITE + } else { + Color::BLACK + }; + output.with_alpha(color.a()) + } +} + +struct GradientMap { + evaluator: GradientEvaluator, + reverse: bool, +} + +impl MapColor for GradientMap { + fn map_cpu(&self, color: Color) -> Color { + // The classic 0.3/0.59/0.11 luma of the gamma-encoded channels picks the position along the gradient + let [r, g, b, alpha] = color.to_gamma_srgb_channels(); + let intensity = 0.3 * r + 0.59 * g + 0.11 * b; + let intensity = if self.reverse { 1. - intensity } else { intensity }; + + // The source alpha is kept and the gradient's own alpha stops are ignored + self.evaluator.evaluate(intensity as f64).with_alpha(alpha) + } +} + +struct Vibrance { + vibrance: f32, + saturation_scale: f32, +} + +impl MapColor for Vibrance { + fn map_cpu(&self, color: Color) -> Color { + // Vibrance then saturation, both in linear light, which equals applying each alone in turn + let (r, g, b) = (color.r(), color.g(), color.b()); + let maximum = r.max(g).max(b); + let [chroma_factor, brightness_factor] = vibrance_factors(r, g, b, self.vibrance); + let after_vibrance = Color::from_rgbaf32_unchecked( + scale_about_maximum(r, maximum, chroma_factor, brightness_factor), + scale_about_maximum(g, maximum, chroma_factor, brightness_factor), + scale_about_maximum(b, maximum, chroma_factor, brightness_factor), + color.a(), + ); + + // For PSD interop, saturation scales each channel's distance from a gray weighted by ProPhoto's luminance coefficients + let gray = 0.288040 * after_vibrance.r() + 0.711874 * after_vibrance.g() + 0.000086 * after_vibrance.b(); + after_vibrance.map_rgb(|c| (gray + (c - gray) * self.saturation_scale).clamp(0., 1.)) + } +} + +fn scale_about_maximum(channel: f32, maximum: f32, chroma_factor: f32, brightness_factor: f32) -> f32 { + (brightness_factor * (maximum + chroma_factor * (channel - maximum))).clamp(0., 1.) +} + +/// Share of the vibrance boost the skin-tone protection removes at full weight, a fitted constant. +const VIBRANCE_PROTECTION_LOSS: f32 = 0.4857; + +/// Vibrance on linear SDR channels as `[chroma factor about the max, brightness multiply]` for an amount in -1..1, both fading out toward black. +/// Negative desaturates and darkens low-chroma colors most. Positive boosts them, brightens a little, and spares reds. +fn vibrance_factors(r: f32, g: f32, b: f32, amount: f32) -> [f32; 2] { + let maximum = r.max(g).max(b); + let minimum = r.min(g).min(b); + if maximum <= 0. { + return [1., 1.]; + } + let ratio = minimum / maximum; + let saturation = 1. - ratio; + let q = ratio * saturation; + let toe = 1. - (16. * maximum).min(1.); + let rolloff = 1. - toe * toe; + let brightness = (2. * q - q * q) * (1. - maximum) * rolloff; + + if amount < 0. { + let amount = -amount; + let chroma_factor = (1. - amount / 4.) * (1. - amount * (1. - rolloff * saturation * (1. + saturation) / 2.)); + return [chroma_factor, 1. - amount * brightness]; + } + + let protection = skin_tone_window(hexagon_hue_degrees(r, g, b)) * (1. - saturation * saturation); + let amount = amount * (1. - protection * (1. - amount)); + let boost = (5. / 6.) * (1. - VIBRANCE_PROTECTION_LOSS * protection) * amount * ratio * (1. - minimum) * rolloff; + [1. / (1. - boost), 1. + amount * brightness / 4.] +} + +/// How fully a hue falls under the skin-tone protection: all of it from red to 30 degrees, fading out by 45, and back in from 300. +fn skin_tone_window(hue: f32) -> f32 { + if hue < 45. { + ((45. - hue) / 15.).min(1.) + } else if hue >= 300. { + (hue - 300.) / 60. + } else { + 0. + } +} + +struct ChannelMixer { + monochrome: bool, + monochrome_r: f32, + monochrome_g: f32, + monochrome_b: f32, + monochrome_c: f32, + red_r: f32, + red_g: f32, + red_b: f32, + red_c: f32, + green_r: f32, + green_g: f32, + green_b: f32, + green_c: f32, + blue_r: f32, + blue_g: f32, + blue_b: f32, + blue_c: f32, +} + +impl MapColor for ChannelMixer { + fn map_cpu(&self, color: Color) -> Color { + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + let (out_r, out_g, out_b) = if self.monochrome { + let gray = (r * self.monochrome_r + g * self.monochrome_g + b * self.monochrome_b + self.monochrome_c).clamp(0., 1.); + + (gray, gray, gray) + } else { + let red = (r * self.red_r + g * self.red_g + b * self.red_b + self.red_c).clamp(0., 1.); + let green = (r * self.green_r + g * self.green_g + b * self.green_b + self.green_c).clamp(0., 1.); + let blue = (r * self.blue_r + g * self.blue_g + b * self.blue_b + self.blue_c).clamp(0., 1.); + + (red, green, blue) + }; + + Color::from_gamma_srgb_channels(out_r, out_g, out_b, a) + } +} + +/// The groups of colors that Selective Color adjusts, in the order of its settings. +#[derive(Clone, Copy)] +enum SelectiveColorGroup { + Reds, + Yellows, + Greens, + Cyans, + Blues, + Magentas, + Whites, + Neutrals, + Blacks, +} + +/// A group's cyan, magenta, yellow, and black percentages, with the inks they combine into for each of red, green, and blue. +#[derive(Clone, Copy)] +struct SelectiveColorGroupInks { + group: SelectiveColorGroup, + cmyk: [f32; 4], + inks: [f32; 3], +} + +struct SelectiveColor { + mode: RelativeAbsolute, + groups: [SelectiveColorGroupInks; 9], +} + +impl MapColor for SelectiveColor { + fn map_cpu(&self, color: Color) -> Color { + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + let min = |a: f32, b: f32, c: f32| a.min(b).min(c); + let max = |a: f32, b: f32, c: f32| a.max(b).max(c); + let med = |a: f32, b: f32, c: f32| a + b + c - min(a, b, c) - max(a, b, c); + + let max_channel = max(r, g, b); + let min_channel = min(r, g, b); + + let pixel_color_range = |group| match group { + SelectiveColorGroup::Reds => max_channel == r, + SelectiveColorGroup::Yellows => min_channel == b, + SelectiveColorGroup::Greens => max_channel == g, + SelectiveColorGroup::Cyans => min_channel == r, + SelectiveColorGroup::Blues => max_channel == b, + SelectiveColorGroup::Magentas => min_channel == g, + SelectiveColorGroup::Whites => r > 0.5 && g > 0.5 && b > 0.5, + // Every pixel, since the neutrals scale factor already vanishes at black, white, and fully saturated colors + SelectiveColorGroup::Neutrals => true, + SelectiveColorGroup::Blacks => r < 0.5 && g < 0.5 && b < 0.5, + }; + + let color_parameter_group_scale_factor_rgb = max(r, g, b) - med(r, g, b); + let color_parameter_group_scale_factor_cmy = med(r, g, b) - min(r, g, b); + + // Used to apply the r, g, or b channel slope (by multiplying it by 1) in relative mode, or no slope (by multiplying it by 0) in absolute mode + let (slope_r, slope_g, slope_b) = match self.mode { + RelativeAbsolute::Relative => (r - 1., g - 1., b - 1.), + RelativeAbsolute::Absolute => (-1., -1., -1.), + }; + + let mut sum = Vec3::ZERO; + for SelectiveColorGroupInks { + group, + cmyk: [c, m, y, k], + inks: [ink_c, ink_m, ink_y], + } in self.groups + { + // Skip this group if it's left at zero or this pixel's color isn't in the range it affects + if (c == 0. && m == 0. && y == 0. && k == 0.) || !pixel_color_range(group) { + continue; + } + + let color_parameter_group_scale_factor = match group { + SelectiveColorGroup::Reds | SelectiveColorGroup::Greens | SelectiveColorGroup::Blues => color_parameter_group_scale_factor_rgb, + SelectiveColorGroup::Cyans | SelectiveColorGroup::Magentas | SelectiveColorGroup::Yellows => color_parameter_group_scale_factor_cmy, + SelectiveColorGroup::Whites => min(r, g, b) * 2. - 1., + SelectiveColorGroup::Neutrals => 1. - ((max(r, g, b) - 0.5).abs() + (min(r, g, b) - 0.5).abs()), + SelectiveColorGroup::Blacks => 1. - max(r, g, b) * 2., + }; + + let offset_r = (ink_c * slope_r).max(-r).min(-r + 1.) * color_parameter_group_scale_factor; + let offset_g = (ink_m * slope_g).max(-g).min(-g + 1.) * color_parameter_group_scale_factor; + let offset_b = (ink_y * slope_b).max(-b).min(-b + 1.) * color_parameter_group_scale_factor; + + // An 8-bit PSD document sums the groups' 8-bit offsets, which this float node does not currently attempt to reproduce + sum += Vec3::new(offset_r, offset_g, offset_b); + } + + let rgb = Vec3::new(r, g, b); + let out = (sum + rgb).clamp(Vec3::ZERO, Vec3::ONE); + + Color::from_gamma_srgb_channels(out.x, out.y, out.z, a) + } +} + +struct Posterize { + levels: f32, +} + +impl MapColor for Posterize { + fn map_cpu(&self, color: Color) -> Color { + let levels = self.levels; + + color.map_gamma_rgb(|c| { + // Bins as floor(c * levels) with the outputs spread evenly to white. + // The sliver of slack keeps an input exactly on an edge in the upper bin despite float ties. + let bin = ((c + 2e-7) * levels).floor().min(levels - 1.); + bin / (levels - 1.) + }) + } +} + +struct Exposure { + exposure: f32, + offset: f32, + gamma_correction: f32, +} + +impl MapColor for Exposure { + fn map_cpu(&self, color: Color) -> Color { + // Linearizes with a 2.2 power above a straight toe of slope 1/32, the two meeting at this constant + const TOE_END: f32 = 0.05568117; // 32^(-1. / 1.2) + + let decode = |value: f32| if value < TOE_END { value / 32. } else { value.powf(2.2) }; + let encode = |linear: f32| if linear < TOE_END / 32. { linear * 32. } else { linear.powf(1. / 2.2) }; + let adjust = |c: f32| { + let linear = decode(c) * 2_f32.powf(self.exposure) + self.offset; + encode(linear.max(0.).powf(1. / self.gamma_correction).min(1.)) + }; + + let [r, g, b, a] = color.to_gamma_srgb_channels(); + Color::from_gamma_srgb_channels(adjust(r), adjust(g), adjust(b), a) + } +} + +/// A Levels-style tone curve: input black and white points on a 0..255 scale and a gamma exponent. For gamma above 1 the +/// power curve's slope is unbounded at black, so a cubic toe holds it to 2^gamma until past where that line meets the curve. +#[derive(Debug, Clone, Copy)] +struct LevelsCurve { + black: f32, + white: f32, + exponent: f32, + toe_end: f32, + toe_value: f32, + toe_slope_start: f32, + toe_slope_end: f32, +} + +impl LevelsCurve { + fn new(black: i32, white: i32, gamma: f32) -> Self { + Self::from_points(black as f32, white as f32, gamma) + } + + /// `gamma` is the Levels dialog value (pixel exponent 1/gamma). + fn from_points(black: f32, white: f32, gamma: f32) -> Self { + let gamma = gamma.max(0.01); + let black = black.min(white - 1.); + let exponent = 1. / gamma; + + let mut curve = Self { + black, + white, + exponent, + toe_end: 0., + toe_value: 0., + toe_slope_start: 0., + toe_slope_end: 0., + }; + if gamma > 1. { + let slope = 2_f32.powf(gamma); + let intersection = 255. * slope.powf(-1. / (1. - exponent)); + // The cubic toe joins the power curve at twice the intersection + if intersection > 1e-3 { + let toe_end = 2. * intersection; + curve.toe_end = toe_end; + curve.toe_value = 255. * (toe_end / 255.).powf(exponent); + curve.toe_slope_start = slope; + curve.toe_slope_end = exponent * (toe_end / 255.).powf(exponent - 1.); + } + } + curve + } + + /// Maps one gamma-space channel value in 0..1. + fn apply(&self, value: f32) -> f32 { + let t = ((value * 255. - self.black) * 255. / (self.white - self.black)).clamp(0., 255.); + let y = if t < self.toe_end { + let u = t / self.toe_end; + let hermite_start = u * u * u - 2. * u * u + u; + let hermite_end_value = 3. * u * u - 2. * u * u * u; + let hermite_end_slope = u * u * u - u * u; + hermite_start * self.toe_end * self.toe_slope_start + hermite_end_value * self.toe_value + hermite_end_slope * self.toe_end * self.toe_slope_end + } else { + 255. * (t / 255.).powf(self.exponent) + }; + y / 255. + } +} + +/// One channel's Levels parameters from its own slider values, and (with preserve_luminosity) the slider +/// extremes across all three channels. The halvings truncate toward zero, as PSD interop requires. +#[allow(clippy::too_many_arguments)] +fn color_balance_curve(s: i32, m: i32, h: i32, s_max: i32, m_max: i32, m_min: i32, h_min: i32, preserve_luminosity: bool) -> LevelsCurve { + let (black, white, tone) = if preserve_luminosity { + (s_max - s, 255 - (h - h_min), m - (m_max + m_min) / 2) + } else { + (0.max(-s), 255 - 0.max(h), (s + h) / 2 + m) + }; + + // Rounding the derived gamma to hundredths, the precision of a PSD Levels record, is needed for compatible results + let gamma = (2_f32.powf(tone as f32 / 100.) * 100.).round() / 100.; + LevelsCurve::new(black, white, gamma) +} + +struct ColorBalance { + red: LevelsCurve, + green: LevelsCurve, + blue: LevelsCurve, +} + +impl MapColor for ColorBalance { + fn map_cpu(&self, color: Color) -> Color { + // The curves operate on gamma-space channel values + let [r, g, b, a] = color.to_gamma_srgb_channels(); + Color::from_gamma_srgb_channels(self.red.apply(r), self.green.apply(g), self.blue.apply(b), a) + } +} + +struct PhotoFilter { + factor: [f32; 3], + preserve_luminosity: bool, +} + +impl MapColor for PhotoFilter { + fn map_cpu(&self, pixel: Color) -> Color { + let PhotoFilter { factor, preserve_luminosity } = *self; + + let [r_in, g_in, b_in, alpha] = pixel.to_gamma_srgb_channels(); + let xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [srgb_to_linear(r_in), srgb_to_linear(g_in), srgb_to_linear(b_in)]); + let filtered = multiply_matrix(&XYZ_D50_TO_SRGB, [xyz[0] * factor[0], xyz[1] * factor[1], xyz[2] * factor[2]]); + let mut r = linear_to_srgb(filtered[0].clamp(0., 1.)); + let mut g = linear_to_srgb(filtered[1].clamp(0., 1.)); + let mut b = linear_to_srgb(filtered[2].clamp(0., 1.)); + + if preserve_luminosity { + let luma_in = luma_rec_601_fixed_point(r_in.clamp(0., 1.), g_in.clamp(0., 1.), b_in.clamp(0., 1.)); + [r, g, b] = set_luminosity(r, g, b, luma_rec_601_fixed_point(r, g, b), luma_in); + } + + Color::from_gamma_srgb_channels(r, g, b, alpha) + } +} + +// sRGB colorants adapted to D50 as in the sRGB IEC61966-2.1 ICC profile, row major, and their inverse +pub(crate) const SRGB_TO_XYZ_D50: [[f32; 3]; 3] = [[0.43607, 0.38515, 0.14307], [0.22249, 0.71687, 0.06061], [0.01392, 0.09708, 0.71410]]; +pub(crate) const XYZ_D50_TO_SRGB: [[f32; 3]; 3] = [[3.134096, -1.6174, -0.490638], [-0.978793, 1.916295, 0.033454], [0.071971, -0.228987, 1.40538]]; +pub(crate) const WHITE_XYZ_D50: [f32; 3] = [0.96420, 1., 0.82491]; + +pub(crate) fn multiply_matrix(matrix: &[[f32; 3]; 3], vector: [f32; 3]) -> [f32; 3] { + [ + matrix[0][0] * vector[0] + matrix[0][1] * vector[1] + matrix[0][2] * vector[2], + matrix[1][0] * vector[0] + matrix[1][1] * vector[1] + matrix[1][2] * vector[2], + matrix[2][0] * vector[0] + matrix[2][1] * vector[1] + matrix[2][2] * vector[2], + ] +} + +/// The Rec. 601 luma in the 14-bit fixed point that PSD interop depends on. +fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { + (4915. * r + 9667. * g + 1802. * b) / 16384. +} + +struct ColorLookup { + lut: Arc, +} + +impl MapColor for ColorLookup { + fn map_cpu(&self, color: Color) -> Color { + // Lookup tables address the gamma-encoded channels + let [r, g, b, a] = color.to_gamma_srgb_channels(); + let [r, g, b] = self.lut.apply([r, g, b]); + + Color::from_gamma_srgb_channels(r, g, b, a) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const COLORS: [Color; 2] = [Color::from_rgbaf32_unchecked(0.2, 0.5, 0.9, 1.), Color::from_rgbaf32_unchecked(1., 0., 0.3, 0.5)]; + + #[test] + fn a_prepared_adjustment_matches_preparing_it_for_each_color() { + let adjustments = [ + Adjustment::Invert, + Adjustment::Posterize { levels: 3 }, + Adjustment::Exposure { + exposure: 1., + offset: 0.1, + gamma_correction: 1.2, + }, + ]; + + for adjustment in &adjustments { + let prepared = PreparedAdjustment::new(adjustment); + for color in COLORS { + assert_eq!(prepared.adjust(color), adjust_color(adjustment, color), "{adjustment:?}"); + } + } + } + + #[test] + fn settings_past_their_bounds_stay_finite() { + let adjustments = [ + Adjustment::Posterize { levels: 1 }, + Adjustment::GammaCorrection { gamma: 0., inverse: true }, + Adjustment::Exposure { + exposure: 0., + offset: 0., + gamma_correction: 0., + }, + ]; + + for adjustment in &adjustments { + for color in COLORS { + let adjusted = adjust_color(adjustment, color); + assert!([adjusted.r(), adjusted.g(), adjusted.b(), adjusted.a()].iter().all(|channel| channel.is_finite()), "{adjustment:?}"); + } + } + } +} diff --git a/node-graph/libraries/raster-kernels/src/blending.rs b/node-graph/libraries/raster-kernels/src/blending.rs new file mode 100644 index 00000000000..db8ec6920ef --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/blending.rs @@ -0,0 +1,20 @@ +//! The kernels blending one color with another. + +use crate::MapColor; +use core_types::Color; +use core_types::blending::{BlendMode, apply_blend_mode}; + +pub(crate) struct ColorOverlay { + pub(crate) color: Color, + pub(crate) blend_mode: BlendMode, + pub(crate) opacity: f32, +} + +impl MapColor for ColorOverlay { + fn map_cpu(&self, pixel: Color) -> Color { + let overlay = apply_blend_mode(self.color, pixel, self.blend_mode); + let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity; + + Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a()) + } +} diff --git a/node-graph/nodes/raster/src/color_lookup_table.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs similarity index 85% rename from node-graph/nodes/raster/src/color_lookup_table.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table.rs index 06362d32d70..0efa48b9fe7 100644 --- a/node-graph/nodes/raster/src/color_lookup_table.rs +++ b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs @@ -8,35 +8,60 @@ mod format_look; use crate::adjustments::{SRGB_TO_XYZ_D50, WHITE_XYZ_D50, XYZ_D50_TO_SRGB, multiply_matrix}; use core_types::color::{linear_to_srgb, srgb_to_linear}; -use graphene_resource::{Resource, ResourceHash}; -use std::sync::{Arc, Mutex, PoisonError}; +use graphene_resource::{Resource, ResourceHash, WeakResource}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"]; /// A file's parse result, in the form the cache shares out. type ParsedLut = Result, LutParseError>; -/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again. -#[derive(Debug, Clone, Default)] -pub struct LutCache(Arc>>); - -impl LutCache { - /// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same. - pub fn parse(&self, resource: &Resource) -> ParsedLut { - // A lock poisoned by a panic elsewhere still guards a usable cache - let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner); - - let hash = resource.hash(); - if let Some((cached_hash, result)) = cached.as_ref() - && *cached_hash == hash - { - return result.clone(); +/// A parse result, kept while the file it came from is still loaded somewhere. +struct ParsedFile { + hash: ResourceHash, + file: WeakResource, + parsed: ParsedLut, +} + +/// The parse results of the files that are still loaded, shared by every adjustment that reads a lookup table. +static PARSED_FILES: Mutex> = Mutex::new(Vec::new()); + +fn parsed_files() -> MutexGuard<'static, Vec> { + // A lock poisoned by a panic elsewhere still guards a usable cache + PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// [`Lut::parse`] for a resource, reusing the result for as long as a file with the same content hash stays loaded. O(n) in the loaded files. +pub fn parse_cached(resource: &Resource) -> ParsedLut { + let hash = resource.hash(); + + { + let mut parsed_files = parsed_files(); + + // Follows the copy in hand before pruning, in case another copy of the same content is the one that went away + let cached = parsed_files.iter_mut().find(|entry| entry.hash == hash).map(|entry| { + entry.file = resource.downgrade(); + entry.parsed.clone() + }); + parsed_files.retain(|entry| entry.file.is_alive()); + + if let Some(parsed) = cached { + return parsed; } + } + + // Parsed outside the lock, so a large file doesn't hold up the adjustments reading other files + let parsed = Lut::parse(resource).map(Arc::new); - let result = Lut::parse(resource).map(Arc::new); - *cached = Some((hash, result.clone())); - result + let mut parsed_files = parsed_files(); + if !parsed_files.iter().any(|entry| entry.hash == hash) { + parsed_files.push(ParsedFile { + hash, + file: resource.downgrade(), + parsed: parsed.clone(), + }); } + parsed } /// Why a file could not be read as a lookup table. @@ -423,18 +448,20 @@ mod tests { } #[test] - fn a_cache_parses_a_file_once_until_the_file_changes() { - let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec()); - let cache = LutCache::default(); - let first = cache.parse(&file).unwrap(); - assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap())); - - // A cloned node shares its cache - assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap())); - - // Another file takes its place, a failed one included - assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err()); - assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap())); + fn the_cache_parses_a_file_once_while_it_stays_loaded() { + let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec()); + let first = parse_cached(&file).unwrap(); + + // Any number of other files, failed ones included, leave it in place + let others: Vec = (0..20).map(|index| Resource::new(format!("not a table {index}").into_bytes())).collect(); + others.iter().for_each(|other| assert!(parse_cached(other).is_err())); + assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap())); + + // Once no copy of it is loaded, parsing another file clears it out + let content = file.to_vec(); + drop(file); + assert!(parse_cached(&Resource::new(b"not a table either".to_vec())).is_err()); + assert!(!Arc::ptr_eq(&first, &parse_cached(&Resource::new(content)).unwrap())); } #[test] diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_3dl.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_3dl.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_3dl.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_3dl.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_csp.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_csp.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_csp.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_csp.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_cube.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_cube.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_cube.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_cube.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_icc.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_icc.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_icc.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_icc.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_look.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_look.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_look.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_look.rs diff --git a/node-graph/libraries/raster-kernels/src/effect_kernels.rs b/node-graph/libraries/raster-kernels/src/effect_kernels.rs new file mode 100644 index 00000000000..ba76a316457 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/effect_kernels.rs @@ -0,0 +1,465 @@ +//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting. +//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas. + +use raster_types::parallel_rows::fill_rows; + +/// Blurs and spreads shorter than this, in pixels, leave no visible trace. +pub const NEGLIGIBLE_LENGTH: f64 = 0.01; + +/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy. +pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.; + +/// The largest box or tent half width, in pixels, convolved on the image itself rather than a halved copy. +pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.; + +/// The farthest texel from the center a kernel weighs, which fits every direct limit. +pub const MAX_KERNEL_REACH: usize = 24; + +/// The most times an image is halved for a blur, by which point it is one pixel across. +const MAX_LEVELS: u32 = 16; + +/// A blur's kernel along one axis, sized in pixels. +#[derive(Clone, Copy, Debug)] +pub enum BlurKernel { + Gaussian { + sigma: f64, + }, + Box { + radius: f64, + }, + /// Weighs each texel by how far short of `radius` it lies, the shape of two box blurs of that width in a row. + Tent { + radius: f64, + }, +} + +impl BlurKernel { + /// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`]. + pub fn levels(self) -> u32 { + let (length, direct_limit) = match self { + Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA), + Self::Box { radius } | Self::Tent { radius } => (radius, MAX_DIRECT_BOX_RADIUS), + }; + + (length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32 + } + + /// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1. + pub fn weights(self, levels: u32) -> Vec { + let level_scale = (1 << levels) as f64; + + let weights: Vec = match self { + Self::Gaussian { sigma } => { + // Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance + let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.; + let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale; + if sigma < NEGLIGIBLE_LENGTH { + return vec![1.]; + } + + let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH); + (0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect() + } + // The texels at the ends weigh only the fraction of them the box covers, so the blur grows smoothly with its radius + Self::Box { radius } => { + let radius = radius / level_scale; + let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH); + (0..=reach).map(|i| (radius + 1. - i as f64).clamp(0., 1.)).collect() + } + Self::Tent { radius } => { + let radius = radius / level_scale; + if radius <= 1. { + return vec![1.]; + } + + let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH); + (0..=reach).map(|i| (radius - i as f64).max(0.)).collect() + } + }; + + let total = weights[0] + 2. * weights[1..].iter().sum::(); + weights.into_iter().map(|weight| weight / total).collect() + } +} + +/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels. +pub trait Sample: Copy + Default + Send + Sync { + fn scaled(self, factor: f32) -> Self; + fn plus(self, other: Self) -> Self; + fn max(self, other: Self) -> Self; +} + +impl Sample for f32 { + fn scaled(self, factor: f32) -> Self { + self * factor + } + fn plus(self, other: Self) -> Self { + self + other + } + fn max(self, other: Self) -> Self { + f32::max(self, other) + } +} + +impl Sample for [f32; 4] { + fn scaled(self, factor: f32) -> Self { + self.map(|channel| channel * factor) + } + fn plus(self, other: Self) -> Self { + std::array::from_fn(|channel| self[channel] + other[channel]) + } + fn max(self, other: Self) -> Self { + std::array::from_fn(|channel| self[channel].max(other[channel])) + } +} + +/// An image of [`Sample`]s in rows, which the operations read and write. +#[derive(Clone, Debug, PartialEq)] +pub struct Plane { + pub width: usize, + pub height: usize, + pub data: Vec, +} + +impl Plane { + pub fn new(width: usize, height: usize) -> Self { + Self { + width, + height, + data: vec![T::default(); width * height], + } + } + + /// A plane of the same size whose pixels are `map` of this one's. + pub fn map(&self, map: impl Fn(T) -> U + Sync) -> Plane { + let mut mapped = Plane::new(self.width, self.height); + fill_rows(&mut mapped.data, self.width, |y, row| { + let source = &self.data[y * self.width..(y + 1) * self.width]; + row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value)); + }); + mapped + } + + /// Combines this plane with `other`, of the same size, pixel by pixel. + pub fn zip(&self, other: &Plane, combine: impl Fn(T, U) -> V + Sync) -> Plane { + let mut combined = Plane::new(self.width, self.height); + fill_rows(&mut combined.data, self.width, |y, row| { + let range = y * self.width..(y + 1) * self.width; + let pairs = self.data[range.clone()].iter().zip(&other.data[range]); + row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b)); + }); + combined + } + + /// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height). + fn transposed(&self) -> Self { + let mut transposed = Self::new(self.height, self.width); + fill_rows(&mut transposed.data, self.height, |x, row| { + row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]); + }); + transposed + } + + /// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels. + fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self { + let mut result = Self::new(width, self.height); + fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row)); + result + } + + /// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back. + fn along_both_axes

(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self { + let plane = along_rows(self, horizontal); + along_rows(plane.transposed(), vertical).transposed() + } + + /// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times + /// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling. + pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self { + self.along_both_axes(horizontal, vertical, |mut plane, kernel| { + let levels = kernel.levels(); + let length = plane.width; + let level_length = |level: u32| length.div_ceil(1 << level); + + for level in 1..=levels { + plane = plane.map_rows(level_length(level), halve_row); + } + + let weights = kernel.weights(levels); + plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights)); + + for level in (0..levels).rev() { + plane = plane.map_rows(level_length(level), double_row); + } + plane + }) + } + + /// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges. + pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self { + self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset))) + } +} + +/// The length of a whole-pixel offset along the shortest path of steps one pixel straight, one diagonally, or a knight's move away. +/// For PSD interop, layer styles measure distances this way, which rounds the corners they grow around into 16 sides rather than a circle. +pub fn chamfer_length([x, y]: [i32; 2]) -> f32 { + let (long, short) = (x.abs().max(y.abs()) as f32, x.abs().min(y.abs()) as f32); + match 2. * short <= long { + // Knight's moves and straight steps + true => (long - 2. * short) + 5_f32.sqrt() * short, + // Knight's moves and diagonal steps + false => 5_f32.sqrt() * (long - short) + std::f32::consts::SQRT_2 * (2. * short - long), + } +} + +impl Plane { + /// Each pixel's distance to the silhouette's edge plus half a pixel, so a pixel beside a fully covered one lies one away and covered ones none, or infinity past `reach`. + /// Distances run by [`chamfer_length`] to the nearest covered pixel, then by its uncovered share within it, placing an antialiased edge between pixels. + pub fn distances_to_silhouette(&self, reach: f64) -> Self { + self.jump_flood(reach, |coverage| coverage > 0., |offset, coverage| chamfer_length(offset) + (0.5 - coverage) + 0.5) + } + + /// Each pixel's least [`chamfer_length`] to a seed plus the seed's own value, where the seeds are the pixels with finite values, or infinity past `reach`. + pub fn distances_through_seeds(&self, reach: f64) -> Self { + self.jump_flood(reach, f32::is_finite, |offset, value| chamfer_length(offset) + value) + } + + /// Each pixel's least `distance` to a seed, given its offset from the seed and the seed's value, or infinity past `reach`. + /// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none. O(width × height × log(reach)). + fn jump_flood(&self, reach: f64, is_seed: impl Fn(f32) -> bool, distance: impl Fn([i32; 2], f32) -> f32 + Sync) -> Self { + let mut nearest: Vec> = self.data.iter().map(|&value| is_seed(value).then_some([0, 0])).collect(); + + let (columns, rows) = (self.width as i32, self.height as i32); + // The offset runs from the seed to the pixel + let distance = |x: i32, y: i32, offset: [i32; 2]| distance(offset, self.data[((y - offset[1]) * columns + x - offset[0]) as usize]); + + let mut step = (reach.clamp(0., (columns.max(rows)) as f64).ceil() as u32 + 1).next_power_of_two(); + while step >= 1 { + let previous = nearest.clone(); + let step_length = step as i32; + + // Each pixel keeps the nearest of the seeds that it and its eight neighbors a step away have found so far + fill_rows(&mut nearest, self.width, |y, row| { + let y = y as i32; + for (x, best) in row.iter_mut().enumerate() { + let x = x as i32; + let mut best_distance = best.map_or(f32::INFINITY, |offset| distance(x, y, offset)); + + for neighbor_y in -1..=1 { + for neighbor_x in -1..=1 { + let (neighbor_x, neighbor_y) = (neighbor_x * step_length, neighbor_y * step_length); + let (from_x, from_y) = (x + neighbor_x, y + neighbor_y); + if from_x < 0 || from_y < 0 || from_x >= columns || from_y >= rows { + continue; + } + let Some([offset_x, offset_y]) = previous[(from_y * columns + from_x) as usize] else { continue }; + + let candidate = [offset_x - neighbor_x, offset_y - neighbor_y]; + let candidate_distance = distance(x, y, candidate); + if candidate_distance < best_distance { + *best = Some(candidate); + best_distance = candidate_distance; + } + } + } + } + }); + step /= 2; + } + + let data = nearest + .into_iter() + .enumerate() + .map(|(index, offset)| offset.map_or(f32::INFINITY, |offset| distance(index as i32 % columns, index as i32 / columns, offset).max(0.))) + .collect(); + Self { + width: self.width, + height: self.height, + data, + } + } + + /// The silhouette grown outward by `distance` pixels, measured by [`chamfer_length`] so it rounds the corners it grows around. + /// The grown edge lies half a pixel short of the farthest pixel center it reaches past, and fades out over one pixel. + pub fn grown(&self, distance: f64) -> Self { + let reach = distance as f32 + 1.; + self.distances_to_silhouette(distance + 1.).map(|nearest| (reach - nearest).clamp(0., 1.)) + } +} + +/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends. +fn sample_row(row: &[T], position: f64) -> T { + let last = row.len() as f64 - 1.; + let position = position.clamp(0., last.max(0.)); + let index = position.floor() as usize; + let fraction = (position - index as f64) as f32; + + match row.get(index + 1) { + Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)), + _ => row[index], + } +} + +/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself. +fn halve_row(source: &[T], target: &mut [T]) { + for (index, value) in target.iter_mut().enumerate() { + let first = source[2 * index]; + let second = source.get(2 * index + 1).copied().unwrap_or(first); + *value = first.plus(second).scaled(0.5); + } +} + +/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into. +fn double_row(source: &[T], target: &mut [T]) { + for (index, value) in target.iter_mut().enumerate() { + *value = sample_row(source, index as f64 / 2. - 0.25); + } +} + +/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends. +fn convolve_row(source: &[T], target: &mut [T], weights: &[f64]) { + let last = source.len() as isize - 1; + let at = |index: isize| source[index.clamp(0, last) as usize]; + + for (index, value) in target.iter_mut().enumerate() { + let index = index as isize; + let mut sum = at(index).scaled(weights[0] as f32); + for (distance, &weight) in weights.iter().enumerate().skip(1) { + let pair = at(index - distance as isize).plus(at(index + distance as isize)); + sum = sum.plus(pair.scaled(weight as f32)); + } + *value = sum; + } +} + +/// Moves the row by `offset` pixels, with nothing beyond its ends. +fn shift_row(source: &[T], target: &mut [T], offset: f64) { + let length = source.len() as f64; + for (index, value) in target.iter_mut().enumerate() { + let position = index as f64 - offset; + let floor = position.floor(); + let fraction = (position - floor) as f32; + + let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() }; + *value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kernel_weights_sum_to_one() { + for kernel in [ + BlurKernel::Gaussian { sigma: 3. }, + BlurKernel::Gaussian { sigma: 40. }, + BlurKernel::Box { radius: 5.5 }, + BlurKernel::Box { radius: 100. }, + ] { + let levels = kernel.levels(); + let weights = kernel.weights(levels); + let total = weights[0] + 2. * weights[1..].iter().sum::(); + + assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}"); + assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len()); + } + } + + #[test] + fn small_kernels_run_without_halving() { + assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0); + assert_eq!( + BlurKernel::Gaussian { + sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01 + } + .levels(), + 1 + ); + assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0); + } + + #[test] + fn gaussian_blur_spreads_a_point_with_the_requested_deviation() { + // A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count + for sigma in [2., 20.] { + let size = 401; + let mut plane = Plane::::new(size, 1); + plane.data[size / 2] = 1.; + + let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. }); + let total: f32 = blurred.data.iter().sum(); + let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::() / total as f64; + + assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}"); + assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt()); + } + } + + #[test] + fn tents_weigh_texels_by_how_far_short_of_the_radius_they_lie() { + // For PSD interop, a size of 16 weighs the texels 16, 15, ..., 1 from the center outward + let weights = BlurKernel::Tent { radius: 16. }.weights(0); + assert_eq!(weights.len(), 17); + for (distance, &weight) in weights.iter().enumerate() { + assert!((weight - (16 - distance) as f64 / 256.).abs() < 1e-12, "texel {distance} weighs {weight}"); + } + + // A straight edge blurred by it reaches (S - i)(S + 1 - i) / 2S² at the i-th pixel past the edge + let mut plane = Plane::::new(64, 1); + plane.data[..32].fill(1.); + let blurred = plane.blurred(BlurKernel::Tent { radius: 16. }, BlurKernel::Tent { radius: 0. }); + for i in 1..17 { + let expected = ((16 - i) * (17 - i)) as f32 / 512.; + assert!((blurred.data[31 + i] - expected).abs() < 1e-6, "pixel {i} past the edge is {}", blurred.data[31 + i]); + } + } + + #[test] + fn growing_rounds_the_corners_it_grows_around() { + // A single pixel grows into a disk the distance across, rather than a square + let mut point = Plane::::new(21, 21); + point.data[10 * 21 + 10] = 1.; + let grown = point.grown(5.); + let at = |x: usize, y: usize| grown.data[y * 21 + x]; + + assert_eq!(at(15, 10), 1., "the full distance along an axis"); + assert_eq!(at(16, 10), 0., "past the distance"); + assert_eq!(at(15, 14), 0., "past the distance diagonally, where a square would still reach"); + } + + #[test] + fn chamfer_lengths_are_exact_along_their_steps() { + assert_eq!(chamfer_length([7, 0]), 7.); + assert!((chamfer_length([-4, 4]) - 4. * std::f32::consts::SQRT_2).abs() < 1e-5); + assert!((chamfer_length([2, -1]) - 5_f32.sqrt()).abs() < 1e-6); + // Between the steps, the path runs a little longer than a straight line + assert!((chamfer_length([3, 1]) - (1. + 5_f32.sqrt())).abs() < 1e-6); + assert!((chamfer_length([3, 2]) - (5_f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-6); + } + + #[test] + fn distances_reach_no_farther_than_asked() { + let mut plane = Plane::::new(64, 1); + plane.data[0] = 1.; + let distances = plane.distances_to_silhouette(8.); + + assert_eq!(distances.data[0], 0.); + assert_eq!(distances.data[5], 5.); + assert!( + distances.data[63].is_infinite() || distances.data[63] == 63., + "a pixel far past the reach finds no seed or the true one" + ); + } + + #[test] + fn shifting_moves_by_fractions_of_a_pixel() { + let mut plane = Plane::::new(4, 1); + plane.data[1] = 1.; + + let shifted = plane.shifted(0.25, 0.); + + assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]); + } +} diff --git a/node-graph/libraries/raster-kernels/src/generators.rs b/node-graph/libraries/raster-kernels/src/generators.rs new file mode 100644 index 00000000000..ea8412f5da7 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/generators.rs @@ -0,0 +1,239 @@ +//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution. + +use core_types::Color; +use glam::{DVec2, IVec2, Vec2}; +use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType}; +use raster_types::parallel_rows::fill_rows; +use raster_types::{Image, ImageError}; + +/// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside. +const MANDELBROT_ITERATIONS: u32 = 255; + +/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels. +/// Fails where an image of that size can't be allocated. +/// The rows are rendered in parallel on native targets. +pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result, ImageError> { + let mut image = Image::try_new(width, height, Color::TRANSPARENT)?; + let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64); + let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size; + + match pattern { + GeneratorPattern::Noise(settings) => { + let noise = NoiseSampler::new(settings); + fill_rows(&mut image.data, width as usize, |y, row| { + row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = Color::from_luminance(noise.sample(pixel_center(x, y)))); + }); + } + GeneratorPattern::Mandelbrot => { + fill_rows(&mut image.data, width as usize, |y, row| { + row.iter_mut().enumerate().for_each(|(x, pixel)| { + let c = pixel_center(x, y) * 3. - DVec2::new(2., 1.5); + let value = mandelbrot_escape_iterations(c) as f32 / MANDELBROT_ITERATIONS as f32; + *pixel = Color::from_rgbaf32_unchecked(value, value, value, 1.); + }); + }); + } + } + + Ok(image) +} + +/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space. +struct NoiseSampler { + noise: fastnoise_lite::FastNoiseLite, + white_noise_seed: Option, + domain_warp: bool, +} + +impl NoiseSampler { + fn new(settings: &NoiseSettings) -> Self { + let mut noise = fastnoise_lite::FastNoiseLite::with_seed(settings.seed as i32); + noise.set_frequency(Some(1. / (settings.scale as f32).max(f32::EPSILON))); + + // Domain warp + let domain_warp_type = match settings.domain_warp_type { + DomainWarpType::None => None, + DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2), + DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced), + DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid), + }; + let domain_warp = domain_warp_type.is_some() && settings.domain_warp_amplitude > 0.; + noise.set_domain_warp_type(domain_warp_type); + noise.set_domain_warp_amp(Some(settings.domain_warp_amplitude as f32)); + + // Noise and fractal + let noise_type = match settings.noise_type { + NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin, + NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2, + NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S, + NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular, + NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic, + NoiseType::Value => fastnoise_lite::NoiseType::Value, + NoiseType::WhiteNoise => { + return Self { + noise, + white_noise_seed: Some(settings.seed as i32), + domain_warp: false, + }; + } + }; + noise.set_noise_type(Some(noise_type)); + let fractal_type = match settings.fractal_type { + FractalType::None => fastnoise_lite::FractalType::None, + FractalType::FBm => fastnoise_lite::FractalType::FBm, + FractalType::Ridged => fastnoise_lite::FractalType::Ridged, + FractalType::PingPong => fastnoise_lite::FractalType::PingPong, + FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive, + FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent, + }; + noise.set_fractal_type(Some(fractal_type)); + noise.set_fractal_octaves(Some(settings.fractal_octaves as i32)); + noise.set_fractal_lacunarity(Some(settings.fractal_lacunarity as f32)); + noise.set_fractal_gain(Some(settings.fractal_gain as f32)); + noise.set_fractal_weighted_strength(Some(settings.fractal_weighted_strength as f32)); + noise.set_fractal_ping_pong_strength(Some(settings.fractal_ping_pong_strength as f32)); + + // Cellular + let cellular_distance_function = match settings.cellular_distance_function { + CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean, + CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq, + CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan, + CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid, + }; + let cellular_return_type = match settings.cellular_return_type { + CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue, + CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance, + CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2, + CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add, + CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub, + CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul, + CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div, + }; + noise.set_cellular_distance_function(Some(cellular_distance_function)); + noise.set_cellular_return_type(Some(cellular_return_type)); + noise.set_cellular_jitter(Some(settings.cellular_jitter as f32)); + + Self { + noise, + white_noise_seed: None, + domain_warp, + } + } + + fn sample(&self, position: DVec2) -> f32 { + // White noise gives each square of one document unit its own random value + if let Some(seed) = self.white_noise_seed { + return white_noise(seed, position.floor().as_ivec2()); + } + + let (mut x, mut y) = (position.x as f32, position.y as f32); + if self.domain_warp { + (x, y) = self.noise.domain_warp_2d(x, y); + } + (self.noise.get_noise_2d(x, y) + 1.) * 0.5 + } +} + +/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match. +fn white_noise(seed: i32, cell: IVec2) -> f32 { + let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]); + + // The top 24 bits, which an f32 holds exactly + (hash >> 8) as f32 / (1_u32 << 24) as f32 +} + +/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result. +fn pcg3d(input: [u32; 3]) -> [u32; 3] { + let mix = |[x, y, z]: [u32; 3]| { + let x = x.wrapping_add(y.wrapping_mul(z)); + let y = y.wrapping_add(z.wrapping_mul(x)); + let z = z.wrapping_add(x.wrapping_mul(y)); + [x, y, z] + }; + + let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223))); + mix(v.map(|value| value ^ (value >> 16))) +} + +/// How many iterations `c` takes to escape the Mandelbrot set, or the iteration limit if it doesn't. In f32, which a GPU can match near the boundary. +fn mandelbrot_escape_iterations(c: DVec2) -> u32 { + let c = c.as_vec2(); + let mut z = Vec2::ZERO; + for iteration in 0..MANDELBROT_ITERATIONS { + z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c; + if z.length_squared() > 4. { + return iteration; + } + } + MANDELBROT_ITERATIONS +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renders_of_overlapping_areas_agree_where_they_overlap() { + let noise = GeneratorPattern::Noise(NoiseSettings { + seed: 7, + scale: 10., + noise_type: NoiseType::OpenSimplex2, + domain_warp_type: DomainWarpType::None, + domain_warp_amplitude: 0., + fractal_type: FractalType::FBm, + fractal_octaves: 3, + fractal_lacunarity: 2., + fractal_gain: 0.5, + fractal_weighted_strength: 0., + fractal_ping_pong_strength: 2., + cellular_distance_function: CellularDistanceFunction::Euclidean, + cellular_return_type: CellularReturnType::Nearest, + cellular_jitter: 1., + }); + + // One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it + let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap(); + let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]); + } + } + } + + #[test] + fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() { + let white_noise = |seed| { + GeneratorPattern::Noise(NoiseSettings { + seed, + scale: 10., + noise_type: NoiseType::WhiteNoise, + domain_warp_type: DomainWarpType::None, + domain_warp_amplitude: 0., + fractal_type: FractalType::None, + fractal_octaves: 1, + fractal_lacunarity: 2., + fractal_gain: 0.5, + fractal_weighted_strength: 0., + fractal_ping_pong_strength: 2., + cellular_distance_function: CellularDistanceFunction::Euclidean, + cellular_return_type: CellularReturnType::Nearest, + cellular_jitter: 1., + }) + }; + + // Each unit cell keeps its value when sampled four times as finely + let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap(); + let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]); + } + } + + // The values spread across the whole range, and another seed gives others + let luminances: Vec = coarse.data.iter().map(|color| color.r()).collect(); + assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5)); + assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data); + } +} diff --git a/node-graph/libraries/raster-kernels/src/kernel.rs b/node-graph/libraries/raster-kernels/src/kernel.rs new file mode 100644 index 00000000000..a76f121165c --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/kernel.rs @@ -0,0 +1,6 @@ +use core_types::Color; + +/// A per-pixel color mapping, run by `map_cpu` on the CPU. +pub trait MapColor: Sync + 'static { + fn map_cpu(&self, color: Color) -> Color; +} diff --git a/node-graph/libraries/raster-kernels/src/lib.rs b/node-graph/libraries/raster-kernels/src/lib.rs new file mode 100644 index 00000000000..57217ed2757 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/lib.rs @@ -0,0 +1,12 @@ +//! The kernels carrying out raster operations, such as color adjustments and procedural patterns, each worked out once from its settings. + +pub mod adjustments; +mod blending; +pub mod color_lookup_table; +pub mod effect_kernels; +pub mod generators; +mod kernel; +pub mod raster_effects; + +pub use kernel::*; +pub use raster_effects::evaluate_raster_effects; diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs new file mode 100644 index 00000000000..b32417fa2b2 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -0,0 +1,378 @@ +//! Carries out a raster's effects on the CPU at the raster's own resolution, for the nodes that read its pixels. +//! Each step mirrors the renderer's GPU passes, working on premultiplied gamma-encoded channels as they do. + +use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane}; +use core_types::color::{linear_to_srgb, srgb_to_linear}; +use core_types::list::{ATTR_EFFECTS, Item}; +use core_types::transfer_curve::TransferCurve; +use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color}; +use glam::{DAffine2, DMat2, DVec2}; +use graphic_types::effects::{EffectOperation, Effects, GlowFill, GlowTechnique, effect_space, grow_and_tent, precise_falloff, shadow_offset, shape_strength, spans_along_axes}; +use raster_types::{CPU, Image, Raster}; +use std::ops::Range; + +/// The most pixels an image may grow to with the margin its effects cast into, beyond which the margin is cut short. +const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64; + +/// The raster with its effects carried out into its pixels, grown to hold what they cast past its edges, and with the effects and the fill opacity they used removed. +/// A raster without the effects attribute is returned as it is. +pub fn evaluate_raster_effects(item: Item>) -> Item> { + let Some(effects) = item.attribute::(ATTR_EFFECTS).cloned() else { return item }; + let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let fill = item.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32; + + let (raster, attributes) = item.into_parts(); + let (raster, transform) = match evaluate(&raster, transform, &effects, fill) { + Some((image, grown_transform)) => (Raster::new_cpu(image), grown_transform), + None => (raster, transform), + }; + + // Which attributes come out depends only on whether the effects attribute came in, not on what it holds + let mut item = Item::from_parts(raster, attributes); + item.remove_attribute::(ATTR_EFFECTS); + item.remove_attribute::(ATTR_OPACITY_FILL); + item.set_attribute(ATTR_TRANSFORM, transform); + item +} + +/// The image of the effects carried out on `raster`, which `transform` places in the document, with the transform placing that larger image. +/// `None` when there's nothing to carry out, or the image is empty or its transform can't be inverted. +fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: f32) -> Option<(Image, DAffine2)> { + let (width, height) = (raster.width as usize, raster.height as usize); + if (effects.change_nothing() && fill >= 1.) || width == 0 || height == 0 || transform.matrix2.determinant() == 0. { + return None; + } + let size = DVec2::new(width as f64, height as f64); + + // Each effect's lengths become pixels along each of the image's axes, and its offsets map from its effect space through the inverse of the image's pixel placement + let document_to_pixels = (transform.matrix2 * DMat2::from_diagonal(size.recip())).inverse(); + let runs: Vec<(DMat2, Range)> = (effects.runs().into_iter()) + .map(|(stamped_transform, rows)| (document_to_pixels * effect_space(transform, stamped_transform).matrix2, rows)) + .collect(); + + // A margin around the image to hold the blur and shadows cast past its edges, cut short evenly for an image that would grow too large + let run_reach = |rows: &Range| effects.operations_in(rows.clone()).map(|operation| operation.painted_reach()).sum::(); + let reach_in_pixels: DVec2 = runs.iter().map(|(effect_to_pixels, rows)| run_reach(rows) * spans_along_axes(*effect_to_pixels)).sum(); + let mut margin = reach_in_pixels.ceil(); + if (size + 2. * margin).element_product() > MAX_PIXELS_WITH_MARGIN { + let reach_in_pixels = margin.max_element(); + margin = (margin * margin_fraction_that_fits(size, margin)).floor(); + if margin.max_element() < reach_in_pixels { + log::warn!( + "The effects on a {width} by {height} image end at a hard edge {} pixels past it, short of the {reach_in_pixels} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels", + margin.max_element() + ); + } + } + let (margin_x, margin_y) = (margin.x as usize, margin.y as usize); + + // The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result + let mut full = Plane::<[f32; 4]>::new(width + 2 * margin_x, height + 2 * margin_y); + for (y, row) in raster.data.chunks_exact(width).enumerate() { + let start = (y + margin_y) * full.width + margin_x; + full.data[start..start + width] + .iter_mut() + .zip(row) + .for_each(|(target, &color)| *target = premultiplied_gamma_channels(color)); + } + let mut filled = (fill < 1.).then(|| full.map(|pixel| pixel.map(|channel| channel * fill))); + // The shadows and glows stacked beneath the content + let mut beneath: Option> = None; + + // Each run after the first takes the result of those before it as its content at full strength, like the renderers' nested runs + let mut run_fill = fill; + let operations = (runs.iter().enumerate()) + .flat_map(|(run_index, (effect_to_pixels, rows))| (effects.operations_in(rows.clone()).enumerate()).map(move |(index, operation)| (operation, *effect_to_pixels, run_index > 0 && index == 0))); + for (effect, effect_to_pixels, starts_later_run) in operations { + if starts_later_run { + full = match (filled.take(), beneath.take()) { + (filled, Some(beneath)) => composite_beneath(filled.as_ref().unwrap_or(&full), &beneath), + (Some(filled), None) => filled, + (None, None) => full, + }; + run_fill = 1.; + } + let pixels_per_length = spans_along_axes(effect_to_pixels); + match effect { + EffectOperation::Blur { radius, box_blur, gamma } => { + let radius = radius * pixels_per_length; + if radius.max_element() < NEGLIGIBLE_LENGTH { + continue; + } + + // What lies beneath blurs together with the content + if let Some(beneath) = beneath.take() { + filled = filled.map(|filled| composite_beneath(&filled, &beneath)); + full = composite_beneath(&full, &beneath); + } + + let kernels = match box_blur { + true => (BlurKernel::Box { radius: radius.x }, BlurKernel::Box { radius: radius.y }), + false => (BlurKernel::Gaussian { sigma: radius.x }, BlurKernel::Gaussian { sigma: radius.y }), + }; + full = blur(full, kernels, !gamma); + filled = filled.map(|filled| blur(filled, kernels, !gamma)); + } + EffectOperation::DropShadow { + color, + angle, + distance, + spread, + size, + contour, + knockout, + } => { + let offset = effect_to_pixels * shadow_offset(angle, distance); + let silhouette = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y); + let strength = cast(silhouette, size, spread, GlowTechnique::Softer, 100., &contour, pixels_per_length); + beneath = Some(accumulate(beneath, &strength, color, knockout, &full, run_fill)); + } + EffectOperation::OuterGlow { + color, + technique, + spread, + size, + range, + contour, + } => { + let Some(paint) = GlowFill::of(&color) else { continue }; + let raw = cast_strength(full.map(|[_, _, _, alpha]| alpha), size, spread, technique, pixels_per_length); + let strength = shaped(raw.clone(), range, &contour); + beneath = Some(stack_beneath(beneath, glow_tint(&paint, &strength, &raw, true), true, &full, run_fill)); + } + EffectOperation::InnerShadow { + color, + angle, + distance, + choke, + size, + contour, + } => { + // Cast from the area outside the content, which the margin and anything moved in from past it belong to + let offset = effect_to_pixels * shadow_offset(angle, distance); + let outside = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y).map(|alpha| 1. - alpha); + let strength = cast(outside, size, choke, GlowTechnique::Softer, 100., &contour, pixels_per_length); + filled = filled.map(|filled| composite_within(&filled, &strength, &full, color)); + full = composite_within(&full, &strength, &full, color); + } + } + } + + let result = match (filled, beneath) { + (filled, Some(beneath)) => composite_beneath(filled.as_ref().unwrap_or(&full), &beneath), + (Some(filled), None) => filled, + (None, None) => full, + }; + let image = Image { + width: result.width as u32, + height: result.height as u32, + data: result.data.into_iter().map(straight_linear_color).collect(), + }; + + // The grown image spans the margin on each side of the original's unit square + let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size; + let grown_transform = transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin); + + Some((image, grown_transform)) +} + +/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it. +fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 { + // The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit + let quadratic = 4. * margin.x * margin.y; + let linear = 2. * (size.x * margin.y + size.y * margin.x); + let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN; + if constant >= 0. || linear <= 0. { + return 0.; + } + + let fraction = match quadratic > 0. { + true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic), + false => -constant / linear, + }; + fraction.clamp(0., 1.) +} + +/// A color as the premultiplied, gamma-encoded channels the effects work with. +fn premultiplied_gamma_channels(color: Color) -> [f32; 4] { + let [red, green, blue, alpha] = color.to_gamma_srgb_channels(); + [red * alpha, green * alpha, blue * alpha, alpha] +} + +/// Premultiplied, gamma-encoded channels back as a color. +fn straight_linear_color([red, green, blue, alpha]: [f32; 4]) -> Color { + if alpha <= 0. { + return Color::TRANSPARENT; + } + Color::from_gamma_srgb_channels(red / alpha, green / alpha, blue / alpha, alpha.min(1.)) +} + +/// Premultiplied channels with `transfer` applied to their straight color. +fn transferred(transfer: fn(f32) -> f32) -> impl Fn([f32; 4]) -> [f32; 4] + Sync { + move |[red, green, blue, alpha]| { + if alpha <= 0. { + return [0.; 4]; + } + let channel = |value: f32| transfer((value / alpha).max(0.)) * alpha; + [channel(red), channel(green), channel(blue), alpha] + } +} + +/// Blurs premultiplied gamma-encoded pixels by a kernel along each axis, in linear light if `linear`. +fn blur(plane: Plane<[f32; 4]>, (horizontal, vertical): (BlurKernel, BlurKernel), linear: bool) -> Plane<[f32; 4]> { + match linear { + true => plane.map(transferred(srgb_to_linear)).blurred(horizontal, vertical).map(transferred(linear_to_srgb)), + false => plane.blurred(horizontal, vertical), + } +} + +/// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage, shaped for PSD interop: grown by the `spread` percentage +/// of its `size` (in document pixels), softened over the rest by the `technique`, then strengthened by its `range` percentage and reshaped by its `contour`. +fn cast(silhouette: Plane, size: f64, spread: f64, technique: GlowTechnique, range: f64, contour: &TransferCurve, pixels_per_length: DVec2) -> Plane { + shaped(cast_strength(silhouette, size, spread, technique, pixels_per_length), range, contour) +} + +/// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage before its range and contour shape it, as [`cast`] describes. +fn cast_strength(silhouette: Plane, size: f64, spread: f64, technique: GlowTechnique, pixels_per_length: DVec2) -> Plane { + // Straight-line distances can't stretch along one axis, so an image scaled unevenly measures them by the mean of its two scales + let mean_scale = (pixels_per_length.x * pixels_per_length.y).sqrt(); + let (grow, tent) = grow_and_tent(size, spread); + + match technique { + GlowTechnique::Softer => { + let grown = match grow * mean_scale >= NEGLIGIBLE_LENGTH { + true => silhouette.grown(grow * mean_scale), + false => silhouette, + }; + let radius = tent * pixels_per_length; + match radius.max_element() >= NEGLIGIBLE_LENGTH { + true => grown.blurred(BlurKernel::Tent { radius: radius.x }, BlurKernel::Tent { radius: radius.y }), + false => grown, + } + } + GlowTechnique::Precise => { + let grow_pixels = (grow * mean_scale) as f32; + let to_content = silhouette.distances_to_silhouette(((size + 1.) * mean_scale).max(grow * mean_scale + 3.)); + + // Within the grown shape, the falloff measures how far it lies in from the grown shape's edge, which at the content's inner corners is farther than the grow. + // Each pixel up to 3 past the grown edge, a band any path in from farther crosses, seeds that measure with how far short of the edge it lies, so the edge falls between pixels. + let distances = match grow_pixels >= NEGLIGIBLE_LENGTH as f32 { + true => { + let past_grown = to_content.map(|distance| match distance > grow_pixels && distance <= grow_pixels + 3. { + true => grow_pixels - distance, + false => f32::INFINITY, + }); + let within_grown = past_grown.distances_through_seeds(grow * mean_scale + 1.); + to_content.zip(&within_grown, |to_content, within_grown| match to_content > grow_pixels { + true => to_content, + false => grow_pixels - within_grown, + }) + } + false => to_content, + }; + distances.map(|distance| precise_falloff(distance as f64 / mean_scale, grow, size) as f32) + } + } +} + +/// The `strength` from 0 to 1 at each pixel, strengthened by the `range` percentage and reshaped by the `contour`. +fn shaped(strength: Plane, range: f64, contour: &TransferCurve) -> Plane { + if range >= 100. && contour.is_identity() { + return strength; + } + let contour = contour.evaluator(); + strength.map(|strength| shape_strength(strength as f64, range, &|value| contour.evaluate(value)) as f32) +} + +/// The premultiplied color a glow filled with `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them. +/// An outer glow `fades` out with its raw strength when filled with a gradient. +fn glow_tint(paint: &GlowFill, strength: &Plane, raw: &Plane, fades: bool) -> Plane<[f32; 4]> { + strength + .zip(raw, |strength, raw| [strength, raw, 0., 0.]) + .map(|[strength, raw, ..]| premultiplied_gamma_channels(paint.color_at(strength as f64, raw as f64, fades))) +} + +/// Stacks a silhouette's coverage, tinted `color`, over what lies `beneath` the content so far. +/// If `knocked_out`, it stays hidden behind the full-strength content where a `fill` below 1 fades the content that shows over it. +fn accumulate(beneath: Option>, coverage: &Plane, color: Color, knocked_out: bool, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> { + let color = premultiplied_gamma_channels(color); + stack_beneath(beneath, coverage.map(|coverage| color.map(|channel| channel * coverage)), knocked_out, full_content, fill) +} + +/// Stacks a premultiplied `tinted` image over what lies `beneath` the content so far, knocked out like [`accumulate`] describes. +fn stack_beneath(beneath: Option>, tinted: Plane<[f32; 4]>, knocked_out: bool, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> { + let tinted = match knocked_out && fill < 1. { + // The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this + true => tinted.zip(full_content, |tinted, content| { + let shown = (1. - content[3]) / (1. - fill * content[3]).max(f32::EPSILON); + tinted.map(|channel| channel * shown) + }), + false => tinted, + }; + + match beneath { + Some(beneath) => tinted.zip(&beneath, |tinted, beneath| std::array::from_fn(|channel| tinted[channel] + beneath[channel] * (1. - tinted[3]))), + None => tinted, + } +} + +/// The image with a silhouette's coverage, tinted `color`, placed over it within the full-strength content. +fn composite_within(image: &Plane<[f32; 4]>, coverage: &Plane, full_content: &Plane<[f32; 4]>, color: Color) -> Plane<[f32; 4]> { + let color = premultiplied_gamma_channels(color); + let coverages = coverage.zip(full_content, |coverage, content| [coverage, content[3], 0., 0.]); + + image.zip(&coverages, |image, [coverage, content_alpha, _, _]| { + let tinted = color.map(|channel| channel * coverage); + std::array::from_fn(|channel| tinted[channel] * content_alpha + image[channel] * (1. - tinted[3])) + }) +} + +/// The image with the shadows and glows `beneath` placed under it. +fn composite_beneath(image: &Plane<[f32; 4]>, beneath: &Plane<[f32; 4]>) -> Plane<[f32; 4]> { + image.zip(beneath, |image, beneath| std::array::from_fn(|channel| image[channel] + beneath[channel] * (1. - image[3]))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_margin_too_large_is_cut_short_to_fit_the_pixel_limit() { + // A tall strip whose margins alone would grow it eightfold past the limit + let size = DVec2::new(1., 16_384.); + let margin = DVec2::splat(3000.); + + let fitted = (margin * margin_fraction_that_fits(size, margin)).floor(); + let grown_area = (size + 2. * fitted).element_product(); + + assert!(grown_area <= MAX_PIXELS_WITH_MARGIN, "the grown image has {grown_area} pixels"); + assert!(grown_area > 0.99 * MAX_PIXELS_WITH_MARGIN, "the grown image has only {grown_area} pixels"); + } + + #[test] + fn an_inner_shadow_of_only_choke_shades_an_opaque_raster() { + use graphic_types::{Effect, stamp_effect}; + + let raster = Raster::new_cpu(Image::new(8, 8, Color::WHITE)); + let mut item = Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.))); + let inner_shadow = EffectOperation::InnerShadow { + color: Color::BLACK, + angle: 0., + distance: 0., + choke: 100., + size: 2., + contour: TransferCurve::default(), + }; + stamp_effect(&mut item, Effect::new(&inner_shadow)); + + let evaluated = evaluate_raster_effects(item); + let raster = evaluated.element(); + let width = raster.width as usize; + let pixel = |x: usize, y: usize| raster.data[y * width + x]; + + // The margin around the content lies outside it, which the shadow grows inward from + let margin = (width - 8) / 2; + assert!(pixel(margin, margin + 4).r() < 0.01, "the content's edge is shaded"); + assert!(pixel(margin + 4, margin + 4).r() > 0.99, "the content's middle is not"); + } +} diff --git a/node-graph/libraries/raster-types/src/image.rs b/node-graph/libraries/raster-types/src/image.rs index cc3bf812143..2ef1cfe4813 100644 --- a/node-graph/libraries/raster-types/src/image.rs +++ b/node-graph/libraries/raster-types/src/image.rs @@ -160,7 +160,12 @@ impl Image

{ impl Image { /// Generate Image from some frontend image data (the canvas pixels as u8s in a flat array) pub fn from_image_data(image_data: &[u8], width: u32, height: u32) -> Self { - let data = image_data.chunks_exact(4).map(|v| SRGBA8::new(v[0], v[1], v[2], v[3]).into()).collect(); + let data = image_data + .as_chunks::<4>() + .0 + .iter() + .map(|&[red, green, blue, alpha]| SRGBA8::new(red, green, blue, alpha).into()) + .collect(); Image { width, height, data } } @@ -195,7 +200,9 @@ impl Image { let image = image.to_rgba32f(); let data = image - .chunks_exact(4) + .as_chunks::<4>() + .0 + .iter() .map(|pixel| { if !linear { return Color::from_gamma_srgb_channels(pixel[0], pixel[1], pixel[2], pixel[3]); @@ -299,7 +306,7 @@ where let mut last_b_srgb = 0u8; let mut result = vec![0; data.len() * 4]; - for (color, out) in data.iter().zip(result.chunks_exact_mut(4)) { + for (color, out) in data.iter().zip(result.as_chunks_mut::<4>().0) { let a = color.a().to_f32(); // Smaller alpha values than this would map to fully transparent // anyway, avoid expensive encoding. diff --git a/node-graph/libraries/raster-types/src/lib.rs b/node-graph/libraries/raster-types/src/lib.rs index 02413ecf220..eac0d10c46d 100644 --- a/node-graph/libraries/raster-types/src/lib.rs +++ b/node-graph/libraries/raster-types/src/lib.rs @@ -1,4 +1,5 @@ pub mod image; +pub mod parallel_rows; pub mod raster_types; // Re-exports for convenience diff --git a/node-graph/nodes/raster/src/parallel_rows.rs b/node-graph/libraries/raster-types/src/parallel_rows.rs similarity index 100% rename from node-graph/nodes/raster/src/parallel_rows.rs rename to node-graph/libraries/raster-types/src/parallel_rows.rs diff --git a/node-graph/libraries/rendering/Cargo.toml b/node-graph/libraries/rendering/Cargo.toml index 8b6fe208564..bae0b7c77da 100644 --- a/node-graph/libraries/rendering/Cargo.toml +++ b/node-graph/libraries/rendering/Cargo.toml @@ -37,6 +37,7 @@ kurbo = { workspace = true } vector-types = { workspace = true } graphic-types = { workspace = true } vello_gpu = { workspace = true } +wgpu = { workspace = true } parley = { workspace = true } skrifa = { workspace = true } diff --git a/node-graph/libraries/rendering/src/deferred_image.rs b/node-graph/libraries/rendering/src/deferred_image.rs new file mode 100644 index 00000000000..2e90bce1877 --- /dev/null +++ b/node-graph/libraries/rendering/src/deferred_image.rs @@ -0,0 +1,145 @@ +//! Effects whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, which an SVG's filter takes as an image of that coverage the GPU renders: a map of it. +//! The content keeps its own markup, and only the map is an image. A placeholder stands in the filter for each map until it's resolved, leaving the effect out of an SVG that never is. + +use crate::renderer::{Render, RenderOutputType, RenderParams}; +use crate::vello_scene_builder::VelloSceneBuilder; +use core_types::math::quad::Quad; +use core_types::transform::Footprint; +use glam::{DAffine2, DVec2, UVec2}; +use graphic_types::Graphic; +use graphic_types::effects::EffectCapture; +use graphic_types::raster_types::{CPU, Raster}; + +/// The most pixels across or down a map may have. +pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192; + +/// One map of an effect's coverage an SVG filter takes as an image the GPU renders. +#[derive(Clone)] +pub struct EffectMap { + /// Names the markers around the placeholder in the SVG, which the map replaces. + pub id: u64, + /// The item with its effects, but without its opacity and blend mode, which don't touch its effects' coverages. + pub content: Graphic, + pub render_params: RenderParams, + pub capture: EffectCapture, + /// The name of the filter result the map stands for. + pub result: String, + /// Maps the filter's user space into the document. + pub user_to_document: DAffine2, + /// Maps the user space the `content` is drawn in into the document, which differs from the filter's where the filter measures in its effects' space. + pub content_to_document: DAffine2, + /// The filter's region in its user space, which the map covers. + pub bounds: [DVec2; 2], +} + +/// Where a filter places the map the GPU rendered of an effect's coverage. +#[derive(Clone, Debug, PartialEq)] +pub struct EffectMapPlacement { + /// Names the markers the map replaces. + pub id: u64, + pub result: String, + /// Places the map's unit square in the filter's user space. + pub transform: DAffine2, +} + +/// The map of an effect's coverage for the GPU to render: where the filter places it, the transform mapping the document into its pixels, and how many pixels it has. +pub struct EffectMapLayout { + pub placement: EffectMapPlacement, + pub document_to_pixels: DAffine2, + pub size: UVec2, +} + +/// The markers that open and close the placeholder for the map `id` names. +fn markers(id: u64) -> (String, String) { + (format!(""), format!("")) +} + +/// The filter primitive standing for the map `id` names until it's resolved, which leaves nothing covered. +pub(crate) fn placeholder(id: u64, result: &str) -> String { + let (opening, closing) = markers(id); + format!(r#"{opening}{closing}"#) +} + +impl EffectMap { + /// The map covering the part of the filter's region in a view that `document_to_view` maps the document into, spanning `view_size` pixels, with at most `max_pixels` across or down. + /// `None` if none of it lies in view. + pub fn layout(&self, document_to_view: DAffine2, view_size: DVec2, max_pixels: u32) -> Option { + let user_to_view = document_to_view * self.user_to_document; + if !user_to_view.matrix2.determinant().is_normal() || !user_to_view.is_finite() { + return None; + } + + // The view's pixels the region reaches into, whole ones so the map's pixels line up with the view's + let [min, max] = (user_to_view * Quad::from_box(self.bounds)).bounding_box(); + let (min, max) = (min.max(DVec2::ZERO).floor(), max.min(view_size).ceil()); + let area = max - min; + if !(area.x > 0. && area.y > 0.) { + return None; + } + + // An area too large for a texture gets fewer pixels, each spanning more of the view + let pixels = area.min(DVec2::splat(max_pixels as f64)).max(DVec2::ONE).round(); + let document_to_pixels = DAffine2::from_scale(pixels / area) * DAffine2::from_translation(-min) * document_to_view; + + Some(EffectMapLayout { + placement: EffectMapPlacement { + id: self.id, + result: self.result.clone(), + transform: user_to_view.inverse() * DAffine2::from_translation(min) * DAffine2::from_scale(area), + }, + document_to_pixels, + size: pixels.as_uvec2(), + }) + } + + /// Draws the effect's coverage into a scene of the document, which the `layout` places in the map's pixels. + pub fn draw(&self, scene: &mut VelloSceneBuilder, layout: &EffectMapLayout) { + let render_params = RenderParams { + render_output_type: RenderOutputType::Vello, + footprint: Footprint { + transform: layout.document_to_pixels, + resolution: layout.size, + ..Default::default() + }, + ..self.render_params.clone() + }; + + scene.capture_next_effects(self.capture); + self.content.render_to_vello(scene, self.content_to_document, &render_params); + } +} + +/// Replaces the placeholder for a map in `svg` with the `map` the GPU rendered, as a filter image of its coverage in alpha. +pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, map: &Raster) { + let (opening, closing) = markers(placement.id); + let Some(start) = svg.find(&opening) else { return }; + let Some(end) = svg[start..].find(&closing).map(|offset| start + offset + closing.len()) else { + return; + }; + + let [min, max] = (placement.transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box(); + let size = max - min; + let png = map.png_data_url(); + + // A map turned against the filter's user space goes in an SVG document of its own, which turns it into place + let [a, b, c, d] = placement.transform.matrix2.to_cols_array(); + let href = match b == 0. && c == 0. && a > 0. && d > 0. { + true => png.to_string(), + false => { + use base64::Engine; + + let [a, b, c, d, e, f] = placement.transform.to_cols_array(); + let document = format!( + r#""#, + min.x, min.y, size.x, size.y, size.x, size.y + ); + format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(document)) + } + }; + + let image = format!( + r#""#, + min.x, min.y, size.x, size.y, placement.result + ); + svg.replace_range(start..end, &image); +} diff --git a/node-graph/libraries/rendering/src/lib.rs b/node-graph/libraries/rendering/src/lib.rs index 25365911c81..fdc3ad27891 100644 --- a/node-graph/libraries/rendering/src/lib.rs +++ b/node-graph/libraries/rendering/src/lib.rs @@ -1,4 +1,5 @@ pub mod convert_usvg_path; +pub mod deferred_image; pub mod render_ext; mod renderer; pub mod to_peniko; diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 737521e01ed..d326a349a59 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -1,3 +1,4 @@ +use crate::deferred_image::{self, EffectMap}; use crate::render_ext::{PaintTarget, RenderExt}; use crate::to_peniko::{BlendModeExt, ToPenikoColor}; use crate::vello_scene_builder::VelloSceneBuilder; @@ -16,13 +17,14 @@ use core_types::math::quad::Quad; use core_types::transform::Footprint; use core_types::uuid::{NodeId, generate_uuid}; use core_types::{ - 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_FONT, - ATTR_FONT_SIZE, ATTR_GRADIENT_FORM, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, - ATTR_TRANSFORM, + 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_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_FORM, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, + ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, }; use dyn_any::DynAny; use glam::{DAffine2, DMat2, DVec2}; use graphene_resource::Resource; +use graphic_types::effects::{EffectCapture, GlowFill, effect_space, spans_along_axes}; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::vector_types::gradient::{Gradient, GradientForm}; use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath}; @@ -31,7 +33,7 @@ use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, Stroke use graphic_types::vector_types::vector::{ GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths, }; -use graphic_types::{Appearance, Artboard, Cover, Coverage, FillAndStroke, Graphic, Vector}; +use graphic_types::{Appearance, Artboard, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Graphic, Vector}; use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape}; use num_traits::Zero; use skrifa::instance::{LocationRef, NormalizedCoord, Size}; @@ -41,6 +43,7 @@ use skrifa::{GlyphId, MetadataProvider}; use std::collections::{HashMap, HashSet}; use std::fmt::Write; use std::hash::Hash; +use std::ops::Range; use std::sync::Arc; use vector_types::gradient::{GradientSettings, GradientSpread}; use vello_gpu::peniko; @@ -96,6 +99,34 @@ impl<'a, T> ItemRef<'a, T> { (self.attribute_cloned_or::(ATTR_OPACITY, 1.) * opacity_fill) as f32 } + /// How the item's opacity attributes and effects apply as it renders, with `content_transform` placing its content in the space it's drawn in. + fn compositing(self, render_params: &RenderParams, content_transform: DAffine2) -> ItemCompositing<'a> { + let opacity = self.attribute_cloned_or::(ATTR_OPACITY, 1.) as f32; + let fill = if render_params.for_mask { + 1. + } else { + self.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32 + }; + + // Outline mode shows only geometry + let effects = self + .attribute::(ATTR_EFFECTS) + .filter(|effects| !effects.change_nothing() && render_params.render_mode != RenderMode::Outline); + + match effects { + Some(effects) => ItemCompositing { + opacity, + effects: Some((effects, fill)), + content_transform, + }, + None => ItemCompositing { + opacity: opacity * fill, + effects: None, + content_transform, + }, + } + } + pub(crate) fn clone_item_attributes(self) -> core_types::list::ItemAttributeValues { match self { ItemRef::ListItem(list, index) => list.clone_item_attributes(index), @@ -161,6 +192,507 @@ impl<'a> ItemRef<'a, Vector> { } } +/// How an item composites: the alpha of the layer it draws through, and the effects its content renders through inside that layer. +struct ItemCompositing<'a> { + opacity: f32, + /// With the fill opacity, which the effects group applies to the content alone so the shadows and glows cast from it stay at full strength. + effects: Option<(&'a Effects, f32)>, + /// Places the content in the space it's drawn in, which the effects' spaces follow. + content_transform: DAffine2, +} + +impl ItemCompositing<'_> { + /// How far the effects reach past the content along each axis of the space it's drawn in. + fn reach(&self) -> DVec2 { + self.effects.map_or(DVec2::ZERO, |(effects, _)| effects.reach_along_axes(self.content_transform)) + } + + /// How far the effects reach past the content along each axis of the content's own space. + fn reach_in_content_space(&self) -> DVec2 { + self.effects.map_or(DVec2::ZERO, |(effects, _)| effects.reach_along_axes(DAffine2::IDENTITY)) + } + + /// Draws the content `draw` draws through the effects group, given the content's bounds in the scene's space. + /// Rendering a split scene calls `draw` again for each part. + fn draw_with_effects(&self, scene: &mut VelloSceneBuilder, bounds: impl FnOnce() -> RenderBoundingBox, mut draw: impl FnMut(&mut VelloSceneBuilder)) { + let Some((effects, fill)) = self.effects else { return draw(scene) }; + + let bounds = match bounds() { + RenderBoundingBox::Rectangle([min, max]) => Some(kurbo::Rect::new(min.x, min.y, max.x, max.y)), + RenderBoundingBox::Infinite => None, + RenderBoundingBox::None => return draw(scene), + }; + + // A capture names an effect by its place in the whole list, which falls in one run, so the runs after that one are left out of its map + let mut runs = effects.runs(); + if let Some(capture) = scene.take_effect_capture() + && let Some(capture_run) = runs.iter().position(|(_, rows)| rows.contains(&capture.index)) + { + let run_start = runs[capture_run].1.start; + runs.truncate(capture_run + 1); + scene.capture_next_effects(EffectCapture { + index: capture.index - run_start, + plane: capture.plane, + }); + } + draw_effect_runs(scene, effects, &runs, fill, self.content_transform, bounds, &mut draw); + } + + /// The opacity for content drawn without the effects group, as SVG draws content its filter can't apply to. + fn opacity_without_effects(&self) -> f32 { + self.opacity * self.effects.map_or(1., |(_, fill)| fill) + } + + /// Writes the SVG filters carrying out the effects, if there are any to apply, given the content's bounds in the current user space, where `content_transform` places it. + /// Returns the groups wrapping the content, the outermost of which also takes the item's opacity and blend mode. + /// The item's `content`, without its opacity and blend mode, is what the GPU renders the maps of its effects' coverages from. + fn svg_filter(&self, render: &mut SvgRender, render_params: &RenderParams, bounds: impl FnOnce() -> RenderBoundingBox, content: impl FnOnce() -> Graphic) -> Option { + let (effects, fill) = self.effects?; + + // Effects change nothing visible about content without edges, like a color or gradient layer filling everything + let RenderBoundingBox::Rectangle(bounds) = bounds() else { return None }; + + // Each run's filter measures in its effect space, which a group's transform sets up unless the content is only moved since the effects were stamped + let runs = effects.runs(); + let spaces: Vec = runs.iter().map(|(stamped_transform, _)| effect_space(self.content_transform, *stamped_transform)).collect(); + if spaces.iter().any(|space| !space.matrix2.determinant().is_normal()) { + return None; + } + let transformed = spaces.len() > 1 || spaces.iter().any(|space| space.matrix2 != DMat2::IDENTITY); + + let (mut build_content, mut built_content) = (Some(content), None); + let mut groups = Vec::with_capacity(runs.len()); + let (mut region, mut region_to_space) = (bounds, DAffine2::IDENTITY); + for (index, ((_, rows), space)) in runs.iter().zip(&spaces).enumerate() { + // The run's content is the content itself or the result of the runs before it, in its effect space + let user_to_space = if transformed { space.inverse() } else { DAffine2::IDENTITY }; + let to_space = if index == 0 { user_to_space } else { user_to_space * region_to_space }; + let content_bounds = (to_space * Quad::from_box(region)).bounding_box(); + let run_fill = if index == 0 { fill } else { 1. }; + + let filter = write_svg_effects_filter(&mut render.svg_defs, &effects.run(rows.clone()), run_fill, content_bounds, rows.start); + let space_to_document = if transformed { render.transform * *space } else { render.transform }; + + // A paint's markup is embedded as an image, where no map can reach its placeholders + if !filter.maps.is_empty() && !render_params.inside_pattern { + if let Some(build_content) = build_content.take() { + built_content = Some(build_content()); + } + for map in filter.maps { + render.effect_maps.push(EffectMap { + id: map.id, + content: built_content.clone().unwrap_or_default(), + render_params: render_params.clone(), + capture: map.capture, + result: map.result, + user_to_document: space_to_document, + content_to_document: render.transform, + bounds: filter.region, + }); + } + } + + groups.push(format!("url(#{})", filter.id)); + (region, region_to_space) = (filter.region, if transformed { *space } else { DAffine2::IDENTITY }); + } + + Some(SvgFilterGroups { + filters: groups, + spaces: transformed.then_some(spaces), + }) + } +} + +/// The SVG filter groups carrying out an item's runs of effects, which wrap its content. +struct SvgFilterGroups { + /// Each run's filter reference, innermost first. + filters: Vec, + /// Each run's effect space placed in the user space, innermost first, when groups have to transform into them. + spaces: Option>, +} + +/// Draws the content `draw` draws through the last of the `runs` of `effects`, around the content drawn through the runs before it, each in its own effect space. +/// The innermost run fades the content by the `fill`, and each run around it takes the result within as its content, at full strength. +#[allow(clippy::too_many_arguments)] +fn draw_effect_runs( + scene: &mut VelloSceneBuilder, + effects: &Effects, + runs: &[(DAffine2, Range)], + fill: f32, + content_transform: DAffine2, + bounds: Option, + draw: &mut dyn FnMut(&mut VelloSceneBuilder), +) { + let Some(((stamped_transform, rows), earlier)) = runs.split_last() else { return draw(scene) }; + let space = effect_space(content_transform, *stamped_transform); + let run = effects.run(rows.clone()); + if earlier.is_empty() { + return scene.draw_effects(&run, fill, bounds, space, draw); + } + + // The runs before this one paint past the content, which this run then reaches from + let earlier_reach: DVec2 = (earlier.iter()) + .map(|(stamped_transform, rows)| { + let reach: f64 = effects.operations_in(rows.clone()).map(|operation| operation.painted_reach()).sum(); + reach * spans_along_axes(effect_space(content_transform, *stamped_transform).matrix2) + }) + .sum(); + let earlier_bounds = bounds.map(|bounds| bounds.inflate(earlier_reach.x, earlier_reach.y)); + scene.draw_effects(&run, 1., earlier_bounds, space, &mut |scene| { + draw_effect_runs(scene, effects, earlier, fill, content_transform, bounds, draw) + }); +} + +/// The item as content of its own, without the opacity and blend mode that act on its effects' result as a whole. +fn without_opacity_and_blend_mode(item: ItemRef<'_, T>, element: T) -> Item { + let mut content = Item::from_parts(element, item.clone_item_attributes()); + content.remove_attribute::(ATTR_OPACITY); + content.remove_attribute::(ATTR_BLEND_MODE); + content +} + +/// How far the effects of the items nested anywhere inside `graphic`, which `transform` places in the document, reach past its bounds along the document's axes, +/// measuring how far each effect reaches by `reach` (like [`EffectOperation::painted_reach`]). +fn nested_effects_reach(graphic: &Graphic, transform: DAffine2, reach: fn(&EffectOperation) -> f64) -> DVec2 { + fn item_reach(item: &Item, transform: DAffine2, reach: fn(&EffectOperation) -> f64) -> DVec2 { + let content_transform = transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM); + item.attribute::(ATTR_EFFECTS) + .map_or(DVec2::ZERO, |effects| effects.reach_along_axes_by(content_transform, reach)) + } + fn list_reach(list: &List, transform: DAffine2, reach: fn(&EffectOperation) -> f64, nested: impl Fn(&T, DAffine2) -> DVec2) -> DVec2 { + (0..list.len()) + .map(|index| { + let content_transform = transform * list.attribute_cloned_or_default::(ATTR_TRANSFORM, index); + let own = list + .attribute::(ATTR_EFFECTS, index) + .map_or(DVec2::ZERO, |effects| effects.reach_along_axes_by(content_transform, reach)); + own + list.element(index).map_or(DVec2::ZERO, |element| nested(element, content_transform)) + }) + .fold(DVec2::ZERO, DVec2::max) + } + fn none(_: &T, _: DAffine2) -> DVec2 { + DVec2::ZERO + } + + match graphic { + Graphic::None(_) | Graphic::NoneList(_) | Graphic::StrokeList(_) => DVec2::ZERO, + Graphic::Graphic(item) => { + let content_transform = transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM); + item_reach(item, transform, reach) + nested_effects_reach(item.element(), content_transform, reach) + } + Graphic::Vector(item) => item_reach(item, transform, reach), + Graphic::RasterCPU(item) => item_reach(item, transform, reach), + Graphic::RasterGPU(item) => item_reach(item, transform, reach), + Graphic::Color(item) => item_reach(item, transform, reach), + Graphic::Gradient(item) => item_reach(item, transform, reach), + Graphic::Text(item) => item_reach(item, transform, reach), + Graphic::GraphicList(list) => list_reach(list, transform, reach, |nested, content_transform| nested_effects_reach(nested, content_transform, reach)), + Graphic::VectorList(list) => list_reach(list, transform, reach, none), + Graphic::RasterCPUList(list) => list_reach(list, transform, reach, none), + Graphic::RasterGPUList(list) => list_reach(list, transform, reach, none), + Graphic::ColorList(list) => list_reach(list, transform, reach, none), + Graphic::GradientList(list) => list_reach(list, transform, reach, none), + Graphic::TextList(list) => list_reach(list, transform, reach, none), + } +} + +/// The bounds of the items in `list`, as [`graphic_list_bounding_box`] finds them, each grown by how far its effects and those nested anywhere inside it paint past it. +/// Without `maps_resolved`, as in an SVG with no GPU to render its maps and images, only the effects SVG then draws past the content count (see [`svg_drawn_reach`]). +pub fn graphic_list_painted_bounds(list: &List, maps_resolved: bool) -> RenderBoundingBox { + let reach: fn(&EffectOperation) -> f64 = if maps_resolved { EffectOperation::painted_reach } else { svg_drawn_reach }; + + let item_bounds = |index| { + let element = list.element(index)?; + let transform = list.attribute_cloned_or_default::(ATTR_TRANSFORM, index); + let RenderBoundingBox::Rectangle([min, max]) = graphic_thumbnail_bounding_box(element, transform) else { + return None; + }; + + let own_reach = list + .attribute::(ATTR_EFFECTS, index) + .map_or(DVec2::ZERO, |effects| effects.reach_along_axes_by(transform, reach)); + let reach = own_reach + nested_effects_reach(element, transform, reach); + Some([min - reach, max + reach]) + }; + + match (0..list.len()).filter_map(item_bounds).reduce(Quad::combine_bounds) { + Some(bounds) => RenderBoundingBox::Rectangle(bounds), + None => graphic_list_bounding_box(list, DAffine2::IDENTITY), + } +} + +/// How far an effect that SVG draws without the GPU's maps paints past the content, in its effect space, which only the blurs do. +fn svg_drawn_reach(operation: &EffectOperation) -> f64 { + match operation { + EffectOperation::Blur { .. } => operation.painted_reach(), + _ => 0., + } +} + +/// Wraps an item's SVG `content` in the groups applying its effects' `filters`, the outermost with the item's opacity and blend mode, if there are filters. +fn render_svg_through_filter(render: &mut SvgRender, filters: Option, opacity: f32, blend_mode: BlendMode, content: impl FnOnce(&mut SvgRender)) { + let Some(SvgFilterGroups { filters, spaces }) = filters else { return content(render) }; + + let mut content = Some(content); + let mut content = |render: &mut SvgRender| { + if let Some(content) = content.take() { + content(render); + } + }; + render_svg_filter_groups(render, &filters, spaces.as_deref(), Some((opacity, blend_mode)), &mut content); +} + +/// Wraps `content` in the group of the last of the `filters` (innermost first), around the groups of those before it, each transforming into its run's effect space in `spaces`. +/// Inside the innermost group, the content returns to the user space it's drawn in. The `outermost` group takes the item's opacity and blend mode. +fn render_svg_filter_groups(render: &mut SvgRender, filters: &[String], spaces: Option<&[DAffine2]>, outermost: Option<(f32, BlendMode)>, content: &mut dyn FnMut(&mut SvgRender)) { + let Some((filter, inner_filters)) = filters.split_last() else { + return match spaces.and_then(|spaces| spaces.first()) { + Some(innermost_space) => render_svg_transformed(render, innermost_space.inverse(), content), + None => content(render), + }; + }; + + // The group transforms from its run's effect space into the space outside it, the next run's or the user space around the outermost + let index = inner_filters.len(); + let transform = spaces.map(|spaces| match spaces.get(index + 1) { + Some(outside_space) => outside_space.inverse() * spaces[index], + None => spaces[index], + }); + + render.parent_tag( + "g", + |attributes| { + let matrix = transform.map(format_transform_matrix).unwrap_or_default(); + if !matrix.is_empty() { + attributes.push(ATTR_TRANSFORM, matrix); + } + attributes.push("filter", filter.clone()); + if let Some((opacity, blend_mode)) = outermost { + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + if blend_mode != BlendMode::default() { + attributes.push("style", blend_mode.render()); + } + } + }, + |render| { + let outside_transform = render.transform; + render.transform = outside_transform * transform.unwrap_or_default(); + render_svg_filter_groups(render, inner_filters, spaces, None, content); + render.transform = outside_transform; + }, + ); +} + +/// Wraps `content` in a group placing it by `transform`, keeping the render's transform into the document in step. +fn render_svg_transformed(render: &mut SvgRender, transform: DAffine2, content: &mut dyn FnMut(&mut SvgRender)) { + let matrix = format_transform_matrix(transform); + if matrix.is_empty() { + return content(render); + } + + render.parent_tag( + "g", + |attributes| attributes.push(ATTR_TRANSFORM, matrix), + |render| { + let outside_transform = render.transform; + render.transform = outside_transform * transform; + content(render); + render.transform = outside_transform; + }, + ); +} + +/// Builds the primitives of an SVG filter, naming each result so later primitives can take it as an input. +#[derive(Default)] +struct SvgFilterPrimitives { + markup: String, + count: usize, + maps: Vec, +} + +impl SvgFilterPrimitives { + /// Appends a primitive tag with `attributes` (and `children`, if any), returning the name of its result. + fn push(&mut self, tag: &str, attributes: &str, children: &str) -> String { + self.count += 1; + let result = format!("effect-{}", self.count); + + match children.is_empty() { + true => write!(self.markup, r#"<{tag} {attributes} result="{result}" />"#), + false => write!(self.markup, r#"<{tag} {attributes} result="{result}">{children}"#), + } + .unwrap(); + + result + } + + /// The sum of two premultiplied images, for composites whose terms SVG's other operators can't express. + fn add(&mut self, first: &str, second: &str) -> String { + self.push("feComposite", &format!(r#"in="{first}" in2="{second}" operator="arithmetic" k2="1" k3="1""#), "") + } + + /// The image with the shadows and glows `beneath` it. + fn composite_beneath(&mut self, image: &str, beneath: &str) -> String { + self.push("feComposite", &format!(r#"in="{image}" in2="{beneath}" operator="over""#), "") + } + + /// A placeholder for the map of an effect's coverage that `capture` names, which the GPU renders, returning the name of the result it stands for. + fn map(&mut self, capture: EffectCapture) -> String { + self.count += 1; + let result = format!("effect-{}", self.count); + let id = generate_uuid(); + + self.markup.push_str(&deferred_image::placeholder(id, &result)); + self.maps.push(SvgEffectMap { id, capture, result: result.clone() }); + result + } +} + +/// A map an SVG filter takes as an image the GPU renders of an effect's coverage. +struct SvgEffectMap { + id: u64, + capture: EffectCapture, + result: String, +} + +/// An SVG filter written into the defs, with the maps of effects' coverages it takes. +struct SvgEffectsFilter { + id: String, + /// The filter's region in its user space. + region: [DVec2; 2], + maps: Vec, +} + +/// Writes an SVG filter into `svg_defs` that carries out a run of `effects` like the GPU passes do, in a user space that is their effect space. +/// `bounds` is the content's extent in that space, and `capture_offset` is the run's place in its item's list, which numbers the maps' captures. +/// Shadows and glows shaped for PSD interop measure distances no filter can, so the filter takes their coverages as maps the GPU renders. +fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], capture_offset: usize) -> SvgEffectsFilter { + use graphic_types::EffectOperation; + + // SVG takes a length along each axis as a pair of numbers + let pair = |length: DVec2| format!("{} {}", length.x, length.y); + + let mut primitives = SvgFilterPrimitives::default(); + + // The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result + let mut full = "SourceGraphic".to_string(); + let mut filled = (fill < 1.).then(|| primitives.push("feComponentTransfer", r#"in="SourceGraphic""#, &format!(r#""#))); + // The shadows and glows stacked beneath the content + let mut beneath: Option = None; + + for (index, effect) in (capture_offset..).zip(effects.operations()) { + let (color, inner) = match effect { + EffectOperation::Blur { radius, box_blur, gamma } => { + let radius = DVec2::splat(radius); + if radius.max_element() < 0.01 { + continue; + } + + // What lies beneath blurs together with the content + if let Some(beneath) = beneath.take() { + filled = filled.map(|filled| primitives.composite_beneath(&filled, &beneath)); + full = primitives.composite_beneath(&full, &beneath); + } + + // SVG has no box blur, so a box becomes the Gaussian of the same variance + let sigma = pair(if box_blur { (radius * (radius + 1.) / 3.).map(f64::sqrt) } else { radius }); + let space = if gamma { "sRGB" } else { "linearRGB" }; + let attributes = |input: &str| format!(r#"in="{input}" stdDeviation="{sigma}" color-interpolation-filters="{space}""#); + + filled = filled.map(|filled| primitives.push("feGaussianBlur", &attributes(&filled), "")); + full = primitives.push("feGaussianBlur", &attributes(&full), ""); + continue; + } + EffectOperation::DropShadow { color, .. } => (color, false), + EffectOperation::OuterGlow { color, .. } => match GlowFill::of(&color) { + Some(GlowFill::Solid(color)) => (color, false), + // A gradient's map holds the glow in its own colors, which stack beneath as they are + Some(fill) if !fill.is_invisible() => { + let tinted = primitives.map(EffectCapture { index, plane: 0 }); + beneath = Some(match beneath { + Some(beneath) => primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{beneath}" operator="over""#), ""), + None => tinted, + }); + continue; + } + _ => continue, + }, + EffectOperation::InnerShadow { color, .. } => (color, true), + }; + if color.a() <= 0. { + continue; + } + + // The GPU works out the coverage, knocked out where the content hides it + let coverage = primitives.map(EffectCapture { index, plane: 0 }); + + let flood = primitives.push( + "feFlood", + &format!(r##"flood-color="#{}" flood-opacity="{}""##, SRGBA8::from(color.with_alpha(1.)).to_rgb_hex(), color.a()), + "", + ); + let tinted = primitives.push("feComposite", &format!(r#"in="{flood}" in2="{coverage}" operator="in""#), ""); + + if inner { + // Placed over the image within the full-strength content, so it stays visible over a faded fill + let within = primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{full}" operator="in""#), ""); + let mut over = |image: &str| { + let uncovered = primitives.push("feComposite", &format!(r#"in="{image}" in2="{tinted}" operator="out""#), ""); + primitives.add(&within, &uncovered) + }; + filled = filled.map(|filled| over(&filled)); + full = over(&full); + } else { + beneath = Some(match beneath { + Some(beneath) => primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{beneath}" operator="over""#), ""), + None => tinted, + }); + } + } + + // The filter's result is its last primitive's, so finish with the image shown + let shown = filled.unwrap_or_else(|| full.clone()); + match beneath { + Some(beneath) => { + primitives.composite_beneath(&shown, &beneath); + } + None => { + primitives.push("feOffset", &format!(r#"in="{shown}""#), ""); + } + } + + // The filter covers how far the effects reach past the content + let reach = effects.reach(); + let (min, max) = (bounds[0] - reach, bounds[1] + reach); + let id = format!("effects-{}", generate_uuid()); + write!( + svg_defs, + r#"{}"#, + min.x, + min.y, + max.x - min.x, + max.y - min.y, + primitives.markup + ) + .unwrap(); + + SvgEffectsFilter { + id, + region: [min, max], + maps: primitives.maps, + } +} + +/// Grows a layer's bounds in the scene's space by a length along each of its axes. +fn inflate_bounds(bounds: [DVec2; 2], amount: DVec2) -> kurbo::Rect { + kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y).inflate(amount.x, amount.y) +} + +fn rect_bounds(rect: kurbo::Rect) -> RenderBoundingBox { + RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]) +} + /// The color one paint item contributes, faded by its opacity attributes. pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option { let color = item.element()?; @@ -201,11 +733,22 @@ impl MaskType { } } - fn write_to_defs(self, svg_defs: &mut String, uuid: u64, svg_string: String) { + /// Writes the clip or mask of the masker's `svg_string` into the defs, a mask covering the masker's `region` in the clipped content's user space if it has one. + fn write_to_defs(self, svg_defs: &mut String, uuid: u64, svg_string: String, region: Option<[DVec2; 2]>) { let id = format!("mask-{uuid}"); - match self { - Self::Clip => write!(svg_defs, r##"{svg_string}"##).unwrap(), - Self::Mask => write!(svg_defs, r##"{svg_string}"##).unwrap(), + match (self, region) { + (Self::Clip, _) => write!(svg_defs, r##"{svg_string}"##).unwrap(), + // By default a mask covers only a tenth past the clipped content's geometry, which cuts off its effects + (Self::Mask, Some([min, max])) => write!( + svg_defs, + r##"{svg_string}"##, + min.x, + min.y, + max.x - min.x, + max.y - min.y, + ) + .unwrap(), + (Self::Mask, None) => write!(svg_defs, r##"{svg_string}"##).unwrap(), } } } @@ -218,6 +761,8 @@ pub struct SvgRender { pub transform: DAffine2, /// The images drawn to canvases rather than embedded, by the canvas ID their placeholders name. pub image_data: HashMap, + /// The maps of effects' coverages the filters take, for the GPU to render. + pub effect_maps: Vec, indent: usize, } @@ -228,6 +773,7 @@ impl SvgRender { svg_defs: String::new(), transform: DAffine2::IDENTITY, image_data: HashMap::new(), + effect_maps: Vec::new(), indent: 0, } } @@ -312,6 +858,7 @@ pub struct SvgRenderOutput { pub svg: String, pub svg_defs: String, pub image_data: HashMap, + pub effect_maps: Vec, } impl From<&SvgRenderOutput> for SvgRender { @@ -321,6 +868,7 @@ impl From<&SvgRenderOutput> for SvgRender { svg_defs: value.svg_defs.clone(), transform: DAffine2::IDENTITY, image_data: value.image_data.clone(), + effect_maps: value.effect_maps.clone(), indent: 0, } } @@ -332,6 +880,7 @@ impl From for SvgRenderOutput { svg: val.svg.to_svg_string(), svg_defs: val.svg_defs, image_data: val.image_data, + effect_maps: val.effect_maps, } } } @@ -530,6 +1079,17 @@ pub(crate) fn transform_is_invertible(transform: DAffine2) -> bool { transform.matrix2.determinant().recip().is_finite() } +/// Maps `transform` into the space of `reference`, exactly for the reference itself even when it can't be inverted. +fn transform_relative_to(reference: DAffine2, transform: DAffine2) -> DAffine2 { + if transform == reference { + DAffine2::IDENTITY + } else if transform_is_invertible(reference) { + reference.inverse() * transform + } else { + transform + } +} + /// Maps a gradient's `transform` into the frame handed to the renderer: radial keeps the full matrix (so a /// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the /// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can @@ -672,7 +1232,7 @@ fn create_peniko_gradient_brush(gradient_item: ItemRef<'_, Gradient>, multiplied Some((brush, gradient_to_device)) } -// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data from Monitor nodes. +// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data the editor observes on 'Path' nodes. // This will require that the transform for child layers into that layer space be calculated, or it could be returned from the RenderOutput instead of click targets. #[derive(Debug, Default, Clone, PartialEq, DynAny)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -697,6 +1257,8 @@ pub struct RenderMetadata { /// Per-layer `ATTR_APPEARANCE` item attribute, exposed so message handlers can read it. #[cfg_attr(feature = "serde", serde(skip))] pub appearance_attributes: HashMap>, + /// Per-layer distance its effects paint past its content, in document pixels, for layers with effects. + pub effects_reach: HashMap, pub backgrounds: Vec, } @@ -722,6 +1284,7 @@ impl RenderMetadata { clip_targets, vector_data, appearance_attributes, + effects_reach, backgrounds, } = self; upstream_footprints.extend(other.upstream_footprints.iter()); @@ -734,6 +1297,7 @@ impl RenderMetadata { clip_targets.extend(other.clip_targets.iter()); vector_data.extend(other.vector_data.iter().map(|(id, data)| (*id, data.clone()))); appearance_attributes.extend(other.appearance_attributes.iter().map(|(id, data)| (*id, data.clone()))); + effects_reach.extend(other.effects_reach.iter()); // TODO: Find a better non O(n^2) way to merge backgrounds for background in &other.backgrounds { @@ -783,20 +1347,29 @@ unsafe impl dyn_any::StaticType for dyn Render + Send + Sync { type Static = dyn Render + Send + Sync; } +/// The region a mask of the `masker` placed by `transform` covers in the user space: its drawn bounds grown by the reach of the effects nested inside, or `None` without edges. +fn masker_region(masker: &Graphic, transform: DAffine2) -> Option<[DVec2; 2]> { + let RenderBoundingBox::Rectangle([min, max]) = drawn_bounding_box(masker, transform) else { + return None; + }; + + let reach = nested_effects_reach(masker, transform, EffectOperation::painted_reach); + Some([min - reach, max + reach]) +} + /// Emits one item of graphic content as SVG, wrapped in a group carrying the item's transform, opacity, and blend mode. /// `mask_state` carries the sibling clipping run between a list's items; a lone item has no siblings, so both mask inputs stay inert. fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_state: &mut Option<(u64, MaskType)>, render: &mut SvgRender, render_params: &RenderParams) { let Some(element) = item.element() else { return }; let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); // This item's declared appearance (if any) cascades to descendants lacking their own let child_render_params = item .attribute::(ATTR_APPEARANCE) .and_then(Appearance::declared) .map(|appearance| render_params.for_child_item(appearance)); let render_params = child_render_params.as_ref().unwrap_or(render_params); + let compositing = item.compositing(render_params, transform); let matrix = format_transform_matrix(transform); let mut masked_by = None; @@ -815,7 +1388,8 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st }; render.svg_defs.push_str(&svg.svg_defs); - mask_type.write_to_defs(&mut render.svg_defs, uuid, masker); + render.effect_maps.extend(svg.effect_maps); + mask_type.write_to_defs(&mut render.svg_defs, uuid, masker, masker_region(element, transform)); *mask_state = Some((uuid, mask_type)); } else if let Some((uuid, mask_type)) = *mask_state { @@ -827,29 +1401,47 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st } let render_item = |render: &mut SvgRender| { - render.parent_tag( - "g", - |attributes| { - if !matrix.is_empty() { - attributes.push(ATTR_TRANSFORM, matrix.clone()); - } + // The filter also covers how far the effects nested inside reach past the content, measured in this user space + let bounds = || match drawn_bounding_box(element, transform) { + RenderBoundingBox::Rectangle([min, max]) => { + let nested_reach = nested_effects_reach(element, transform, EffectOperation::painted_reach); + RenderBoundingBox::Rectangle([min - nested_reach, max + nested_reach]) + } + bounds => bounds, + }; + let filter = compositing.svg_filter(render, render_params, bounds, || Graphic::Graphic(Box::new(without_opacity_and_blend_mode(item, element.clone())))); + let filtered = filter.is_some(); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; - if opacity < 1. { - attributes.push("opacity", opacity.to_string()); - } + render_svg_through_filter(render, filter, compositing.opacity, blend_mode, |render| { + render.parent_tag( + "g", + |attributes| { + if !matrix.is_empty() { + attributes.push(ATTR_TRANSFORM, matrix.clone()); + } - if blend_mode != BlendMode::default() { - attributes.push("style", blend_mode.render()); - } - }, - |render| { - let parent_transform = render.transform; - render.transform = parent_transform * transform; - element.render_svg(render, render_params); - render.transform = parent_transform; - }, - ); + // A filter's wrapping group takes the opacity and blend mode instead + if filtered { + return; + } + + let opacity = compositing.opacity_without_effects(); + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + + if blend_mode != BlendMode::default() { + attributes.push("style", blend_mode.render()); + } + }, + |render| { + let parent_transform = render.transform; + render.transform = parent_transform * transform; + element.render_svg(render, render_params); + render.transform = parent_transform; + }, + ); + }); }; // The mask rides an untransformed wrapper so it resolves in this list's space rather than the item's own @@ -874,54 +1466,68 @@ fn render_graphic_item_to_vello<'a>( let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let transform = transform * item_transform; let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); // This item's declared appearance (if any) cascades to descendants lacking their own let child_render_params = item .attribute::(ATTR_APPEARANCE) .and_then(Appearance::declared) .map(|appearance| render_params.for_child_item(appearance)); let render_params = child_render_params.as_ref().unwrap_or(render_params); - - let mut layer = false; + let compositing = item.compositing(render_params, transform); let blend_mode = match render_params.render_mode { RenderMode::Outline => peniko::Mix::Normal, _ => blend_mode_attr.to_peniko(), }; - let mut bounds = RenderBoundingBox::None; + let needs_layer = compositing.opacity < 1. || (render_params.render_mode != RenderMode::Outline && blend_mode_attr != BlendMode::default()); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; - if opacity < 1. || (render_params.render_mode != RenderMode::Outline && blend_mode_attr != BlendMode::default()) { - bounds = element.bounding_box(transform, true); + // The bounds are only worth finding for the layers or effects group that need them + let bounds = if needs_layer || mask_element_and_transform.is_some() || compositing.effects.is_some() { + drawn_bounding_box(element, transform) + } else { + RenderBoundingBox::None + }; - if let RenderBoundingBox::Rectangle(bounds) = bounds { - scene.push_layer( - peniko::Fill::NonZero, - peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver), - opacity, - kurbo::Affine::IDENTITY, - &kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y), - ); - layer = true; - } - } + // The layers and effects group also cover how far the effects nested inside reach past the content + let nested_reach = match bounds { + RenderBoundingBox::Rectangle(_) => nested_effects_reach(element, transform, EffectOperation::painted_reach), + _ => DVec2::ZERO, + }; + let layer_rect = match bounds { + RenderBoundingBox::Rectangle(bounds) => Some(inflate_bounds(bounds, compositing.reach() + nested_reach)), + _ => None, + }; + + let layer = if needs_layer && let Some(rect) = layer_rect { + scene.push_layer( + peniko::Fill::NonZero, + peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver), + compositing.opacity, + kurbo::Affine::IDENTITY, + &rect, + ); + true + } else { + false + }; + + let effects_bounds = || match bounds { + RenderBoundingBox::Rectangle(bounds) => rect_bounds(inflate_bounds(bounds, nested_reach)), + bounds => bounds, + }; + let draw_content = |scene: &mut VelloSceneBuilder| { + compositing.draw_with_effects(scene, effects_bounds, |scene| element.render_to_vello(scene, transform, render_params)); + }; if next_clips && mask_element_and_transform.is_none() { *mask_element_and_transform = Some((element, transform)); - element.render_to_vello(scene, transform, render_params); + draw_content(scene); } else if let Some((mask_element, transform_mask)) = *mask_element_and_transform { if !next_clips { *mask_element_and_transform = None; } - if !layer { - bounds = element.bounding_box(transform, true); - } - - if let RenderBoundingBox::Rectangle(bounds) = bounds { - let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y); + if let Some(rect) = layer_rect { scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., kurbo::Affine::IDENTITY, &rect); mask_element.render_to_vello(scene, transform_mask, &render_params.for_clipper()); scene.push_layer( @@ -933,14 +1539,14 @@ fn render_graphic_item_to_vello<'a>( ); } - element.render_to_vello(scene, transform, render_params); + draw_content(scene); - if matches!(bounds, RenderBoundingBox::Rectangle(_)) { + if layer_rect.is_some() { scene.pop_layer(); scene.pop_layer(); } } else { - element.render_to_vello(scene, transform, render_params); + draw_content(scene); } if layer { @@ -958,6 +1564,14 @@ fn collect_graphic_item_metadata(item: ItemRef<'_, Graphic>, metadata: &mut Rend let mut footprint = footprint; footprint.transform *= item_transform; + if let Some(layer) = item.layer() { + let own_reach = item.attribute::(ATTR_EFFECTS).map_or(DVec2::ZERO, |effects| effects.reach_along_axes(footprint.transform)); + let reach = (own_reach + nested_effects_reach(element, footprint.transform, EffectOperation::painted_reach)).max_element(); + if reach > 0. { + metadata.effects_reach.insert(layer, reach); + } + } + // An anonymous wrapper item (no layer tag) still recurses to reach nested content with "editor:layer_path" attributes element.collect_metadata(metadata, footprint, item.layer(), child_appearance); } @@ -1078,7 +1692,7 @@ impl Render for Graphic { } Graphic::RasterCPU(item) => render_raster_cpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params), Graphic::RasterGPU(item) => render_raster_gpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params), - Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, render_params), + Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, transform, render_params), Graphic::Gradient(item) => render_gradient_item_to_vello(ItemRef::Item(item), scene, transform, render_params), Graphic::Text(item) => render_text_item_to_vello(ItemRef::Item(item), scene, transform, render_params), Graphic::GraphicList(list) => list.render_to_vello(scene, transform, render_params), @@ -1448,12 +2062,16 @@ impl Render for List { } /// Emits one vector shape as SVG, with no wrapping group of its own. -fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &mut SvgRender, render_params: &RenderParams) { +/// When `filtered`, the group applying the item's effects takes its opacity and blend mode instead. +fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, filtered: bool, render: &mut SvgRender, render_params: &RenderParams) { let paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let blend_mode_attr: BlendMode = if filtered { BlendMode::default() } else { item.attribute_cloned_or_default(ATTR_BLEND_MODE) }; + let opacity = if filtered { + 1. + } else { + item.compositing(render_params, item_transform).opacity_without_effects() + }; // The item's own declared appearance wins over one cascading down from an ancestor let own_appearance = item.attribute::(ATTR_APPEARANCE).and_then(Appearance::declared); @@ -1627,7 +2245,6 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & attributes.push_val(stroke_shape_attribute); attributes.push_val(stroke_attribute); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; if opacity < 1. { attributes.push("opacity", opacity.to_string()); } @@ -1660,14 +2277,17 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let mut masked_by = None; if next_clips && clip_mask_state.is_none() { - let masker = Graphic::VectorList(List::new_from_item(Item::from_parts(vector.clone(), item.clone_item_attributes()))); + // The shadows and glows the masker casts don't widen the area its clipped content shows in + let mut masker = Item::from_parts(vector.clone(), item.clone_item_attributes()); + masker.remove_attribute::(ATTR_EFFECTS); + let masker = Graphic::VectorList(List::new_from_item(masker)); let mask_type = if masker.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask }; let uuid = generate_uuid(); let mut masker_svg = SvgRender::new(); masker.render_svg(&mut masker_svg, &render_params.for_clipper()); render.svg_defs.push_str(&masker_svg.svg_defs); - mask_type.write_to_defs(&mut render.svg_defs, uuid, masker_svg.svg.to_svg_string()); + mask_type.write_to_defs(&mut render.svg_defs, uuid, masker_svg.svg.to_svg_string(), masker_region(&masker, DAffine2::IDENTITY)); *clip_mask_state = Some((uuid, mask_type)); } else if let Some((uuid, mask_type)) = *clip_mask_state { @@ -1678,22 +2298,40 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask masked_by = Some((mask_type.to_attribute(), format!("url(#mask-{uuid})"))); } + let compositing = item.compositing(render_params, item.attribute_cloned_or_default(ATTR_TRANSFORM)); + let render_shape = |render: &mut SvgRender| { + let bounds = || { + let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let appearance = item.attribute::(ATTR_APPEARANCE).and_then(Appearance::declared); + let stroke = appearance.or(render_params.inherited_appearance.as_ref()).and_then(|appearance| appearance.fill_and_stroke().stroke); + let paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); + + vector + .stroke_inclusive_bounding_box_with_transform(paths, item_transform, stroke.as_ref()) + .map_or(RenderBoundingBox::None, RenderBoundingBox::Rectangle) + }; + let filter = compositing.svg_filter(render, render_params, bounds, || Graphic::Vector(Box::new(without_opacity_and_blend_mode(item, vector.clone())))); + let filtered = filter.is_some(); + let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); + + render_svg_through_filter(render, filter, compositing.opacity, blend_mode, |render| { + render_vector_shape_svg(item, vector, filtered, render, render_params) + }); + }; + // Item geometry is baked into the path data instead of a group transform, so mask coordinates line up match masked_by { - Some((attribute, selector)) => render.parent_tag( - "g", - |attributes| attributes.push(attribute, selector), - |render| render_vector_shape_svg(item, vector, render, render_params), - ), - None => render_vector_shape_svg(item, vector, render, render_params), + Some((attribute, selector)) => render.parent_tag("g", |attributes| attributes.push(attribute, selector), render_shape), + None => render_shape(render), } } -/// Whether `bounds` placed by `transform` overlaps the scene once widened by `inflation`, which is measured in the space `inflation_transform` maps from. -fn overlaps_scene(scene: &VelloSceneBuilder, bounds: [DVec2; 2], transform: DAffine2, inflation: f64, inflation_transform: DAffine2) -> bool { +/// Whether `bounds` placed by `transform` overlaps the scene once widened by `inflation`, measured in the space `inflation_transform` maps from, and by its effects' `reach`, measured in the scene's space. +fn overlaps_scene(scene: &VelloSceneBuilder, bounds: [DVec2; 2], transform: DAffine2, inflation: f64, inflation_transform: DAffine2, reach: f64) -> bool { let view = DAffine2::from_cols_array(&scene.view().as_coeffs()); let (largest_scale, _) = singular_values(view * inflation_transform); - let inflation = inflation * largest_scale; + let (largest_view_scale, _) = singular_values(view); + let inflation = inflation * largest_scale + reach * largest_view_scale; let [min, max] = (view * transform * Quad::from_box(bounds)).bounding_box(); min.x - inflation < scene.width() as f64 && max.x + inflation > 0. && min.y - inflation < scene.height() as f64 && max.y + inflation > 0. @@ -1715,9 +2353,8 @@ fn render_vector_item_to_vello( let element_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); let multiplied_transform = parent_transform * item_transform; + let compositing = item.compositing(render_params, multiplied_transform); // The item's own declared appearance wins over one cascading down from an ancestor let own_appearance = item.attribute::(ATTR_APPEARANCE).and_then(Appearance::declared); @@ -1768,7 +2405,7 @@ fn render_vector_item_to_vello( // Vello only culls after expanding strokes and flattening paths, so an item outside the scene is skipped before any of that work let stroke_inflation = stroke.map_or(0., |stroke| stroke.max_aabb_inflation(true)).max(get_outline_styles(render_params).0.width); - if !overlaps_scene(scene, layer_bounds, multiplied_transform, stroke_inflation, element_transform) { + if !overlaps_scene(scene, layer_bounds, multiplied_transform, stroke_inflation, element_transform, compositing.reach().length()) { if next_clips && clip_masker.is_none() { *clip_masker = Some(List::new_from_item(Item::from_parts(element.clone(), item.clone_item_attributes()))); } else if clip_masker.is_some() && !next_clips { @@ -1780,11 +2417,11 @@ fn render_vector_item_to_vello( let Some(placed) = item.placed_contours(applied_stroke_transform) else { return }; let path = placed.path(); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let opacity = compositing.opacity; let needs_blend_layer = opacity < 1. || blend_mode_attr != BlendMode::default(); - // Shared by the blend and clipping layers below, so it is only worth deriving when one of them is pushed - let layer_geometry = (needs_blend_layer || clip_masker.is_some()).then(|| { + // Shared by the layers and effects group below, so it is only worth deriving when one of them is pushed + let layer_geometry = (needs_blend_layer || clip_masker.is_some() || compositing.effects.is_some()).then(|| { // `max_aabb_inflation` is in `applied_stroke_transform`-space; `layer_bounds` is path-local and `push_layer` re-applies `multiplied_transform`. // Divide by the smaller axial scale to cover the stroke in both axes after Vello's transform. Skip on a degenerate transform. let (_, smallest_scale) = singular_values(applied_stroke_transform); @@ -1798,17 +2435,32 @@ fn render_vector_item_to_vello( ) }); + // The layers also cover what the effects paint past the content + let effects_inflation = compositing.reach_in_content_space(); + let layer_rect_with_effects = |layer_rect: kurbo::Rect| layer_rect.inflate(effects_inflation.x, effects_inflation.y); + if needs_blend_layer && let Some((layer_affine, layer_rect)) = layer_geometry { layer = true; - scene.push_layer(peniko::Fill::NonZero, peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver), opacity, layer_affine, &layer_rect); + scene.push_layer( + peniko::Fill::NonZero, + peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver), + opacity, + layer_affine, + &layer_rect_with_effects(layer_rect), + ); } // Pushed inside the blend layer so the mask cuts this item's own paint rather than the composited result let mut clip_layers = false; if next_clips && clip_masker.is_none() { - *clip_masker = Some(List::new_from_item(Item::from_parts(element.clone(), item.clone_item_attributes()))); + // The shadows and glows the masker casts don't widen the area its clipped content shows in + let mut masker = Item::from_parts(element.clone(), item.clone_item_attributes()); + masker.remove_attribute::(ATTR_EFFECTS); + *clip_masker = Some(List::new_from_item(masker)); } else if let Some(masker) = clip_masker.as_ref() { if let Some((layer_affine, layer_rect)) = layer_geometry { + let layer_rect = layer_rect_with_effects(layer_rect); + scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., layer_affine, &layer_rect); masker.render_to_vello(scene, parent_transform, &render_params.for_clipper()); scene.push_layer( @@ -1979,76 +2631,79 @@ fn render_vector_item_to_vello( scene.fill_path(peniko::Fill::NonZero, element_affine, outline_color_peniko, None, &outline); } _ => { - if use_layer { - let cloned_element = element.clone(); - - // The mask must draw at full alpha so `SrcOut` fully zeroes the path interior. - // The outer opacity/blend layer (above) handles the user-set opacity. - let mut mask_item = Item::new_from_element(cloned_element) - .with_attribute(ATTR_PATHS, element_paths.clone()) - .with_attribute(ATTR_GEOMETRY_CACHE, item.geometry_cache()) - .with_attribute(ATTR_TRANSFORM, item_transform); - let black_fill = Graphic::ColorList(List::new_from_element(Color::BLACK)); - mask_item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), black_fill)); - let vector_list = List::new_from_item(mask_item); - - let bounds = contours_bounding_box(&contours, multiplied_transform).unwrap_or(layer_bounds); - // This branch is gated on `can_draw_aligned_stroke`, which already requires every subpath is closed - let inflation = stroke.map_or(0., |stroke| stroke.max_aabb_inflation(true)); - let (largest_scale, _) = singular_values(applied_stroke_transform); - let quad = Quad::from_box(bounds).inflate(inflation * largest_scale); - let bounds = quad.bounding_box(); - let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y); - - let compose = if stroke.is_some_and(|x| x.align == StrokeAlign::Outside) { - peniko::Compose::SrcOut - } else { - peniko::Compose::SrcIn - }; + let effects_bounds = || layer_geometry.map_or(RenderBoundingBox::None, |(layer_affine, layer_rect)| rect_bounds(layer_affine.transform_rect_bbox(layer_rect))); + compositing.draw_with_effects(scene, effects_bounds, |scene| { + if use_layer { + let cloned_element = element.clone(); + + // The mask must draw at full alpha so `SrcOut` fully zeroes the path interior. + // The outer opacity/blend layer (above) handles the user-set opacity. + let mut mask_item = Item::new_from_element(cloned_element) + .with_attribute(ATTR_PATHS, element_paths.clone()) + .with_attribute(ATTR_GEOMETRY_CACHE, item.geometry_cache()) + .with_attribute(ATTR_TRANSFORM, item_transform); + let black_fill = Graphic::ColorList(List::new_from_element(Color::BLACK)); + mask_item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), black_fill)); + let vector_list = List::new_from_item(mask_item); + + let bounds = contours_bounding_box(&contours, multiplied_transform).unwrap_or(layer_bounds); + // This branch is gated on `can_draw_aligned_stroke`, which already requires every subpath is closed + let inflation = stroke.map_or(0., |stroke| stroke.max_aabb_inflation(true)); + let (largest_scale, _) = singular_values(applied_stroke_transform); + let quad = Quad::from_box(bounds).inflate(inflation * largest_scale); + let bounds = quad.bounding_box(); + let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y); + + let compose = if stroke.is_some_and(|x| x.align == StrokeAlign::Outside) { + peniko::Compose::SrcOut + } else { + peniko::Compose::SrcIn + }; - if wants_stroke_below { - scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., kurbo::Affine::IDENTITY, &rect); - vector_list.render_to_vello(scene, parent_transform, &render_params.for_alignment(applied_stroke_transform)); - scene.push_layer(peniko::Fill::NonZero, peniko::BlendMode::new(peniko::Mix::Normal, compose), 1., kurbo::Affine::IDENTITY, &rect); + if wants_stroke_below { + scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., kurbo::Affine::IDENTITY, &rect); + vector_list.render_to_vello(scene, parent_transform, &render_params.for_alignment(applied_stroke_transform)); + scene.push_layer(peniko::Fill::NonZero, peniko::BlendMode::new(peniko::Mix::Normal, compose), 1., kurbo::Affine::IDENTITY, &rect); - do_stroke(scene, 2.); + do_stroke(scene, 2.); - scene.pop_layer(); - scene.pop_layer(); + scene.pop_layer(); + scene.pop_layer(); - do_fill(scene); - } else { - // Fill first (unclipped), then stroke (clipped) above - do_fill(scene); + do_fill(scene); + } else { + // Fill first (unclipped), then stroke (clipped) above + do_fill(scene); - scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., kurbo::Affine::IDENTITY, &rect); - vector_list.render_to_vello(scene, parent_transform, &render_params.for_alignment(applied_stroke_transform)); - scene.push_layer(peniko::Fill::NonZero, peniko::BlendMode::new(peniko::Mix::Normal, compose), 1., kurbo::Affine::IDENTITY, &rect); + scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., kurbo::Affine::IDENTITY, &rect); + vector_list.render_to_vello(scene, parent_transform, &render_params.for_alignment(applied_stroke_transform)); + scene.push_layer(peniko::Fill::NonZero, peniko::BlendMode::new(peniko::Mix::Normal, compose), 1., kurbo::Affine::IDENTITY, &rect); - do_stroke(scene, 2.); + do_stroke(scene, 2.); - scene.pop_layer(); - scene.pop_layer(); - } - } else { - // Non-aligned strokes or open paths: default order behavior - enum Op { - Fill, - Stroke, - } + scene.pop_layer(); + scene.pop_layer(); + } + } else { + // Non-aligned strokes or open paths: default order behavior + enum Op { + Fill, + Stroke, + } - let order = match wants_stroke_below { - true => [Op::Stroke, Op::Fill], - false => [Op::Fill, Op::Stroke], // Default - }; + let order = match wants_stroke_below { + true => [Op::Stroke, Op::Fill], + false => [Op::Fill, Op::Stroke], // Default + }; - for operation in &order { - match operation { - Op::Fill => do_fill(scene), - Op::Stroke => do_stroke(scene, 1.), + for operation in &order { + match operation { + Op::Fill => do_fill(scene), + Op::Stroke => do_stroke(scene, 1.), + } } } - } + }); } } @@ -2086,14 +2741,9 @@ fn collect_vector_items_metadata<'a>( if let Some(element_id) = caller_element_id.or(item.layer()) { let reference_transform = *reference_transforms.entry(element_id).or_insert(transform); - let reference_inverse = if transform_is_invertible(reference_transform) { - reference_transform.inverse() - } else { - DAffine2::IDENTITY - }; let source_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); - let item_relative_transform = reference_inverse * transform; + let item_relative_transform = transform_relative_to(reference_transform, transform); // Outlines trace the source geometry as drawn (actual letterforms, open paths left open) let mut outlines_unwrapped = Vec::new(); @@ -2360,13 +3010,28 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let compositing = item.compositing(render_params, transform); if image.data.is_empty() { return; } + let bounds = || RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()); + let filter = compositing.svg_filter(render, render_params, bounds, || Graphic::RasterCPU(Box::new(without_opacity_and_blend_mode(item, image.clone())))); + + // A filter's wrapping group takes the opacity and blend mode instead + let (opacity, blend_mode) = match filter { + Some(_) => (1., BlendMode::default()), + None => (compositing.opacity_without_effects(), blend_mode_attr), + }; + + render_svg_through_filter(render, filter, compositing.opacity, blend_mode_attr, |render| { + render_raster_cpu_image_svg(image, transform, opacity, blend_mode, render, render_params) + }); +} + +/// Emits a CPU raster's image as SVG, either as a placeholder for a canvas or as an embedded PNG. +fn render_raster_cpu_image_svg(image: &Raster, transform: DAffine2, opacity: f32, blend_mode: BlendMode, render: &mut SvgRender, render_params: &RenderParams) { if render_params.to_canvas() { // An image drawn smaller than its pixels is sent at a resolution halved enough times to still cover each screen pixel let document_to_screen = DAffine2::from_scale(DVec2::splat(render_params.canvas_image_scale)); @@ -2395,13 +3060,12 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe attributes.push("width", size.x.to_string()); attributes.push("height", size.y.to_string()); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; if opacity < 1. { attributes.push("opacity", opacity.to_string()); } - if blend_mode_attr != BlendMode::default() { - attributes.push("style", blend_mode_attr.render()); + if blend_mode != BlendMode::default() { + attributes.push("style", blend_mode.render()); } }, |render| { @@ -2425,12 +3089,11 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe attributes.push(ATTR_TRANSFORM, matrix); } - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; if opacity < 1. { attributes.push("opacity", opacity.to_string()); } - if blend_mode_attr != BlendMode::default() { - attributes.push("style", blend_mode_attr.render()); + if blend_mode != BlendMode::default() { + attributes.push("style", blend_mode.render()); } }); } @@ -2444,11 +3107,11 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut V } let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let transform_attribute: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let compositing = item.compositing(render_params, transform * transform_attribute); let blend_mode = blend_mode_attr.to_peniko(); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let opacity = compositing.opacity; let mut layer = false; let whole_bounds = || match item { @@ -2459,13 +3122,11 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut V && let RenderBoundingBox::Rectangle(bounds) = whole_bounds() { let blending = peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver); - let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y); + let rect = inflate_bounds(bounds, compositing.reach()); scene.push_layer(peniko::Fill::NonZero, blending, opacity, kurbo::Affine::IDENTITY, &rect); layer = true; } - let transform_attribute: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - if let RenderMode::Outline = render_params.render_mode { let outline_transform: DAffine2 = transform * transform_attribute; draw_raster_outline(scene, &outline_transform, render_params); @@ -2480,7 +3141,10 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut V let image_transform = transform * transform_attribute * DAffine2::from_scale(1. / DVec2::new(image.width as f64, image.height as f64)); let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad); - scene.draw_raster(image.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array())); + let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()); + compositing.draw_with_effects(scene, item_bounds, |scene| { + scene.draw_raster(image.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array())) + }); if layer { scene.pop_layer(); @@ -2572,8 +3236,8 @@ impl Render for List> { fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { let Some(raster) = item.element() else { return }; let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let transform_attribute: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let compositing = item.compositing(render_params, transform * transform_attribute); let clip_attr: bool = item.attribute_cloned_or_default(ATTR_CLIPPING_MASK); let blend_mode = match render_params.render_mode { RenderMode::Outline => peniko::Mix::Normal, @@ -2586,19 +3250,17 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut V ItemRef::ListItem(list, _) => list.bounding_box(transform, true), ItemRef::Item(item) => item.bounding_box(transform, true), }; - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let opacity = compositing.opacity; let any_nondefault = blend_mode_attr != BlendMode::default() || opacity < 1. || clip_attr; if (render_params.render_mode != RenderMode::Outline && any_nondefault) && let RenderBoundingBox::Rectangle(bounds) = whole_bounds() { let blending = peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver); - let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y); + let rect = inflate_bounds(bounds, compositing.reach()); scene.push_layer(peniko::Fill::NonZero, blending, opacity, kurbo::Affine::IDENTITY, &rect); layer = true; } - let transform_attribute: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - if let RenderMode::Outline = render_params.render_mode { let outline_transform = transform * transform_attribute; draw_raster_outline(scene, &outline_transform, render_params); @@ -2615,7 +3277,11 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster>, scene: &mut V let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad); let image_transform = transform * transform_attribute * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64)); - scene.draw_texture(raster.texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array())); + + let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()); + compositing.draw_with_effects(scene, item_bounds, |scene| { + scene.draw_texture(raster.texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array())) + }); if layer { scene.pop_layer() @@ -2640,9 +3306,9 @@ impl Render for List { } } - fn render_to_vello(&self, scene: &mut VelloSceneBuilder, _parent_transform: DAffine2, render_params: &RenderParams) { + fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) { for index in 0..self.len() { - render_color_item_to_vello(ItemRef::ListItem(self, index), scene, render_params); + render_color_item_to_vello(ItemRef::ListItem(self, index), scene, parent_transform, render_params); } } } @@ -2676,14 +3342,13 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende }); } -/// Draws one item of color content into the Vello scene, covering the whole render area. -fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, render_params: &RenderParams) { +/// Draws one item of color content into the Vello scene, covering the whole render area, with `parent_transform` placing the space it lies in, which its effects follow. +fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) { let Some(color) = item.element() else { return }; let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let compositing = item.compositing(render_params, parent_transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM)); let blend_mode = blend_mode_attr.to_peniko(); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let opacity = compositing.opacity; let vello_color = SRGBA8::from(*color).to_peniko_color(); @@ -2693,7 +3358,7 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu layer = true; } - scene.fill_viewport(vello_color, None); + compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(vello_color, None)); if layer { scene.pop_layer(); @@ -2873,12 +3538,11 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM); let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); let gradient_transform = parent_transform * transform; + let compositing = item.compositing(render_params, gradient_transform); let blend_mode = blend_mode_attr.to_peniko(); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let opacity = compositing.opacity; let settings = gradient_settings_from_item(item); let samples = spread_adjusted_samples(gradient, settings, gradient_form); @@ -2904,7 +3568,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS layer = true; } - scene.fill_viewport(&fill, Some(brush_transform)); + compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(&fill, Some(brush_transform))); if layer { scene.pop_layer(); @@ -2917,7 +3581,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS fn collect_gradient_items_metadata<'a>(items: impl Iterator>, metadata: &mut RenderMetadata, element_id: Option) { let Some(element_id) = element_id else { return }; - let mut item_zero_inverse = None; + let mut item_zero_transform = None; let mut outline_targets = Vec::new(); let mut click_targets = Vec::new(); for item in items { @@ -2925,10 +3589,10 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator, x_offset: f3 let run = glyph_run.run(); let font = run.font(); let font_size_pts = run.font_size(); - let normalized_coords: Vec = run.normalized_coords().iter().map(|c| NormalizedCoord::from_bits(*c)).collect(); + let normalized_coords: Vec = run.normalized_coords().iter().map(|c| NormalizedCoord::from_bits(c.to_bits())).collect(); let Ok(font_ref) = SkrifaFontRef::from_index(font.data.as_ref(), font.index) else { return }; let outlines = font_ref.outline_glyphs(); @@ -3085,7 +3749,7 @@ fn text_item_size_and_transform(item: ItemRef<'_, String>) -> Option<(DVec2, DAf pub fn text_list_bounding_box(list: &List, outer_transform: DAffine2) -> RenderBoundingBox { let mut bounds: Option<[DVec2; 2]> = None; for index in 0..list.len() { - accumulate_text_item_bounds(ItemRef::ListItem(list, index), outer_transform, &mut bounds); + accumulate_text_item_bounds(ItemRef::ListItem(list, index), outer_transform, false, &mut bounds); } match bounds { Some(bounds) => RenderBoundingBox::Rectangle(bounds), @@ -3093,11 +3757,14 @@ pub fn text_list_bounding_box(list: &List, outer_transform: DAffine2) -> } } -/// Folds one laid-out text item's corner points into the running bounds. -fn accumulate_text_item_bounds(item: ItemRef<'_, String>, outer_transform: DAffine2, bounds: &mut Option<[DVec2; 2]>) { +/// Folds one laid-out text item's corner points into the running bounds, padded by its font size for glyphs overhanging their layout box if `padded`. +fn accumulate_text_item_bounds(item: ItemRef<'_, String>, outer_transform: DAffine2, padded: bool, bounds: &mut Option<[DVec2; 2]>) { let Some((size, transform)) = text_item_size_and_transform(item) else { return }; + let padding = if padded { item.attribute_cloned_or(ATTR_FONT_SIZE, DEFAULT_FONT_SIZE) } else { 0. }; + let (min, max) = (DVec2::splat(-padding), size + padding); + let full_transform = outer_transform * transform; - for corner in [DVec2::ZERO, DVec2::new(size.x, 0.), DVec2::new(0., size.y), size] { + for corner in [min, DVec2::new(max.x, min.y), DVec2::new(min.x, max.y), max] { let point = full_transform.transform_point2(corner); *bounds = Some(match *bounds { Some([min, max]) => [min.min(point), max.max(point)], @@ -3139,7 +3806,7 @@ fn graphic_thumbnail_bounding_box(graphic: &Graphic, item_transform: DAffine2) - match graphic { Graphic::Text(item) => { let mut bounds = None; - accumulate_text_item_bounds(ItemRef::Item(item), item_transform, &mut bounds); + accumulate_text_item_bounds(ItemRef::Item(item), item_transform, false, &mut bounds); match bounds { Some(bounds) => RenderBoundingBox::Rectangle(bounds), None => RenderBoundingBox::None, @@ -3156,6 +3823,37 @@ fn graphic_thumbnail_bounding_box(graphic: &Graphic, item_transform: DAffine2) - } } +/// The bounds a graphic draws within, like the `BoundingBox` trait's with strokes included, but laying out its text, which that reports as `None`. +/// O(items), with a layout for each text item. +fn drawn_bounding_box(graphic: &Graphic, transform: DAffine2) -> RenderBoundingBox { + let mut text_bounds = None; + match graphic { + Graphic::Text(item) => accumulate_text_item_bounds(ItemRef::Item(item), transform, true, &mut text_bounds), + Graphic::TextList(list) => (0..list.len()).for_each(|index| accumulate_text_item_bounds(ItemRef::ListItem(list, index), transform, true, &mut text_bounds)), + Graphic::Graphic(item) => return drawn_bounding_box(item.element(), transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM)), + Graphic::GraphicList(list) => { + let mut combined = RenderBoundingBox::None; + for index in 0..list.len() { + let Some(element) = list.element(index) else { continue }; + let item_transform = transform * list.attribute_cloned_or_default::(ATTR_TRANSFORM, index); + + combined = match (combined, drawn_bounding_box(element, item_transform)) { + (RenderBoundingBox::Infinite, _) | (_, RenderBoundingBox::Infinite) => return RenderBoundingBox::Infinite, + (RenderBoundingBox::Rectangle(existing), RenderBoundingBox::Rectangle(bounds)) => RenderBoundingBox::Rectangle(Quad::combine_bounds(existing, bounds)), + (RenderBoundingBox::None, bounds) | (bounds, RenderBoundingBox::None) => bounds, + }; + } + return combined; + } + other => return other.bounding_box(transform, true), + } + + match text_bounds { + Some(bounds) => RenderBoundingBox::Rectangle(bounds), + None => RenderBoundingBox::None, + } +} + /// Emits one item of text content as SVG, laying out its glyphs and wrapping them in a styled group. fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, render_params: &RenderParams) { let Some(text) = item.element() else { return }; @@ -3164,8 +3862,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende } let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); + let compositing = item.compositing(render_params, transform); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let font: Resource = { let f: Resource = item.attribute_cloned_or_default(ATTR_FONT); @@ -3178,7 +3875,6 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende let max_height = item.attribute::(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.); let letter_tilt: f64 = item.attribute_cloned_or(ATTR_LETTER_TILT, 0.); let align: text_nodes::TextAlign = item.attribute_cloned_or_default(ATTR_TEXT_ALIGN); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; let typesetting = text_nodes::TypesettingConfig { font_size, @@ -3191,11 +3887,17 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende }; let mut glyph_paths: Vec = Vec::new(); + let mut layout_bounds = RenderBoundingBox::None; text_nodes::TextContext::with_thread_local(|ctx| { let Some(layout) = ctx.layout_text(text, &font, typesetting) else { return }; let tilt_tan = letter_tilt.to_radians().tan(); + // Padded by the font size, since glyphs can overhang their layout box + let alignment_width = max_width.unwrap_or(layout.full_width() as f64); + let padded = Quad::from_box([DVec2::splat(-font_size), DVec2::new(alignment_width, layout.height() as f64) + font_size]); + layout_bounds = RenderBoundingBox::Rectangle((transform * padded).bounding_box()); + text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| { draw_glyph_run_to_bezpaths(glyph_run, x_offset, space_extra, tilt_tan, |bez_path| { glyph_paths.push(bez_path.to_svg()); @@ -3207,37 +3909,47 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende return; } - // Wrap all glyph elements in a with the item's transform/opacity/blend-mode. - render.parent_tag( - "g", - |attributes| { - let matrix = format_transform_matrix(transform); - if !matrix.is_empty() { - attributes.push("transform", matrix); - } - if opacity < 1. { - attributes.push("opacity", opacity.to_string()); - } - if blend_mode_attr != BlendMode::default() { - attributes.push("style", blend_mode_attr.render()); - } - }, - |render| { - for path_d in glyph_paths { - render.leaf_tag("path", |attributes| { - attributes.push("d", path_d); - if let RenderMode::Outline = render_params.render_mode { - attributes.push("fill", "none"); - attributes.push("stroke", "black"); - attributes.push("stroke-width", "1"); - } else { - attributes.push("fill", "black"); - attributes.push("fill-rule", "nonzero"); - } - }); - } - }, - ); + let filter = compositing.svg_filter(render, render_params, || layout_bounds, || Graphic::Text(without_opacity_and_blend_mode(item, text.clone()))); + let filtered = filter.is_some(); + + // Wrap all glyph elements in a with the item's transform/opacity/blend-mode, which a filter's wrapping group takes instead + render_svg_through_filter(render, filter, compositing.opacity, blend_mode_attr, |render| { + render.parent_tag( + "g", + |attributes| { + let matrix = format_transform_matrix(transform); + if !matrix.is_empty() { + attributes.push("transform", matrix); + } + if filtered { + return; + } + + let opacity = compositing.opacity_without_effects(); + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + if blend_mode_attr != BlendMode::default() { + attributes.push("style", blend_mode_attr.render()); + } + }, + |render| { + for path_d in glyph_paths { + render.leaf_tag("path", |attributes| { + attributes.push("d", path_d); + if let RenderMode::Outline = render_params.render_mode { + attributes.push("fill", "none"); + attributes.push("stroke", "black"); + attributes.push("stroke-width", "1"); + } else { + attributes.push("fill", "black"); + attributes.push("fill-rule", "nonzero"); + } + }); + } + }, + ); + }); } /// Draws one item of text content into the Vello scene, laying out its glyphs under the item's styling. @@ -3260,9 +3972,8 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut VelloSceneBu let letter_tilt: f64 = item.attribute_cloned_or(ATTR_LETTER_TILT, 0.); let align: text_nodes::TextAlign = item.attribute_cloned_or_default(ATTR_TEXT_ALIGN); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); - let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.); - let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; + let compositing = item.compositing(render_params, transform * item_transform); + let opacity = compositing.opacity; let typesetting = text_nodes::TypesettingConfig { font_size, @@ -3279,28 +3990,38 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut VelloSceneBu text_nodes::TextContext::with_thread_local(|ctx| { let Some(layout) = ctx.layout_text(text, &font, typesetting) else { return }; - let needs_layer = opacity < 1. || blend_mode_attr != BlendMode::default(); - if needs_layer { + let transformed_bounds = || { let alignment_width = max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width()); - let blending = peniko::BlendMode::new(blend_mode_attr.to_peniko(), peniko::Compose::SrcOver); let padding = font_size; let bounds = kurbo::Rect::new(-padding, -padding, alignment_width as f64 + padding, layout.height() as f64 + padding); - let transformed_bounds = affine.transform_rect_bbox(bounds); - scene.push_layer(peniko::Fill::NonZero, blending, opacity, kurbo::Affine::IDENTITY, &transformed_bounds); + affine.transform_rect_bbox(bounds) + }; + + let needs_layer = opacity < 1. || blend_mode_attr != BlendMode::default(); + if needs_layer { + let blending = peniko::BlendMode::new(blend_mode_attr.to_peniko(), peniko::Compose::SrcOver); + let reach = compositing.reach(); + scene.push_layer(peniko::Fill::NonZero, blending, opacity, kurbo::Affine::IDENTITY, &transformed_bounds().inflate(reach.x, reach.y)); } let tilt_tan = letter_tilt.to_radians().tan(); - text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| { - draw_glyph_run_to_bezpaths(glyph_run, x_offset, space_extra, tilt_tan, |bez_path| { - if let RenderMode::Outline = render_params.render_mode { - let (outline_stroke, outline_color) = get_outline_styles(render_params); - scene.stroke(&outline_stroke, affine, outline_color, None, bez_path); - } else { - scene.fill(peniko::Fill::NonZero, affine, peniko::Color::BLACK, None, bez_path); - } - }); - }); + compositing.draw_with_effects( + scene, + || rect_bounds(transformed_bounds()), + |scene| { + text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| { + draw_glyph_run_to_bezpaths(glyph_run, x_offset, space_extra, tilt_tan, |bez_path| { + if let RenderMode::Outline = render_params.render_mode { + let (outline_stroke, outline_color) = get_outline_styles(render_params); + scene.stroke(&outline_stroke, affine, outline_color, None, bez_path); + } else { + scene.fill(peniko::Fill::NonZero, affine, peniko::Color::BLACK, None, bez_path); + } + }); + }); + }, + ); if needs_layer { scene.pop_layer(); @@ -3312,17 +4033,12 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut VelloSceneBu /// which `Graphic::collect_metadata` records as `local_transforms[element_id]`. fn collect_text_items_metadata<'a>(items: impl Iterator>, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option) { let mut item_zero_transform = None; - let mut item_zero_inverse = DAffine2::IDENTITY; let mut accumulated_click_targets: HashMap>> = HashMap::new(); for item in items { // The first item's transform is the reference all targets bake against - let item_zero_transform = *item_zero_transform.get_or_insert_with(|| { - let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - item_zero_inverse = if transform.matrix2.determinant() != 0. { transform.inverse() } else { DAffine2::IDENTITY }; - transform - }); + let item_zero_transform = *item_zero_transform.get_or_insert_with(|| item.attribute_cloned_or_default(ATTR_TRANSFORM)); let Some(element_id) = caller_element_id.or(item.layer()) else { continue }; @@ -3334,7 +4050,7 @@ fn collect_text_items_metadata<'a>(items: impl Iterator graphic_types::EffectOperation { + graphic_types::EffectOperation::DropShadow { + color: Color::BLACK, + angle, + distance, + spread: 0., + size, + contour: Default::default(), + knockout: true, + } + } + + #[test] + fn svg_effects_filters_take_shadows_as_maps_the_gpu_renders() { + let mut defs = String::new(); + let filter = write_svg_effects_filter(&mut defs, &Effects::from_operations([drop_shadow(180., 4., 2.)]), 1., [DVec2::ZERO, DVec2::splat(10.)], 0); + + // The shadow's coverage waits in a placeholder that leaves nothing covered, which its map replaces + assert_eq!(filter.maps.len(), 1); + assert_eq!(filter.maps[0].capture, EffectCapture { index: 0, plane: 0 }); + assert!( + defs.contains(&format!(r#""#, filter.maps[0].id, filter.maps[0].result)), + "{defs}" + ); + } + + #[test] + fn svg_effects_filters_measure_lengths_as_given_in_their_effect_space() { + let mut defs = String::new(); + + // The filter's user space is the effects' own, so the shadow's 7 unit reach is 7 units, and its map is numbered by the run's place in the list + let filter = write_svg_effects_filter(&mut defs, &Effects::from_operations([drop_shadow(180., 4., 2.)]), 1., [DVec2::ZERO, DVec2::splat(10.)], 2); + + assert!(defs.contains(r#"x="-7" y="-7" width="24" height="24""#), "{defs}"); + assert_eq!(filter.region, [DVec2::splat(-7.), DVec2::splat(17.)]); + assert_eq!(filter.maps[0].capture, EffectCapture { index: 2, plane: 0 }); + } + + /// The SVG of a 10 unit orange square blurred by 3 units, placed by a scale of 2 applied before the blur, or after it when `scaled_after`. + fn blurred_square_scaled_svg(scaled_after: bool) -> String { + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + let blur = EffectOperation::Blur { + radius: 3., + box_blur: false, + gamma: false, + }; + let mut item = orange_square_item(&[], 1., 1.); + if !scaled_after { + item.set_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.))); + } + stamp_effect(&mut item, Effect::new(&blur)); + if scaled_after { + item.set_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.))); + } + + let mut render = SvgRender::new(); + List::new_from_item(item).render_svg(&mut render, &RenderParams::default()); + render.svg.to_svg_string() + } + + #[test] + fn svg_effects_before_a_transform_scale_with_it() { + // The filter measures in the square's own units, which the group around it scales up by 2, before the square returns to the user space inside + let svg = blurred_square_scaled_svg(true); + assert!(svg.contains(r#""#), "{svg}"); + } + + #[test] + fn svg_effects_after_a_transform_measure_as_viewed() { + // The blur was stamped on the scaled square, so its filter measures in the user space as it's viewed, with no group transforming into it + let svg = blurred_square_scaled_svg(false); + assert!(svg.contains(r#""#), "{defs}"); + assert!(defs.contains(r#"in="effect-1" stdDeviation="3 3" color-interpolation-filters="linearRGB""#), "{defs}"); + assert!(defs.ends_with(r#""#), "{defs}"); + } + + /// A 10 unit orange square with `effects` stamped on it, its `fill` opacity, and its `opacity`. + fn orange_square(effects: &[graphic_types::EffectOperation], fill: f64, opacity: f64) -> List { + List::new_from_item(orange_square_item(effects, fill, opacity)) + } + + fn orange_square_item(effects: &[graphic_types::EffectOperation], fill: f64, opacity: f64) -> Item { + use graphic_types::{Effect, stamp_effect}; + use kurbo::Shape; + + let orange = Color::from_gamma_srgb_channels(1., 0.5, 0., 1.); + let mut item = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., 10., 10.).to_path(0.1)); + item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(orange)))); + item.set_attribute(ATTR_OPACITY_FILL, fill); + item.set_attribute(ATTR_OPACITY, opacity); + effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + item + } + + #[test] + fn svg_masks_of_clipping_content_cover_it_whatever_the_clipped_content_draws() { + use graphic_types::raster_types::Image; + + // A raster can't reduce to a clip path, so it masks the square above it, which casts a shadow far past its own geometry + let raster = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(200.))); + let square = orange_square_item(&[drop_shadow(135., 60., 10.)], 1., 1.).with_attribute(ATTR_CLIPPING_MASK, true); + let mut list = List::new_from_element(Graphic::RasterCPU(Box::new(raster))); + list.push(Item::new_from_element(Graphic::Vector(Box::new(square)))); + + let mut render = SvgRender::new(); + list.render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + + // The mask covers the raster rather than a tenth past the square's geometry + assert!( + render.svg_defs.contains(r#"mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="200" height="200">"#), + "{}", + render.svg_defs + ); + } + + #[test] + fn lists_paint_as_far_as_the_effects_nested_anywhere_inside_them_paint() { + use graphic_types::EffectOperation; + + // A shadow on a square inside a group paints past the group + let shadow = drop_shadow(135., 20., 5.); + let in_group = |effects: &[EffectOperation]| List::new_from_element(Graphic::VectorList(orange_square(effects, 1., 1.))); + let square_grown_by = |reach: f64| RenderBoundingBox::Rectangle([DVec2::splat(-reach), DVec2::splat(10. + reach)]); + assert_eq!(graphic_list_painted_bounds(&in_group(std::slice::from_ref(&shadow)), true), square_grown_by(shadow.reach())); + + // An SVG with no GPU leaves the shadow out, so it frames the square alone + assert_eq!(graphic_list_painted_bounds(&in_group(std::slice::from_ref(&shadow)), false), square_grown_by(0.)); + + // Each item grows by its own reach, so a plain square far from the shadowed one isn't padded by its shadow + let mut list = in_group(std::slice::from_ref(&shadow)); + list.push(Item::new_from_element(Graphic::VectorList(orange_square(&[], 1., 1.))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(100.)))); + assert_eq!( + graphic_list_painted_bounds(&list, true), + RenderBoundingBox::Rectangle([DVec2::splat(-shadow.reach()), DVec2::splat(110.)]) + ); + } } diff --git a/node-graph/libraries/rendering/src/vello_scene_builder.rs b/node-graph/libraries/rendering/src/vello_scene_builder.rs index 2695af4acf7..d0947be02ea 100644 --- a/node-graph/libraries/rendering/src/vello_scene_builder.rs +++ b/node-graph/libraries/rendering/src/vello_scene_builder.rs @@ -1,4 +1,7 @@ +use glam::{DAffine2, DMat2, DVec2, UVec2}; +use graphic_types::effects::EffectCapture; use graphic_types::raster_types::{CPU, Raster, Texture}; +use graphic_types::{EffectOperation, Effects}; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke}; use std::borrow::Cow; use std::collections::HashMap; @@ -8,9 +11,14 @@ use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion}; /// Tolerance for turning shapes other than paths into paths, matching Vello's own. const SHAPE_TOLERANCE: f64 = 0.1; +/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures. +const EFFECTS_SIZE_CLASS: u32 = 64; + +/// The most pixels an effects group's area renders with, as a multiple of the viewport's, beyond which it renders at a lower resolution to bound its memory. +const MAX_EFFECTS_AREA_PER_VIEWPORT_AREA: f64 = 4.; + /// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time. -#[derive(Debug)] -pub struct VelloSceneBuilder { +pub struct VelloSceneBuilder<'a> { scene: vello_gpu::Scene, /// Places the drawn content in the scene, applied on top of every transform it's drawn with. view: Affine, @@ -20,6 +28,31 @@ pub struct VelloSceneBuilder { /// The largest width or height an image's texture can have, beyond which images are drawn from a downscaled texture. max_texture_size: u32, pushed: Vec, + /// Renders effects groups as they're drawn. A scene drawn ahead of its render has none, so it draws effects groups without their effects. + effects_renderer: Option<&'a mut dyn EffectsRenderer>, + /// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it. + effect_capture: Option, +} + +/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn. +pub trait EffectsRenderer: Send { + /// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill. + fn renders_effects(&self) -> bool; + + /// Renders the content `draw` draws, placed by `view`, into a premultiplied texture of `size`, returning a texture of the same size with `effects` carried out on it. + /// `effect_to_pixels` places the effects' space on the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it. + /// With a `capture`, the texture instead holds that effect's coverage, as black with it in alpha. + #[allow(clippy::too_many_arguments)] + fn render_effects( + &mut self, + size: UVec2, + view: Affine, + effects: &Effects, + fill: f32, + effect_to_pixels: DAffine2, + capture: Option, + draw: &mut dyn FnMut(&mut VelloSceneBuilder), + ) -> wgpu::Texture; } /// The pixels behind an image the scene draws. @@ -31,6 +64,8 @@ pub enum SceneImage { Raster(Raster), /// Straight-alpha pixels in a GPU texture. Texture(Texture), + /// Premultiplied pixels of an effects group's result, rendered for this scene. + Rendered(wgpu::Texture), } #[derive(Clone, PartialEq, Eq, Hash, Debug)] @@ -38,6 +73,7 @@ enum ImageKey { Blob(u64), Raster(u64), Texture(Texture), + Rendered(wgpu::Texture), } #[derive(Debug)] @@ -46,7 +82,17 @@ enum Pushed { Clip, } -impl VelloSceneBuilder { +impl std::fmt::Debug for VelloSceneBuilder<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VelloSceneBuilder") + .field("scene", &self.scene) + .field("view", &self.view) + .field("images", &self.images) + .finish_non_exhaustive() + } +} + +impl<'a> VelloSceneBuilder<'a> { pub fn new(width: u16, height: u16, view: Affine, max_texture_size: u32) -> Self { Self::from_vello(vello_gpu::Scene::new(width, height), view, max_texture_size) } @@ -61,9 +107,27 @@ impl VelloSceneBuilder { image_ids: HashMap::new(), max_texture_size, pushed: Vec::new(), + effects_renderer: None, + effect_capture: None, } } + /// Renders the effects groups drawn into the scene through `renderer`. + pub fn with_effects_renderer(mut self, renderer: &'a mut dyn EffectsRenderer) -> Self { + self.effects_renderer = Some(renderer); + self + } + + /// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are. + pub fn capture_next_effects(&mut self, capture: EffectCapture) { + self.effect_capture = Some(capture); + } + + /// The coverage the next effects group drawn was to output, which it then won't. + pub fn take_effect_capture(&mut self) -> Option { + self.effect_capture.take() + } + pub fn width(&self) -> u16 { self.scene.width() } @@ -93,6 +157,14 @@ impl VelloSceneBuilder { self.view } + /// Draws what `draw` draws placed by `placement` within the view, as content with its own document space for its effects' lengths, like each thumbnail of an atlas. + pub fn draw_placed(&mut self, placement: Affine, draw: impl FnOnce(&mut Self)) { + let outer_view = self.view; + self.view = outer_view * placement; + draw(self); + self.view = outer_view; + } + /// The tolerance Vello GPU expands a stroke drawn with `transform` at, so a stroke outline expanded at it fills identically. pub fn stroke_tolerance(&self, transform: Affine) -> f64 { // Matches `vello_common::flatten::stroke`, including its use of the diagonal coefficients as the scale @@ -191,6 +263,71 @@ impl VelloSceneBuilder { self.draw_image_source(source, sampler, transform * texture_to_image, texture_size); } + /// Draws the content `draw` draws with `effects` carried out on it in their `effect_space` (placed in the drawn content's space), given the area it covers in that space, or `None` if unbounded. + /// `fill` fades the content but not the shadows and glows cast from it. Rendering a split scene calls `draw` again for each part. + pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option, effect_space: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) { + let capture = self.effect_capture.take(); + let effect_to_device = DAffine2::from_cols_array(&self.view.as_coeffs()) * effect_space; + if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) || !effect_to_device.matrix2.determinant().is_normal() { + self.push_viewport_layer(peniko::Mix::Normal, fill); + draw(self); + self.pop_layer(); + return; + } + + // The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail. + // A box blur, which isn't round, turns with its space only along that space's axes. + let has_box_blur = effects + .operations() + .any(|operation| matches!(operation, EffectOperation::Blur { box_blur: true, .. }) && !operation.changes_nothing()); + let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_box_blur || is_axis_aligned(effect_to_device.matrix2)); + let (frame_to_device, lengths_to_frame) = match follows_viewport { + true => (DAffine2::IDENTITY, effect_to_device.matrix2), + false => { + let density = largest_stretch(effect_to_device.matrix2); + (effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density))) + } + }; + let device_to_frame = frame_to_device.inverse(); + let document_to_frame = Affine::new(device_to_frame.to_cols_array()) * self.view; + let reach = effects.reach() * lengths_to_frame.determinant().abs().sqrt(); + + // The content reaching into the viewport, rounded out to whole pixels of the frame + let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64); + let viewport_in_frame = Affine::new(device_to_frame.to_cols_array()).transform_rect_bbox(viewport); + let content_bounds = bounds.map_or(viewport_in_frame, |bounds| document_to_frame.transform_rect_bbox(bounds)); + let region = content_bounds.inflate(reach, reach).intersect(viewport_in_frame.inflate(reach, reach)).expand(); + if !(region.width() > 0. && region.height() > 0.) { + return; + } + + // A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide. + // Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures. + let max_size = self.max_texture_size.min(u16::MAX as u32); + let max_area = MAX_EFFECTS_AREA_PER_VIEWPORT_AREA * viewport.area(); + let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.); + let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size); + let size = UVec2::new(size_along(region.width()), size_along(region.height())); + let origin = region.origin().to_vec2(); + + let content_view = Affine::scale(resolution) * Affine::translate(-origin) * document_to_frame; + let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space; + let Some(renderer) = self.effects_renderer.as_deref_mut() else { return }; + let result = renderer.render_effects(size, content_view, effects, fill, effect_to_pixels, capture, draw); + + // Draw the result where the content was + self.images.push(SceneImage::Rendered(result)); + let id = TextureId(self.images.len() as u64 - 1); + self.scene + .set_transform(Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution)); + self.scene.set_paint(PaintType::Image(Image { + image: ImageSource::external_texture(id, TextureRegion::Full, true), + sampler: peniko::ImageSampler::new(), + })); + self.scene.set_paint_transform(Affine::IDENTITY); + self.scene.fill_rect(&Rect::new(0., 0., size.x as f64, size.y as f64)); + } + fn draw_image_source(&mut self, source: ImageSource, sampler: peniko::ImageSampler, transform: Affine, (width, height): (u32, u32)) { self.scene.set_transform(self.view * transform); self.scene.set_paint(PaintType::Image(Image { image: source, sampler })); @@ -222,6 +359,7 @@ impl VelloSceneBuilder { SceneImage::Pixels(data) => (data.width, data.height), SceneImage::Raster(raster) => (raster.width, raster.height), SceneImage::Texture(texture) => (texture.width(), texture.height()), + SceneImage::Rendered(texture) => (texture.width(), texture.height()), }; if width == 0 || height == 0 { return None; @@ -231,6 +369,7 @@ impl VelloSceneBuilder { SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()), SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()), SceneImage::Texture(texture) => ImageKey::Texture(texture.clone()), + SceneImage::Rendered(texture) => ImageKey::Rendered(texture.clone()), }; let id = *self.image_ids.entry(key).or_insert_with(|| { self.images.push(image); @@ -307,6 +446,26 @@ fn finite_path(path: &BezPath) -> Cow<'_, BezPath> { Cow::Owned(result) } +/// Whether the linear map only turns, flips, and evenly scales, so it keeps circles round. +fn is_similarity(linear: DMat2) -> bool { + let (x_axis, y_axis) = (linear.x_axis, linear.y_axis); + let tolerance = 1e-9 * x_axis.length_squared().max(y_axis.length_squared()); + (x_axis.length_squared() - y_axis.length_squared()).abs() <= tolerance && x_axis.dot(y_axis).abs() <= tolerance +} + +/// Whether the linear map keeps the axes along the axes, at most swapping or flipping them. +fn is_axis_aligned(linear: DMat2) -> bool { + let tolerance = 1e-9 * linear.x_axis.abs().max_element().max(linear.y_axis.abs().max_element()); + (linear.x_axis.y.abs() <= tolerance && linear.y_axis.x.abs() <= tolerance) || (linear.x_axis.x.abs() <= tolerance && linear.y_axis.y.abs() <= tolerance) +} + +/// The most the linear map stretches any length, its largest singular value. +fn largest_stretch(linear: DMat2) -> f64 { + let sum_of_squares = linear.x_axis.length_squared() + linear.y_axis.length_squared(); + let determinant = linear.determinant(); + ((sum_of_squares + (sum_of_squares * sum_of_squares - 4. * determinant * determinant).max(0.).sqrt()) / 2.).sqrt() +} + /// The size of the texture an image is drawn from, downscaled by a whole factor until both sides fit within `max_texture_size`. pub fn image_texture_size(width: u32, height: u32, max_texture_size: u32) -> (u32, u32) { let factor = image_downscale_factor(width, height, max_texture_size); diff --git a/node-graph/libraries/resources/src/lib.rs b/node-graph/libraries/resources/src/lib.rs index 5e34ca3c196..aa10fc4da59 100644 --- a/node-graph/libraries/resources/src/lib.rs +++ b/node-graph/libraries/resources/src/lib.rs @@ -5,7 +5,7 @@ use std::future::Future; use std::hash::Hash; use std::ops::Deref; use std::pin::Pin; -use std::sync::Arc; +use std::sync::{Arc, Weak}; #[derive(Clone, DynAny)] pub struct Resource { @@ -30,6 +30,22 @@ impl Resource { pub fn empty() -> Self { Self::new([]) } + + /// A reference to this resource's data that doesn't keep it alive. + pub fn downgrade(&self) -> WeakResource { + WeakResource(Arc::downgrade(&self.inner)) + } +} + +/// A reference to a [`Resource`]'s data that doesn't keep it alive, for caches of what's derived from the data. +#[derive(Clone)] +pub struct WeakResource(Weak + Send + Sync>); + +impl WeakResource { + /// Whether anything still holds the resource's data. + pub fn is_alive(&self) -> bool { + self.0.strong_count() > 0 + } } impl Default for Resource { @@ -135,7 +151,7 @@ impl std::str::FromStr for ResourceHash { } let mut out = [0u8; 32]; - for (index, chunk) in bytes.chunks_exact(2).enumerate() { + for (index, chunk) in bytes.as_chunks::<2>().0.iter().enumerate() { let high = decode_hex_nibble(chunk[0], index * 2)?; let low = decode_hex_nibble(chunk[1], index * 2 + 1)?; out[index] = (high << 4) | low; diff --git a/node-graph/libraries/vector-types/src/gradient.rs b/node-graph/libraries/vector-types/src/gradient.rs index 7722953755e..b155be13abb 100644 --- a/node-graph/libraries/vector-types/src/gradient.rs +++ b/node-graph/libraries/vector-types/src/gradient.rs @@ -1,6 +1,7 @@ use core_types::Color; use core_types::color::SRGBA8; use core_types::list::{ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_MIDPOINT, ATTR_POSITION, Item, List}; +use core_types::math::midpoint::{apply_midpoint, sanitized_midpoint}; use dyn_any::DynAny; use glam::{DAffine2, DVec2}; @@ -323,27 +324,6 @@ impl From> for Gradient { /// deviate by no more than 2 gradations of 8-bit color from the theoretically perfect curve. const SAMPLE_THRESHOLD: f64 = 2. / 255.; -/// The effective midpoint domain shared by sampling and rendering: NaN reads as the linear default, and extremes are bounded to `0.01..=0.99` so curves stay finite and cheap to subdivide. -fn sanitized_midpoint(midpoint: f64) -> f64 { - if midpoint.is_nan() { 0.5 } else { midpoint.clamp(0.01, 0.99) } -} - -/// Apply the midpoint curve to a normalized parameter `t` (0 to 1) given a `midpoint` (0 to 1, where 0.5 is linear). -fn apply_midpoint(t: f64, midpoint: f64) -> f64 { - let midpoint = sanitized_midpoint(midpoint); - if (midpoint - 0.5).abs() < 1e-6 { - return t; - } - - if midpoint < 0.5 { - let q = -1. / (1. - midpoint).log2(); - 1. - (1. - t).powf(q) - } else { - let p = -1. / midpoint.log2(); - t.powf(p) - } -} - /// Calls a color-space-generic function with the `color` crate space matching a [`GradientSpace`] variant. macro_rules! with_space { ($gradient_space:expr, $function:ident $(, $argument:expr)* $(,)?) => { @@ -1783,7 +1763,7 @@ impl GradientInterpolation { /// The whole-ramp attributes governing how a gradient plays back, read together off a gradient item so the /// sampling entry points take one argument instead of a widening list of same-typed positional ones. -#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash)] +#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct GradientSettings { pub spread: GradientSpread, diff --git a/node-graph/libraries/vector-types/src/vector/algorithms/weld.rs b/node-graph/libraries/vector-types/src/vector/algorithms/weld.rs index 2fffc16a904..a8b7e7238d4 100644 --- a/node-graph/libraries/vector-types/src/vector/algorithms/weld.rs +++ b/node-graph/libraries/vector-types/src/vector/algorithms/weld.rs @@ -33,7 +33,7 @@ impl WeldExt for Vector { // TODO: We lose information on the winding order by using an undirected graph. Switch to a directed graph and fix the algorithm to handle that. // Graph containing only short edges, referencing the data graph - let mut short_edges = UnGraphMap::new(); + let mut short_edges = UnGraphMap::<_, _, rustc_hash::FxBuildHasher>::new(); for segment_id in working.segment_ids.iter().copied() { let length = indices.segment_chord_length(segment_id); @@ -409,8 +409,8 @@ fn weld_nearby_points(vector: &mut Vector, paths: &mut List, transform: DA let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); // Add points to grid cells without collecting all positions first - for i in 0..point_count { - let pos = transform.transform_point2(working.point_positions[i]); + for (i, &position) in working.point_positions.iter().enumerate() { + let pos = transform.transform_point2(position); let grid_x = ((pos.x - min_x) / distance).floor() as i64; let grid_y = ((pos.y - min_y) / distance).floor() as i64; diff --git a/node-graph/libraries/vector-types/src/vector/misc.rs b/node-graph/libraries/vector-types/src/vector/misc.rs index 73505332059..23b69b7619d 100644 --- a/node-graph/libraries/vector-types/src/vector/misc.rs +++ b/node-graph/libraries/vector-types/src/vector/misc.rs @@ -154,6 +154,8 @@ pub enum GridTopology { Serpentine, /// One path through every point that finishes each region of the grid before moving on to the next. HilbertCurve, + /// One closed path through every point, finishing each region of the grid before moving on to the next, so animating along it loops with no visible start. + MooreCurve, /// One path winding inward through every point, lap by lap. Spiral, /// One closed path through every point, so animating along it loops with no visible start. Rectangular grids with an odd number of both columns and rows leave out one corner. diff --git a/node-graph/libraries/vector-types/src/vector/style.rs b/node-graph/libraries/vector-types/src/vector/style.rs index e22b68d54a2..36020e28d75 100644 --- a/node-graph/libraries/vector-types/src/vector/style.rs +++ b/node-graph/libraries/vector-types/src/vector/style.rs @@ -18,7 +18,7 @@ use std::f64::consts::{PI, TAU}; /// /// In the future we'll probably also add a pattern fill. #[repr(C)] -#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))] +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum FillChoice { diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index cb7cbfee095..29619764202 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -430,9 +430,10 @@ impl SegmentGraph { fn construct_face(&self, adjacency: &[Vec], first: FaceSide, faces: &mut Faces, seen: &mut FaceSideSet) -> Option<()> { faces.start_new_face(); + // A tree's one orbit walks every side, so it takes all `2 * len` iterations to come back around let max_iterations = self.len() * 2; let mut side = first; - for _iteration in 1..max_iterations { + for _iteration in 0..max_iterations { if seen.contains(side) { return None; } @@ -1535,4 +1536,14 @@ mod tests { vector.construct_faces(&paths); } + + #[test] + fn a_branching_tree_has_one_orbit_along_both_sides_of_every_segment() { + let points = [DVec2::new(0., 0.), DVec2::new(0., -10.), DVec2::new(-5., -15.), DVec2::new(5., -15.)]; + let (vector, paths) = build_vector(&points, &[(0, 1), (1, 2), (1, 3)]); + + let orbits = SegmentGraph::new(&vector, &paths).face_orbits(); + assert_eq!(orbits.face_count(), 1); + assert_eq!(orbits.face_sides(0).len(), 6); + } } diff --git a/node-graph/libraries/wgpu-executor/Cargo.toml b/node-graph/libraries/wgpu-executor/Cargo.toml index e45a852e468..395fc9033d3 100644 --- a/node-graph/libraries/wgpu-executor/Cargo.toml +++ b/node-graph/libraries/wgpu-executor/Cargo.toml @@ -16,6 +16,8 @@ workspace = true [dependencies] # Local dependencies core-types = { workspace = true } +graphic-types = { workspace = true } +raster-kernels = { workspace = true } raster-types = { workspace = true, features = ["wgpu"] } graphene-application-io = { workspace = true, features = ["wgpu"] } rendering = { workspace = true } @@ -32,4 +34,5 @@ log = { workspace = true } web-sys = { workspace = true } vello_gpu = { workspace = true } bytemuck = { workspace = true } +half = { workspace = true } thiserror = { workspace = true } diff --git a/node-graph/libraries/wgpu-executor/src/deferred_svg_images.rs b/node-graph/libraries/wgpu-executor/src/deferred_svg_images.rs new file mode 100644 index 00000000000..c4e7c7f9e83 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/deferred_svg_images.rs @@ -0,0 +1,35 @@ +use crate::WgpuExecutor; +use core_types::ops::ConvertAsync; +use core_types::transform::Footprint; +use raster_types::{CPU, Raster, Texture}; +use rendering::deferred_image::{EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_effect_map}; + +impl WgpuExecutor { + /// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each. + /// Maps out of view, or that fail to render, keep their placeholders. + pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> { + let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d); + + effect_maps + .iter() + .filter_map(|map| { + let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?; + match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) { + Ok(texture) => Some((layout.placement, texture)), + Err(error) => { + log::error!("Failed to render a map of an effect's coverage for an SVG filter: {error}"); + None + } + } + }) + .collect() + } + + /// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder. + pub async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) { + for (placement, texture) in maps { + let map: Raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await; + substitute_effect_map(svg, &placement, &map); + } + } +} diff --git a/node-graph/libraries/wgpu-executor/src/lib.rs b/node-graph/libraries/wgpu-executor/src/lib.rs index 087703265c0..cefd2afa698 100644 --- a/node-graph/libraries/wgpu-executor/src/lib.rs +++ b/node-graph/libraries/wgpu-executor/src/lib.rs @@ -1,8 +1,10 @@ mod buffer; mod context; +mod deferred_svg_images; mod pipeline; mod texture_cache; pub mod texture_conversion; +mod vello_effects; mod vello_render; use crate::texture_cache::TextureCache; @@ -177,7 +179,7 @@ impl WgpuExecutor { } pub fn with_context(context: WgpuContext) -> Option { - let vello_renderer = VelloRenderer::new(&context.device); + let vello_renderer = VelloRenderer::new(&context.device, &context.adapter); let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE); diff --git a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs index 629cd05e819..05c516038fb 100644 --- a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs +++ b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs @@ -114,8 +114,8 @@ impl RasterGpuToRasterCpuConverter { for row in 0..self.height as usize { let start = row * row_stride; let row_slice = &view[start..start + row_bytes]; - for px in row_slice.chunks_exact(4) { - cpu_data.push(SRGBA8::new(px[0], px[1], px[2], px[3]).into()); + for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 { + cpu_data.push(SRGBA8::new(red, green, blue, alpha).into()); } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.rs b/node-graph/libraries/wgpu-executor/src/vello_effects.rs new file mode 100644 index 00000000000..71b86e5e151 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.rs @@ -0,0 +1,816 @@ +//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back. + +use bytemuck::{Pod, Zeroable}; +use core_types::Color; +use core_types::transfer_curve::TransferCurve; +use glam::{DMat2, DVec2, UVec2}; +use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GlowFill, grow_and_tent, shadow_offset}; +use graphic_types::{EffectOperation, Effects, GlowTechnique}; +use raster_kernels::effect_kernels::{BlurKernel, MAX_KERNEL_REACH, NEGLIGIBLE_LENGTH}; +use std::collections::HashMap; +use std::sync::{Mutex, PoisonError}; + +/// The format of the images the passes produce, with the precision to keep soft gradients smooth. +pub(crate) const WORKING_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; + +/// The format of the silhouettes shadows and glows are cast from, which hold only coverage, or a distance. +const COVERAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; + +/// How many samples of a contour the shaders interpolate between, enough to follow its spline to well within a level. +const CONTOUR_SAMPLES: u32 = 256; +/// How many samples of a glow's gradient the shaders interpolate between. +const GRADIENT_SAMPLES: u32 = 256; + +/// The most taps one kernel pass weighs, matching the length of the shader's array, which holds a kernel of [`MAX_KERNEL_REACH`] texels to each side in pairs. +const MAX_TAPS: usize = 1 + 2 * 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. +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct Parameters { + target_to_uv: [f32; 2], + step: [f32; 2], + offset: [f32; 2], + amount: f32, + tap_count: u32, + color: [f32; 4], + values: [f32; 4], + taps: [[f32; 4]; MAX_TAPS], +} + +impl Default for Parameters { + fn default() -> Self { + Self::zeroed() + } +} + +/// The kernel's taps for a texture halved `levels` times, each the distance and weight of a symmetric pair of taps that sample between two texels. +fn kernel_taps(kernel: BlurKernel, levels: u32) -> Vec<[f32; 4]> { + let weights = kernel.weights(levels); + + // Each tap between a pair of texels samples them in the ratio of their weights, through bilinear filtering + let mut taps = vec![[0., weights[0] as f32, 0., 0.]]; + for (pair_index, pair) in weights[1..].chunks(2).enumerate() { + let near_distance = (1 + 2 * pair_index) as f64; + let (distance, weight) = match *pair { + [near, far] => ((near_distance * near + (near_distance + 1.) * far) / (near + far), near + far), + [near] => (near_distance, near), + _ => continue, + }; + taps.push([distance as f32, weight as f32, 0., 0.]); + taps.push([-distance as f32, weight as f32, 0., 0.]); + } + + taps +} + +/// The pipelines of the effect passes, each built the first time it is used. +pub(crate) struct EffectPasses { + shader: wgpu::ShaderModule, + bind_group_layout: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + sampler: wgpu::Sampler, + pipelines: Mutex>, + /// Whether the GPU can render into the passes' formats, which WebGL2 can't without `EXT_color_buffer_float`. + pub(crate) renders_working_formats: bool, +} + +impl EffectPasses { + pub(crate) fn new(device: &wgpu::Device, adapter: &wgpu::Adapter) -> Self { + let renders_working_formats = [WORKING_FORMAT, COVERAGE_FORMAT] + .into_iter() + .all(|format| adapter.get_texture_format_features(format).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT)); + if !renders_working_formats { + log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects"); + } + + let shader = device.create_shader_module(wgpu::include_wgsl!("vello_effects.wgsl")); + + let texture_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("vello_effects_bind_group_layout"), + entries: &[ + texture_entry(0), + texture_entry(1), + texture_entry(2), + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("vello_effects_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + // Sampling past the edges repeats them, which is transparent since the content's offscreen area reaches past it by the effects' reach + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("vello_effects_sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + + Self { + shader, + bind_group_layout, + pipeline_layout, + sampler, + pipelines: Mutex::new(HashMap::new()), + renders_working_formats, + } + } + + fn pipeline(&self, device: &wgpu::Device, entry_point: &'static str, format: wgpu::TextureFormat) -> wgpu::RenderPipeline { + let mut pipelines = self.pipelines.lock().unwrap_or_else(PoisonError::into_inner); + + pipelines + .entry((entry_point, format)) + .or_insert_with(|| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry_point), + layout: Some(&self.pipeline_layout), + vertex: wgpu::VertexState { + module: &self.shader, + entry_point: Some("vertex"), + compilation_options: Default::default(), + buffers: &[], + }, + fragment: Some(wgpu::FragmentState { + module: &self.shader, + entry_point: Some(entry_point), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }) + }) + .clone() + } + + /// Carries out `effects` on `content`, a texture of premultiplied pixels, returning the result in a pooled texture of [`WORKING_FORMAT`] the same size. + /// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it. + /// With a `capture`, the result is instead that effect's coverage, as black with it in alpha, and the effects after it are left out. + #[expect(clippy::too_many_arguments)] + pub(crate) fn apply( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + textures: &mut EffectTextures, + content: &wgpu::Texture, + effects: &Effects, + fill: f32, + lengths_to_pixels: DMat2, + capture: Option, + ) -> wgpu::Texture { + let mut recorder = PassRecorder { + passes: self, + device, + queue, + encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }), + textures, + size: UVec2::new(content.width(), content.height()), + }; + let length_scale = lengths_to_pixels.determinant().abs().sqrt(); + + // The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result + let mut full = recorder.scale(content, 1.); + let mut filled = (fill < 1.).then(|| recorder.scale(content, fill)); + // The shadows and glows stacked beneath the content + let mut beneath: Option = None; + + for (index, effect) in effects.operations().enumerate() { + // A captured coverage ends the passes in place of the effects' result + let mut captured = None; + // A coverage is captured in black, and an already tinted image as it is + let mut capture_plane = |recorder: &mut PassRecorder, plane: usize, coverage: &wgpu::Texture, tinted: bool| { + if capture == Some(EffectCapture { index, plane }) { + let black = Parameters { + color: [0., 0., 0., 1.], + ..Default::default() + }; + captured = Some(match tinted { + true => recorder.scale(coverage, 1.), + false => recorder.run("tint", WORKING_FORMAT, recorder.size, coverage, None, None, black), + }); + } + }; + + match effect { + EffectOperation::Blur { radius, box_blur, gamma } => { + let radius = radius * length_scale; + if radius < NEGLIGIBLE_LENGTH { + continue; + } + + // What lies beneath blurs together with the content + if let Some(beneath) = beneath.take() { + if let Some(filled) = &mut filled { + let composited = recorder.composite_beneath(filled, &beneath); + recorder.replace(filled, composited); + } + let composited = recorder.composite_beneath(&full, &beneath); + recorder.replace(&mut full, composited); + recorder.textures.release(beneath); + } + + let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } }; + full = recorder.blur(full, kernel, !gamma); + filled = filled.map(|filled| recorder.blur(filled, kernel, !gamma)); + } + EffectOperation::DropShadow { + color, + angle, + distance, + spread, + size, + contour, + knockout, + } => { + let silhouette = recorder.silhouette(&full, lengths_to_pixels * shadow_offset(angle, distance), false); + let mut strength = recorder.cast(silhouette, size, spread, GlowTechnique::Softer, 100., &contour, length_scale); + if knockout { + strength = recorder.knock_out(strength, &full, fill); + } + capture_plane(&mut recorder, 0, &strength, false); + + beneath = Some(recorder.accumulate(beneath, &strength, color)); + recorder.textures.release(strength); + } + EffectOperation::OuterGlow { + color, + technique, + spread, + size, + range, + contour, + } => { + let Some(paint) = GlowFill::of(&color) else { continue }; + let silhouette = recorder.silhouette(&full, DVec2::ZERO, false); + let raw = recorder.cast_strength(silhouette, size, spread, technique, length_scale); + let shaped = recorder.shaped(&raw, range, &contour); + let strength = shaped.as_ref().unwrap_or(&raw); + + // A solid color tints the coverage as it stacks, but a gradient paints each pixel its own color, which a map captures whole + let (coverage, color) = match paint { + GlowFill::Solid(color) => (recorder.scale(strength, 1.), Some(color)), + GlowFill::Gradient { .. } => match recorder.gradient_glow_tint(&paint, strength, &raw, true) { + Some(tinted) => (tinted, None), + None => continue, + }, + }; + [Some(raw), shaped].into_iter().flatten().for_each(|texture| recorder.textures.release(texture)); + + let coverage = recorder.knock_out(coverage, &full, fill); + capture_plane(&mut recorder, 0, &coverage, color.is_none()); + beneath = Some(recorder.stack_beneath(beneath, &coverage, color)); + recorder.textures.release(coverage); + } + EffectOperation::InnerShadow { + color, + angle, + distance, + choke, + size, + contour, + } => { + let outside = recorder.silhouette(&full, lengths_to_pixels * shadow_offset(angle, distance), true); + let strength = recorder.cast(outside, size, choke, GlowTechnique::Softer, 100., &contour, length_scale); + capture_plane(&mut recorder, 0, &strength, false); + + if let Some(filled) = &mut filled { + let composited = recorder.composite_within(filled, &strength, &full, color); + recorder.replace(filled, composited); + } + let composited = recorder.composite_within(&full, &strength, &full, color); + recorder.replace(&mut full, composited); + recorder.textures.release(strength); + } + } + + if let Some(captured) = captured { + [Some(full), filled, beneath].into_iter().flatten().for_each(|texture| recorder.textures.release(texture)); + queue.submit([recorder.encoder.finish()]); + return captured; + } + } + + let result = match (filled, beneath) { + (filled, Some(beneath)) => { + let result = recorder.composite_beneath(filled.as_ref().unwrap_or(&full), &beneath); + recorder.textures.release(beneath); + recorder.textures.release(full); + if let Some(filled) = filled { + recorder.textures.release(filled); + } + result + } + (Some(filled), None) => { + recorder.textures.release(full); + filled + } + (None, None) => full, + }; + + queue.submit([recorder.encoder.finish()]); + result + } +} + +/// Which pixels seed a distance pass, and how far from each one its edge lies. +#[derive(Clone, Copy)] +enum Seeds { + /// The covered pixels, with their antialiased edges placed by coverage, matching `distances_to_silhouette`. + Covered, + /// The pixels of a distance texture lying up to 3 past a grow of so many pixels, matching `distances_through_seeds` of how far short of the grown edge they lie. + PastGrow { grow: f64 }, +} + +/// A color as the premultiplied, gamma-encoded channels the passes work with. +fn premultiplied_gamma_channels(color: Color) -> [f32; 4] { + let [red, green, blue, alpha] = color.to_gamma_srgb_channels(); + [red * alpha, green * alpha, blue * alpha, alpha] +} + +/// Records the passes of one effects group, whose images all share one size. +struct PassRecorder<'a> { + passes: &'a EffectPasses, + device: &'a wgpu::Device, + queue: &'a wgpu::Queue, + encoder: wgpu::CommandEncoder, + textures: &'a mut EffectTextures, + size: UVec2, +} + +impl PassRecorder<'_> { + /// Runs the shader's `entry_point` into a new pooled texture of `format` and `size`, reading `source` and optionally the `secondary` and `content` inputs. + #[expect(clippy::too_many_arguments)] + fn run( + &mut self, + entry_point: &'static str, + format: wgpu::TextureFormat, + size: UVec2, + source: &wgpu::Texture, + secondary: Option<&wgpu::Texture>, + content: Option<&wgpu::Texture>, + parameters: Parameters, + ) -> wgpu::Texture { + use wgpu::util::DeviceExt; + + let target = self.textures.acquire(self.device, size, format); + let parameters = Parameters { + target_to_uv: [1. / size.x as f32, 1. / size.y as f32], + ..parameters + }; + + let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); + let (source_view, secondary_view, content_view) = (view(source), view(secondary.unwrap_or(source)), view(content.unwrap_or(source))); + let parameters_buffer = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("vello_effects_parameters"), + contents: bytemuck::bytes_of(¶meters), + usage: wgpu::BufferUsages::UNIFORM, + }); + let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("vello_effects_bind_group"), + layout: &self.passes.bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&source_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&secondary_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&content_view), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&self.passes.sampler), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: parameters_buffer.as_entire_binding(), + }, + ], + }); + + let pipeline = self.passes.pipeline(self.device, entry_point, format); + let target_view = view(&target); + let mut pass = self.encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(entry_point), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target_view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.draw(0..3, 0..1); + drop(pass); + + target + } + + /// Puts `next` in place of the texture in `slot`, returning the old one to the pool. + fn replace(&mut self, slot: &mut wgpu::Texture, next: wgpu::Texture) { + self.textures.release(std::mem::replace(slot, next)); + } + + /// A copy of `source` in the working format, multiplied by `amount`. + fn scale(&mut self, source: &wgpu::Texture, amount: f32) -> wgpu::Texture { + self.run("scale", WORKING_FORMAT, self.size, source, None, None, Parameters { amount, ..Default::default() }) + } + + /// The coverage of the content's silhouette (or of the area outside it, if `inverse`), cast by `offset` in pixels. + fn silhouette(&mut self, content: &wgpu::Texture, offset: DVec2, inverse: bool) -> wgpu::Texture { + let offset = offset / self.size.as_dvec2(); + let parameters = Parameters { + offset: [offset.x as f32, offset.y as f32], + ..Default::default() + }; + let entry_point = if inverse { "cast_inverse_silhouette" } else { "cast_silhouette" }; + self.run(entry_point, COVERAGE_FORMAT, self.size, content, None, None, parameters) + } + + /// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage, shaped for PSD interop, matching the CPU's `cast`: + /// grown by the `spread` percentage of its `size` (in document pixels, `length_scale` pixels each), softened over the rest by the `technique`, then strengthened by its `range` percentage and reshaped by its `contour`. + #[expect(clippy::too_many_arguments)] + fn cast(&mut self, silhouette: wgpu::Texture, size: f64, spread: f64, technique: GlowTechnique, range: f64, contour: &TransferCurve, length_scale: f64) -> wgpu::Texture { + let strength = self.cast_strength(silhouette, size, spread, technique, length_scale); + match self.shaped(&strength, range, contour) { + Some(shaped) => { + self.textures.release(strength); + shaped + } + None => strength, + } + } + + /// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage before its range and contour shape it, as [`Self::cast`] describes. + fn cast_strength(&mut self, silhouette: wgpu::Texture, size: f64, spread: f64, technique: GlowTechnique, length_scale: f64) -> wgpu::Texture { + let (grow, tent) = grow_and_tent(size, spread); + let grow_pixels = grow * length_scale; + + match technique { + GlowTechnique::Softer => { + let mut coverage = silhouette; + if grow_pixels >= NEGLIGIBLE_LENGTH { + let to_silhouette = self.distances(&coverage, grow_pixels + 1., Seeds::Covered); + let parameters = Parameters { + values: [grow_pixels as f32, 0., 0., 0.], + ..Default::default() + }; + let grown = self.run("grow", COVERAGE_FORMAT, self.size, &to_silhouette, None, None, parameters); + self.textures.release(to_silhouette); + self.replace(&mut coverage, grown); + } + + let radius = tent * length_scale; + if radius >= NEGLIGIBLE_LENGTH { + coverage = self.blur(coverage, BlurKernel::Tent { radius }, false); + } + coverage + } + GlowTechnique::Precise => { + let to_content = self.distances(&silhouette, ((size + 1.) * length_scale).max(grow_pixels + 3.), Seeds::Covered); + self.textures.release(silhouette); + + // Within the grown shape, the falloff measures how far it lies in from the grown shape's edge + let within_grown = (grow_pixels >= NEGLIGIBLE_LENGTH).then(|| self.distances(&to_content, grow_pixels + 1., Seeds::PastGrow { grow: grow_pixels })); + let parameters = Parameters { + values: [grow_pixels as f32, size as f32, length_scale as f32, if within_grown.is_some() { 1. } else { 0. }], + ..Default::default() + }; + let falloff = self.run("precise_falloff", COVERAGE_FORMAT, self.size, &to_content, within_grown.as_ref(), None, parameters); + + self.textures.release(to_content); + if let Some(within_grown) = within_grown { + self.textures.release(within_grown); + } + falloff + } + } + } + + /// The `strength` strengthened by the `range` percentage and reshaped by the `contour`, matching the CPU's `shaped`, or `None` where they leave it as it is. + fn shaped(&mut self, strength: &wgpu::Texture, range: f64, contour: &TransferCurve) -> Option { + if range >= 100. && contour.is_identity() { + return None; + } + let contour_samples = (!contour.is_identity()).then(|| self.contour_samples(contour)); + let parameters = Parameters { + values: [(range.clamp(1., 100.) / 100.) as f32, if contour_samples.is_some() { 1. } else { 0. }, 0., 0.], + ..Default::default() + }; + Some(self.run("shape_strength", COVERAGE_FORMAT, self.size, strength, contour_samples.as_ref(), None, parameters)) + } + + /// The premultiplied color a glow filled with the gradient in `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them. + /// An outer glow `fades` out with its raw strength, matching the CPU's `glow_tint`. + fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, raw: &wgpu::Texture, fades: bool) -> Option { + let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?; + let samples: Vec = 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 parameters = Parameters { + values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, 0.], + ..Default::default() + }; + Some(self.run("gradient_glow_tint", WORKING_FORMAT, self.size, strength, Some(&samples), Some(raw), parameters)) + } + + /// Each pixel's distance from the `seeds` in `seed_values`, matching the CPU's distance passes, or far past `reach` pixels. + /// Jump flooding finds them in a pass for each halving of a step that starts past `reach`. O(width × height × log(reach)). + fn distances(&mut self, seed_values: &wgpu::Texture, reach: f64, seeds: Seeds) -> wgpu::Texture { + let (mode, grow) = match seeds { + Seeds::Covered => (0., 0.), + Seeds::PastGrow { grow } => (1., grow as f32), + }; + let parameters = |step: u32| Parameters { + values: [step as f32, mode, grow, 0.], + ..Default::default() + }; + + let mut nearest = self.run("jump_flood_seed", WORKING_FORMAT, self.size, seed_values, None, Some(seed_values), parameters(0)); + let mut step = (reach.clamp(0., self.size.max_element() as f64).ceil() as u32 + 1).next_power_of_two(); + while step >= 1 { + let flooded = self.run("jump_flood_step", WORKING_FORMAT, self.size, &nearest, None, Some(seed_values), parameters(step)); + self.replace(&mut nearest, flooded); + step /= 2; + } + + let distances = self.run("jump_flood_distance", COVERAGE_FORMAT, self.size, &nearest, None, Some(seed_values), parameters(0)); + self.textures.release(nearest); + distances + } + + /// A row of samples of the contour across 0 to 1, which shaders interpolate between. + /// 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 contour_samples(&mut self, contour: &TransferCurve) -> wgpu::Texture { + let contour = contour.evaluator(); + let samples: Vec = (0..CONTOUR_SAMPLES) + .map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.))) + .collect(); + self.row_texture("vello_effects_contour", 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. + /// 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, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture { + let extent = wgpu::Extent3d { + width, + height: 1, + depth_or_array_layers: 1, + }; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + 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( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(data.len() as u32), + rows_per_image: Some(1), + }, + extent, + ); + texture + } + + /// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 fades the content that shows over it. + fn knock_out(&mut self, coverage: wgpu::Texture, full_content: &wgpu::Texture, fill: f32) -> wgpu::Texture { + if fill >= 1. { + return coverage; + } + let parameters = Parameters { amount: fill, ..Default::default() }; + let knocked_out = self.run("knock_out", coverage.format(), self.size, &coverage, None, Some(full_content), parameters); + self.textures.release(coverage); + knocked_out + } + + /// Stacks a silhouette's coverage, tinted `color`, over what lies `beneath` the content so far. + fn accumulate(&mut self, beneath: Option, coverage: &wgpu::Texture, color: Color) -> wgpu::Texture { + self.stack_beneath(beneath, coverage, Some(color)) + } + + /// Stacks a coverage tinted `color`, or with no color an already tinted premultiplied image, over what lies `beneath` the content so far. + fn stack_beneath(&mut self, beneath: Option, coverage: &wgpu::Texture, color: Option) -> wgpu::Texture { + let parameters = Parameters { + color: color.map_or([0.; 4], premultiplied_gamma_channels), + values: [if beneath.is_some() { 1. } else { 0. }, if color.is_none() { 1. } else { 0. }, 0., 0.], + ..Default::default() + }; + + let accumulated = self.run("accumulate", WORKING_FORMAT, self.size, beneath.as_ref().unwrap_or(coverage), Some(coverage), None, parameters); + if let Some(beneath) = beneath { + self.textures.release(beneath); + } + accumulated + } + + /// The image with a silhouette's coverage, tinted `color`, placed over it within the full-strength content. + fn composite_within(&mut self, image: &wgpu::Texture, coverage: &wgpu::Texture, full_content: &wgpu::Texture, color: Color) -> wgpu::Texture { + let parameters = Parameters { + color: premultiplied_gamma_channels(color), + ..Default::default() + }; + self.run("composite_within", WORKING_FORMAT, self.size, image, Some(coverage), Some(full_content), parameters) + } + + /// The image with the shadows and glows `beneath` placed under it. + fn composite_beneath(&mut self, image: &wgpu::Texture, beneath: &wgpu::Texture) -> wgpu::Texture { + self.run("composite_beneath", WORKING_FORMAT, self.size, image, Some(beneath), None, Parameters::default()) + } + + /// Blurs `texture` by `kernel` along both axes, in linear light if `linear`. + /// Kernels too wide for one pass run on a texture halved enough times for them to fit, then doubled back to full size. O(width × height) per pass. + fn blur(&mut self, texture: wgpu::Texture, kernel: BlurKernel, linear: bool) -> wgpu::Texture { + let format = texture.format(); + let mut texture = texture; + + if linear { + let decoded = self.run("decode_to_linear", format, self.size, &texture, None, None, Parameters::default()); + self.replace(&mut texture, decoded); + } + + let levels = kernel.levels(); + let size = self.size; + let level_size = |level: u32| UVec2::new(size.x.div_ceil(1 << level), size.y.div_ceil(1 << level)); + + for level in 1..=levels { + let halved = self.run("resample", format, level_size(level), &texture, None, None, Parameters::default()); + self.replace(&mut texture, halved); + } + + let taps = kernel_taps(kernel, levels); + let mut tap_array = [[0.; 4]; MAX_TAPS]; + tap_array[..taps.len()].copy_from_slice(&taps); + for axis in [DVec2::X, DVec2::Y] { + let step = axis / level_size(levels).as_dvec2(); + let parameters = Parameters { + step: [step.x as f32, step.y as f32], + tap_count: taps.len() as u32, + taps: tap_array, + ..Default::default() + }; + let convolved = self.run("convolve", format, level_size(levels), &texture, None, None, parameters); + self.replace(&mut texture, convolved); + } + + for level in (0..levels).rev() { + let doubled = self.run("resample", format, level_size(level), &texture, None, None, Parameters::default()); + self.replace(&mut texture, doubled); + } + + if linear { + let encoded = self.run("encode_to_gamma", format, self.size, &texture, None, None, Parameters::default()); + self.replace(&mut texture, encoded); + } + + texture + } +} + +/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes. +#[derive(Default)] +pub(crate) struct EffectTextures { + /// Each unused texture with the render it was last used in. + free: Vec<(wgpu::Texture, u64)>, + render_count: u64, +} + +impl EffectTextures { + pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture { + let size = size.max(UVec2::ONE); + 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)) { + return self.free.swap_remove(index).0; + } + + device.create_texture(&wgpu::TextureDescriptor { + label: Some("vello_effects_texture"), + size: wgpu::Extent3d { + width: size.x, + 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. + pub(crate) fn release(&mut self, texture: wgpu::Texture) { + self.free.push((texture, self.render_count)); + } + + /// Frees the textures no recent render has used. + pub(crate) fn finish_render(&mut self) { + let render_count = self.render_count; + self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT); + self.render_count += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The sum of the weights of all taps, which must be one so blurring keeps the total brightness. + fn total_weight(taps: &[[f32; 4]]) -> f32 { + taps.iter().map(|tap| tap[1]).sum() + } + + #[test] + fn kernels_keep_brightness_and_fit_one_pass() { + let kernels = [0.3, 1., 2.5, 7.9, 8., 12., 100., 4000.] + .into_iter() + .flat_map(|length| [BlurKernel::Gaussian { sigma: length }, BlurKernel::Box { radius: length }]); + + for kernel in kernels { + let taps = kernel_taps(kernel, kernel.levels()); + + assert!(taps.len() <= MAX_TAPS, "{kernel:?} needs {} taps", taps.len()); + assert!((total_weight(&taps) - 1.).abs() < 1e-5, "{kernel:?} weighs {}", total_weight(&taps)); + } + } + + #[test] + fn merged_taps_sample_between_the_texels_they_weigh() { + // A box of half width two weighs five texels evenly, so its outer pair merges into taps one and a half texels out + let taps = kernel_taps(BlurKernel::Box { radius: 2. }, 0); + + assert_eq!(taps.len(), 3); + assert!((taps[0][1] - 0.2).abs() < 1e-6); + assert!((taps[1][0] - 1.5).abs() < 1e-6 && (taps[1][1] - 0.4).abs() < 1e-6); + assert!((taps[2][0] + 1.5).abs() < 1e-6); + } +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl b/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl new file mode 100644 index 00000000000..fae0b727684 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl @@ -0,0 +1,302 @@ +// The passes that carry out an item's effects on the pixels of its content, which are premultiplied with gamma-encoded color like the pixels Vello GPU blends + +struct Parameters { + // Converts a target pixel's position into the normalized coordinates the inputs are sampled at + target_to_uv: vec2, + // One step along the axis a kernel runs, in normalized coordinates + step: vec2, + // How far a silhouette is cast, in normalized coordinates + offset: vec2, + // The factor the scale pass multiplies by, or the fill the content is faded by + amount: f32, + tap_count: u32, + // The premultiplied color a silhouette is tinted + color: vec4, + // Each pass's own settings, described where it reads them + values: vec4, + // Each kernel tap's distance in steps (x) and weight (y) + taps: array, 25>, +} + +@group(0) @binding(0) var source: texture_2d; +@group(0) @binding(1) var secondary: texture_2d; +@group(0) @binding(2) var content: texture_2d; +@group(0) @binding(3) var linear_sampler: sampler; +@group(0) @binding(4) var parameters: Parameters; + +// Distances past the farthest a pass looks, which stand for none found +const FAR: f32 = 65504.; + +// One triangle that covers the whole target +@vertex +fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4 { + let corner = vec2(f32((index << 1u) & 2u), f32(index & 2u)); + return vec4(corner * 2. - 1., 0., 1.); +} + +fn sample_source(uv: vec2) -> vec4 { + return textureSampleLevel(source, linear_sampler, uv, 0.); +} + +// A separable kernel along one axis, whose taps sit between texels to weight two of them at once +@fragment +fn convolve(@builtin(position) position: vec4) -> @location(0) vec4 { + let uv = position.xy * parameters.target_to_uv; + + var sum = vec4(0.); + for (var i = 0u; i < parameters.tap_count; i++) { + let tap = parameters.taps[i]; + sum += sample_source(uv + parameters.step * tap.x) * tap.y; + } + return sum; +} + +// Halving a texture samples the corner shared by each block of four texels, averaging them, and doubling it interpolates between texels +@fragment +fn resample(@builtin(position) position: vec4) -> @location(0) vec4 { + return sample_source(position.xy * parameters.target_to_uv); +} + +// The coverage of the content's silhouette, shifted by the offset +@fragment +fn cast_silhouette(@builtin(position) position: vec4) -> @location(0) vec4 { + return vec4(sample_source(position.xy * parameters.target_to_uv - parameters.offset).a); +} + +// The coverage of the area outside the content's silhouette, shifted by the offset +@fragment +fn cast_inverse_silhouette(@builtin(position) position: vec4) -> @location(0) vec4 { + return vec4(1. - sample_source(position.xy * parameters.target_to_uv - parameters.offset).a); +} + +// The length of an offset along the shortest path of steps one texel straight, one diagonally, or a knight's move away, matching `chamfer_length` +fn chamfer_length(offset: vec2) -> f32 { + let long = max(abs(offset.x), abs(offset.y)); + let short = min(abs(offset.x), abs(offset.y)); + if 2. * short <= long { + return (long - 2. * short) + sqrt(5.) * short; + } + return sqrt(5.) * (long - short) + sqrt(2.) * (2. * short - long); +} + +// Jump flooding keeps each texel's offset from the nearest seed found so far (xy) and whether one is found (z). The `content` input holds the seeds' values. +// With `values.y` 0, the seeds are the covered texels and a distance runs to the edge within the seed, placed by its coverage. +// With `values.y` 1, the seeds are the texels past a grow of `values.z` texels and a distance runs to that grown edge, matching `distances_through_seeds`. +fn is_seed(value: f32) -> bool { + if parameters.values.y > 0.5 { + // Only those up to 3 texels past it, a band any path in from farther crosses + return value > parameters.values.z && value <= parameters.values.z + 3.; + } + return value > 0.; +} + +fn seed_distance(pixel: vec2, offset: vec2) -> f32 { + let value = textureLoad(content, pixel - vec2(offset), 0).r; + if parameters.values.y > 0.5 { + return chamfer_length(offset) + parameters.values.z - value; + } + + return chamfer_length(offset) + (0.5 - value) + 0.5; +} + +@fragment +fn jump_flood_seed(@builtin(position) position: vec4) -> @location(0) vec4 { + let seed = is_seed(textureLoad(content, vec2(position.xy), 0).r); + return vec4(0., 0., select(0., 1., seed), 0.); +} + +// Takes the nearest of the seeds that the texel and its eight neighbors `values.x` texels away have found so far +@fragment +fn jump_flood_step(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let size = vec2(textureDimensions(source)); + let step = i32(parameters.values.x); + + var best = textureLoad(source, pixel, 0); + var best_distance = FAR; + if best.z > 0.5 { + best_distance = seed_distance(pixel, best.xy); + } + + for (var neighbor_y = -1; neighbor_y <= 1; neighbor_y++) { + for (var neighbor_x = -1; neighbor_x <= 1; neighbor_x++) { + let direction = vec2(neighbor_x, neighbor_y) * step; + let neighbor = pixel + direction; + if any(neighbor < vec2(0)) || any(neighbor >= size) { + continue; + } + let found = textureLoad(source, neighbor, 0); + if found.z < 0.5 { + continue; + } + + // Offsets run from the seed to the texel + let candidate = found.xy - vec2(direction); + let candidate_distance = seed_distance(pixel, candidate); + if candidate_distance < best_distance { + best = vec4(candidate, 1., 0.); + best_distance = candidate_distance; + } + } + } + return best; +} + +// Each texel's distance to the nearest seed's edge, or `FAR` if none is found +@fragment +fn jump_flood_distance(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let nearest = textureLoad(source, pixel, 0); + if nearest.z < 0.5 { + return vec4(FAR); + } + return vec4(max(seed_distance(pixel, nearest.xy), 0.)); +} + +// The silhouette grown by `values.x` texels, given each texel's distance to it, with the grown edge fading out over one texel +@fragment +fn grow(@builtin(position) position: vec4) -> @location(0) vec4 { + let to_silhouette = textureLoad(source, vec2(position.xy), 0).r; + return vec4(clamp(parameters.values.x + 1. - to_silhouette, 0., 1.)); +} + +// A precise glow's strength, falling through half at the edge of a grow of `values.x` texels to nothing a unit past the size of `values.y` units, at `values.z` texels per unit. +// Within the grown shape, given `secondary` with `values.w` 1, it measures how far in from the grown edge each texel lies, matching `precise_falloff`. +@fragment +fn precise_falloff(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let grow = parameters.values.x; + var measured = textureLoad(source, pixel, 0).r; + if parameters.values.w > 0.5 && measured <= grow { + measured = grow - textureLoad(secondary, pixel, 0).r; + } + + let scale = parameters.values.z; + let size = parameters.values.y; + let grow_units = grow / scale; + return vec4(clamp(0.5 - 0.5 * (measured / scale - grow_units) / (size - grow_units + 1.), 0., 1.)); +} + +// A shadow or glow's strength, strengthened to reach full at the fraction `values.x` of it, then reshaped by the contour `secondary` holds in a row with `values.y` 1, matching `shape_strength` +@fragment +fn shape_strength(@builtin(position) position: vec4) -> @location(0) vec4 { + let strength = clamp(textureLoad(source, vec2(position.xy), 0).r / parameters.values.x, 0., 1.); + if parameters.values.y < 0.5 { + return vec4(strength); + } + + // The contour's samples span its ends, each at a texel's center + let samples = f32(textureDimensions(secondary).x); + let uv = vec2((strength * (samples - 1.) + 0.5) / samples, 0.5); + return vec4(clamp(textureSampleLevel(secondary, linear_sampler, uv, 0.).r, 0., 1.)); +} + +// A glow's premultiplied color from its strength after range and contour (`source`), as the gradient `secondary` holds in a row of straight colors from its start to its end. +// Its alpha is the gradient's, faded with `values.x` 1 as the `content` strength before range and contour falls below `values.y`, then by the opacity `values.z`, matching `GlowFill::color_at`. +@fragment +fn gradient_glow_tint(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let strength = textureLoad(source, pixel, 0).r; + + let samples = f32(textureDimensions(secondary).x); + let uv = vec2(((1. - strength) * (samples - 1.) + 0.5) / samples, 0.5); + let color = textureSampleLevel(secondary, linear_sampler, uv, 0.); + + var alpha = color.a; + if parameters.values.x > 0.5 { + alpha = min(alpha, textureLoad(content, pixel, 0).r / parameters.values.y); + } + alpha *= parameters.values.z; + return vec4(color.rgb * alpha, alpha); +} + +// A silhouette's coverage in its color +@fragment +fn tint(@builtin(position) position: vec4) -> @location(0) vec4 { + return parameters.color * textureLoad(source, vec2(position.xy), 0).r; +} + +// Hides the coverage of what lies beneath behind the `content` at full strength, where the fill `amount` fades the content showing over it. +// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this. +@fragment +fn knock_out(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let alpha = textureLoad(content, pixel, 0).a; + let shown = (1. - alpha) / max(1. - parameters.amount * alpha, 1e-6); + return textureLoad(source, pixel, 0) * shown; +} + +// Stacks a tinted silhouette with its `secondary` coverage over the shadows and glows beneath the content (`source`, with `values.x` 1). +// With `values.y` 1, `secondary` is already tinted. +@fragment +fn accumulate(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + var tinted = parameters.color * textureLoad(secondary, pixel, 0).r; + if parameters.values.y > 0.5 { + tinted = textureLoad(secondary, pixel, 0); + } + + var beneath = vec4(0.); + if parameters.values.x > 0.5 { + beneath = textureLoad(source, pixel, 0); + } + return tinted + beneath * (1. - tinted.a); +} + +// Places a tinted silhouette over the image, within the content at full strength so it stays visible over a faded fill +@fragment +fn composite_within(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let image = textureLoad(source, pixel, 0); + let tinted = parameters.color * textureLoad(secondary, pixel, 0).r; + let full_content = textureLoad(content, pixel, 0); + + return tinted * full_content.a + image * (1. - tinted.a); +} + +// Places the shadows and glows beneath the image +@fragment +fn composite_beneath(@builtin(position) position: vec4) -> @location(0) vec4 { + let pixel = vec2(position.xy); + let image = textureLoad(source, pixel, 0); + let beneath = textureLoad(secondary, pixel, 0); + + return image + beneath * (1. - image.a); +} + +@fragment +fn scale(@builtin(position) position: vec4) -> @location(0) vec4 { + return textureLoad(source, vec2(position.xy), 0) * parameters.amount; +} + +@fragment +fn decode_to_linear(@builtin(position) position: vec4) -> @location(0) vec4 { + let color = textureLoad(source, vec2(position.xy), 0); + if color.a <= 0. { + return vec4(0.); + } + + return vec4(srgb_to_linear(max(color.rgb / color.a, vec3(0.))) * color.a, color.a); +} + +@fragment +fn encode_to_gamma(@builtin(position) position: vec4) -> @location(0) vec4 { + let color = textureLoad(source, vec2(position.xy), 0); + if color.a <= 0. { + return vec4(0.); + } + + return vec4(linear_to_srgb(max(color.rgb / color.a, vec3(0.))) * color.a, color.a); +} + +fn srgb_to_linear(srgb: vec3) -> vec3 { + let low = srgb / 12.92; + let high = pow((srgb + 0.055) / 1.055, vec3(2.4)); + return select(high, low, srgb <= vec3(0.04045)); +} + +fn linear_to_srgb(linear: vec3) -> vec3 { + let low = linear * 12.92; + let high = 1.055 * pow(linear, vec3(1. / 2.4)) - 0.055; + return select(high, low, linear <= vec3(0.0031308)); +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_render.rs b/node-graph/libraries/wgpu-executor/src/vello_render.rs index 04a36491665..f186b7dd711 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render.rs @@ -1,6 +1,9 @@ -use glam::UVec2; +use crate::vello_effects::{EffectPasses, EffectTextures}; +use glam::{DAffine2, UVec2}; +use graphic_types::Effects; +use graphic_types::effects::EffectCapture; use raster_types::WeakCPU; -use rendering::vello_scene_builder::{SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size}; +use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size}; use std::collections::HashMap; use std::sync::{Mutex, PoisonError}; use vello_gpu::kurbo::Affine; @@ -29,20 +32,37 @@ pub(crate) struct VelloRenderer { /// Locked only while a scene is rendered and submitted, so one canvas drawing its scene on the CPU doesn't hold up another's render. gpu: Mutex<(Renderer, Resources)>, alpha_conversion: AlphaConversion, + effect_passes: EffectPasses, } /// A stream of frames rendered through the shared Vello renderer, such as the document or the overlays, keeping what its frames reuse. #[derive(Default)] pub struct VelloCanvas { - /// The Vello GPU scene of the last render, handed out again to keep its allocations. - spare_scene: Option, + /// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations. + spare_scenes: Vec, /// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same. premultiplied_target: Option, images: ImageTextures, + effect_textures: EffectTextures, +} + +/// Whether a render leaves its target with the straight alpha the rest of Graphite expects, or the premultiplied alpha the effect passes take. +#[derive(Clone, Copy, PartialEq, Eq)] +enum TargetAlpha { + Straight, + Premultiplied, +} + +/// A render in progress: the shared renderer and GPU, and the canvas whose resources it draws with. +struct RenderContext<'a> { + renderer: &'a VelloRenderer, + canvas: &'a mut VelloCanvas, + device: &'a wgpu::Device, + queue: &'a Queue, } impl VelloRenderer { - pub(crate) fn new(device: &wgpu::Device) -> Self { + pub(crate) fn new(device: &wgpu::Device, adapter: &wgpu::Adapter) -> Self { let render_target_config = RenderTargetConfig { format: TEXTURE_FORMAT, width: 1, @@ -60,6 +80,7 @@ impl VelloRenderer { Self { gpu: Mutex::new(Renderer::new_with(device, &render_target_config, settings)), alpha_conversion: AlphaConversion::new(device), + effect_passes: EffectPasses::new(device, adapter), } } @@ -81,10 +102,15 @@ impl VelloRenderer { } canvas.images.render_count += 1; - if let Err(error) = self.render_once(canvas, device, queue, draw, view, size, target) { - self.render_halves(canvas, device, queue, draw, view, size, target, error, 1); - } + let mut context = RenderContext { + renderer: self, + canvas, + device, + queue, + }; + context.render_area(draw, view, size, target, TargetAlpha::Straight); canvas.images.free_unused(); + canvas.effect_textures.finish_render(); Ok(()) } @@ -94,27 +120,35 @@ impl VelloRenderer { pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) { canvas.images.render_count += 1; let max_texture_size = scene.max_texture_size(); - if let Err(error) = self.submit(canvas, device, queue, scene.finish(), max_texture_size, target) { + let mut context = RenderContext { + renderer: self, + canvas, + device, + queue, + }; + let (scene, images) = scene.finish(); + if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight) { log::error!("Vello GPU failed to render: {error}"); clear(device, queue, target); } canvas.images.free_unused(); + canvas.effect_textures.finish_render(); + } +} + +impl RenderContext<'_> { + /// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can. + fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) { + if let Err(error) = self.render_once(draw, view, size, target, target_alpha) { + self.render_halves(draw, view, size, target, target_alpha, error, 1); + } } /// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much. #[expect(clippy::too_many_arguments)] - fn render_halves( - &self, - canvas: &mut VelloCanvas, - device: &wgpu::Device, - queue: &Queue, - draw: &mut dyn FnMut(&mut VelloSceneBuilder), - view: Affine, - size: UVec2, - target: &wgpu::Texture, - error: RenderError, - split_depth: u32, - ) { + fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) { + let (device, queue) = (self.device, self.queue); + // Each half covers less of the scene, so it has less content and smaller layers to hold let too_much_to_hold = matches!( error, @@ -142,7 +176,7 @@ impl VelloRenderer { wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, ); let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view; - let rendered = self.render_once(canvas, device, queue, draw, half_view, half_size, &half_target); + let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha); (offset, half_size, half_view, half_target, rendered) }); @@ -166,7 +200,7 @@ impl VelloRenderer { for (offset, half_size, half_view, half_target, rendered) in halves { if let Err(half_error) = rendered { - self.render_halves(canvas, device, queue, draw, half_view, half_size, &half_target, half_error, split_depth + 1); + self.render_halves(draw, half_view, half_size, &half_target, target_alpha, half_error, split_depth + 1); } let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_split_copy") }); @@ -182,43 +216,32 @@ impl VelloRenderer { } } - /// Renders the scene `draw` draws, with its content placed by `view`, into `target`, a texture of `size`, in a single Vello GPU render. - #[expect(clippy::too_many_arguments)] - fn render_once( - &self, - canvas: &mut VelloCanvas, - device: &wgpu::Device, - queue: &Queue, - draw: &mut dyn FnMut(&mut VelloSceneBuilder), - view: Affine, - size: UVec2, - target: &wgpu::Texture, - ) -> Result<(), RenderError> { + /// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render. + fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> { let (width, height) = (size.x as u16, size.y as u16); - let max_texture_size = device.limits().max_texture_dimension_2d; + let max_texture_size = self.device.limits().max_texture_dimension_2d; - let mut scene = canvas.spare_scene.take().unwrap_or_else(|| vello_gpu::Scene::new(width, height)); + // Draw the scene for this render's size and placement, which renders its effects groups as they're drawn + let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height)); scene.reset_and_resize(width, height); - let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size); + let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self); draw(&mut builder); + let (scene, images) = builder.finish(); - self.submit(canvas, device, queue, builder.finish(), max_texture_size, target) + let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha); + // Once the render that draws it is submitted, the scene is free to reuse + self.canvas.spare_scenes.push(scene); + rendered } /// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render. - fn submit( - &self, - canvas: &mut VelloCanvas, - device: &wgpu::Device, - queue: &Queue, - (scene, images): (vello_gpu::Scene, Vec), - max_texture_size: u32, - target: &wgpu::Texture, - ) -> Result<(), RenderError> { + fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> { + let device = self.device; let (width, height) = (scene.width(), scene.height()); + let size = UVec2::new(width as u32, height as u32); // Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue - let queue = queue.lock(); + let queue = self.queue.lock(); // Each render submits its own encoder, since Vello GPU stages its uploads for the next submission let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") }); @@ -226,34 +249,35 @@ impl VelloRenderer { // Supply the textures of the images the scene draws, under the IDs it drew them with let mut texture_bindings = TextureBindings::new(); for (id, image) in images.iter().enumerate() { - if let Some(view) = canvas.images.prepare(device, &queue, &mut encoder, &self.alpha_conversion, image, max_texture_size) { + if let Some(view) = self.canvas.images.prepare(device, &queue, &mut encoder, &self.renderer.alpha_conversion, image, max_texture_size) { texture_bindings.insert(TextureId(id as u64), view); } } - // Render premultiplied, then convert to the straight alpha the rest of Graphite expects - let size = UVec2::new(width as u32, height as u32); - let premultiplied_target = match &canvas.premultiplied_target { - Some(texture) if texture.width() == size.x && texture.height() == size.y => texture.clone(), - _ => { + // Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied + let target_view = target.create_view(&wgpu::TextureViewDescriptor::default()); + let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) { + (TargetAlpha::Premultiplied, _) => target_view.clone(), + (TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()), + (TargetAlpha::Straight, _) => { let texture = create_texture( device, "vello_gpu_premultiplied_target", size, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, ); - canvas.premultiplied_target = Some(texture.clone()); - texture + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + self.canvas.premultiplied_target = Some(texture); + view } }; - let premultiplied_view = premultiplied_target.create_view(&wgpu::TextureViewDescriptor::default()); let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT }); // Vello GPU stages this render's uploads into resources every render shares, so another can't stage its own until this one is submitted - let mut gpu = self.gpu.lock().unwrap_or_else(PoisonError::into_inner); + let mut gpu = self.renderer.gpu.lock().unwrap_or_else(PoisonError::into_inner); let (renderer, resources) = &mut *gpu; let rendered = renderer.render( - &scene, + scene, resources, device, &queue, @@ -265,20 +289,52 @@ impl VelloRenderer { target_init, ); - if rendered.is_ok() { - let target_view = target.create_view(&wgpu::TextureViewDescriptor::default()); - self.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view); + if rendered.is_ok() && target_alpha == TargetAlpha::Straight { + self.renderer.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view); } // Submitted even after a failure, since it also prepares the textures of the scene's images queue.submit([encoder.finish()]); drop((gpu, queue)); - canvas.spare_scene = Some(scene); + + // Once the render that draws them is submitted, its effects results are free to reuse + for image in images { + if let SceneImage::Rendered(texture) = image { + self.canvas.effect_textures.release(texture); + } + } rendered } } +impl EffectsRenderer for RenderContext<'_> { + fn renders_effects(&self) -> bool { + self.renderer.effect_passes.renders_working_formats + } + + fn render_effects( + &mut self, + size: UVec2, + view: Affine, + effects: &Effects, + fill: f32, + effect_to_pixels: DAffine2, + capture: Option, + draw: &mut dyn FnMut(&mut VelloSceneBuilder), + ) -> wgpu::Texture { + let content_texture = self.canvas.effect_textures.acquire(self.device, size, TEXTURE_FORMAT); + self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied); + + let effect_textures = &mut self.canvas.effect_textures; + let queue = self.queue.lock(); + let result = (self.renderer.effect_passes).apply(self.device, &queue, effect_textures, &content_texture, effects, fill, effect_to_pixels.matrix2, capture); + effect_textures.release(content_texture); + + result + } +} + /// Leaves `target` transparent. fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_clear") }); @@ -325,6 +381,8 @@ impl ImageTextures { SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()), SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()), SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()), + // Effects results are premultiplied already + SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())), }; if !self.textures.contains_key(&key) { @@ -341,6 +399,7 @@ impl ImageTextures { let (pixels, width, height) = raster.to_flat_u8(); upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)? } + SceneImage::Rendered(_) => return None, SceneImage::Texture(texture) => create_texture( device, "vello_gpu_premultiplied_image", @@ -350,7 +409,7 @@ impl ImageTextures { }; let raster = match image { SceneImage::Raster(raster) => Some(raster.downgrade()), - SceneImage::Pixels(_) | SceneImage::Texture(_) => None, + SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) => None, }; self.textures.insert(key.clone(), ImageTexture { texture, last_used: 0, raster }); } @@ -406,35 +465,83 @@ fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], widt let (texture_width, texture_height) = image_texture_size(width, height, max_texture_size); let pixels = if factor == 1 { premultiplied } else { box_downscale(&premultiplied, width, height, factor) }; - let texture = create_texture( - device, - "vello_gpu_image", - UVec2::new(texture_width, texture_height), - wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - ); - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &texture, - mip_level: 0, - origin: wgpu::Origin3d::ZERO, - aspect: wgpu::TextureAspect::All, - }, - &pixels, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(4 * texture_width), - rows_per_image: Some(texture_height), - }, - wgpu::Extent3d { + // Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them + let level_count = texture_width.max(texture_height).ilog2() + 1; + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("vello_gpu_image"), + size: wgpu::Extent3d { width: texture_width, height: texture_height, depth_or_array_layers: 1, }, - ); + mip_level_count: level_count, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: TEXTURE_FORMAT, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height); + for level in 0..level_count { + if level > 0 { + (level_pixels, level_width, level_height) = halve_for_mipmap(&level_pixels, level_width, level_height); + } + + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: level, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + &level_pixels, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(4 * level_width), + rows_per_image: Some(level_height), + }, + wgpu::Extent3d { + width: level_width, + height: level_height, + depth_or_array_layers: 1, + }, + ); + } Some(texture) } +/// Halves premultiplied RGBA8 pixels to the next mipmap level's size, which rounds down, so the last pixel of each row and column of an odd side averages three. +/// O(width × height). +fn halve_for_mipmap(pixels: &[u8], width: u32, height: u32) -> (Vec, u32, u32) { + let (half_width, half_height) = ((width / 2).max(1), (height / 2).max(1)); + // The source pixels along one side that an output pixel averages + let span = |index: u32, half: u32, full: u32| { + let start = index * 2; + let end = if index + 1 == half { full } else { start + 2 }; + start..end.clamp(start + 1, full) + }; + + let mut output = Vec::with_capacity((half_width * half_height * 4) as usize); + for output_y in 0..half_height { + for output_x in 0..half_width { + let mut sums = [0_u32; 4]; + let mut count = 0; + for y in span(output_y, half_height, height) { + for x in span(output_x, half_width, width) { + let index = ((y * width + x) * 4) as usize; + sums.iter_mut().zip(&pixels[index..index + 4]).for_each(|(sum, channel)| *sum += *channel as u32); + count += 1; + } + } + output.extend(sums.map(|sum| ((sum + count / 2) / count) as u8)); + } + } + + (output, half_width, half_height) +} + /// Averages each `factor` by `factor` block of RGBA8 pixels, letting blocks at the right and bottom edges average only the pixels they have. fn box_downscale(pixels: &[u8], width: u32, height: u32, factor: u32) -> Vec { let (output_width, output_height) = (width.div_ceil(factor), height.div_ceil(factor)); diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index b28c018ca3e..2afac201b94 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -274,6 +274,346 @@ fn degenerate_strokes_render() { let Some(_) = render(size, draw) else { return }; } +/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`. +fn render_square_with_effects(effects: Vec, fill: f32, min: f64, max: f64, size: UVec2) -> Option> { + render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size) +} + +/// Like [`render_square_with_effects`], carrying out the effects in an `effect_space` placed in the document. +fn render_square_with_effects_in(effects: Vec, effect_space: DAffine2, fill: f32, min: f64, max: f64, size: UVec2) -> Option> { + let square = Rect::new(min, min, max, max); + let effects = graphic_types::Effects::from_operations(effects); + + render(size, |scene| { + scene.draw_effects(&effects, fill, Some(square), effect_space, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) + }); + }) +} + +/// A drop shadow falling at `offset` from the content, with its own `size` and `spread` percentage, knocked out by the content. +fn drop_shadow(color: core_types::Color, offset: glam::DVec2, size: f64, spread: f64) -> graphic_types::EffectOperation { + graphic_types::EffectOperation::DropShadow { + color, + angle: offset.y.atan2(-offset.x).to_degrees(), + distance: offset.length(), + spread, + size, + contour: Default::default(), + knockout: true, + } +} + +/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7. +fn normal_cdf(x: f64) -> f64 { + let z = x.abs() / std::f64::consts::SQRT_2; + let t = 1. / (1. + 0.327_591_1 * z); + let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429)))); + let erf = 1. - polynomial * (-z * z).exp(); + + if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) } +} + +#[test] +fn gaussian_blur_follows_the_normal_distribution() { + use graphic_types::EffectOperation; + + let size = UVec2::new(512, 256); + // Small kernels run directly, and larger ones on halved textures + for sigma in [2., 6., 20.] { + let blur = EffectOperation::Blur { + radius: sigma, + box_blur: false, + gamma: false, + }; + // A square much larger than the blur, so across its left edge at x = 100, on a row far from its other edges, the coverage is the one-dimensional profile + let Some(pixels) = render_square_with_effects(vec![blur], 1., 100., 400., size) else { return }; + + let mut worst = 0_f64; + for x in 40..160 { + let expected = normal_cdf((x as f64 + 0.5 - 100.) / sigma); + let actual = pixel(&pixels, size, x, 200)[3] as f64 / 255.; + worst = worst.max((expected - actual).abs()); + } + assert!(worst < 0.03, "σ {sigma} strays from the normal distribution by {worst}"); + } +} + +#[test] +fn blurs_stretch_with_an_effect_space_scaled_unevenly() { + use graphic_types::EffectOperation; + + // Three times as wide as it is tall, the effect space renders in a texture of its own, so the blur of 4 spreads 12 pixels across and 4 down + let size = UVec2::new(512, 512); + let blur = EffectOperation::Blur { + radius: 4., + box_blur: false, + gamma: false, + }; + let Some(pixels) = render_square_with_effects_in(vec![blur], DAffine2::from_scale(glam::DVec2::new(3., 1.)), 1., 100., 400., size) else { + return; + }; + + let stray = |sigma: f64, coverage: &dyn Fn(u32) -> u8| (40..160).map(|at| (normal_cdf((at as f64 + 0.5 - 100.) / sigma) - coverage(at) as f64 / 255.).abs()).fold(0., f64::max); + let across = stray(12., &|x| pixel(&pixels, size, x, 250)[3]); + let down = stray(4., &|y| pixel(&pixels, size, 250, y)[3]); + assert!(across < 0.04 && down < 0.04, "the blur strays from σ 12 across by {across} and σ 4 down by {down}"); +} + +#[test] +fn shadows_turn_with_their_effect_space() { + use core_types::Color as GraphicColor; + + // A shadow cast to the right of the content in an effect space turned a quarter clockwise falls below it in the document + let size = UVec2::new(256, 256); + let shadow = drop_shadow(GraphicColor::BLACK, glam::DVec2::new(30., 0.), 0., 0.); + let Some(pixels) = render_square_with_effects_in(vec![shadow], DAffine2::from_angle(std::f64::consts::FRAC_PI_2), 1., 50., 150., size) else { + return; + }; + + assert!(pixel(&pixels, size, 100, 165)[3] > 200, "the shadow should fall below the square"); + assert_eq!(pixel(&pixels, size, 165, 100)[3], 0, "the shadow shouldn't fall to its right"); +} + +#[test] +fn shadows_and_glows_fall_where_they_should() { + use core_types::Color as GraphicColor; + use glam::DVec2; + use graphic_types::EffectOperation; + + let size = UVec2::new(128, 128); + let black = GraphicColor::BLACK; + + // A hard drop shadow offset down and right shows past the square's bottom right corner, beneath it + let shadow = drop_shadow(black, DVec2::new(10., 10.), 0., 0.); + let Some(pixels) = render_square_with_effects(vec![shadow.clone()], 1., 30., 80., size) else { + return; + }; + assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "the content covers its shadow"); + assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow shows past the content"); + assert_eq!(pixel(&pixels, size, 25, 25)[3], 0, "no shadow before the offset"); + + // With no fill, the content vanishes and its shadow stays knocked out where the content would be + let Some(pixels) = render_square_with_effects(vec![shadow], 0., 30., 80., size) else { return }; + assert_eq!(pixel(&pixels, size, 50, 50)[3], 0, "the shadow is knocked out by the faded content"); + assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow stays at full strength"); + + // An inner shadow darkens the content's top left edges from inside and stays within it + let inner_shadow = EffectOperation::InnerShadow { + color: black, + angle: 135., + distance: 6. * std::f64::consts::SQRT_2, + choke: 0., + size: 0., + contour: Default::default(), + }; + let Some(pixels) = render_square_with_effects(vec![inner_shadow], 1., 30., 80., size) else { + return; + }; + assert_eq!(pixel(&pixels, size, 32, 50), [0, 0, 0, 255], "inside the left edge"); + assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "deep inside"); + assert_eq!(pixel(&pixels, size, 78, 50), [255, 255, 255, 255], "inside the right edge, away from the offset"); + assert_eq!(pixel(&pixels, size, 25, 50)[3], 0, "outside"); + + // A glow grown by its whole size surrounds the content evenly + let glow = EffectOperation::OuterGlow { + color: GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 1.).into(), + technique: Default::default(), + spread: 100., + size: 5., + range: 50., + contour: Default::default(), + }; + let Some(pixels) = render_square_with_effects(vec![glow], 1., 30., 80., size) else { return }; + for (x, y) in [(27, 55), (82, 55), (55, 27), (55, 82)] { + assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "glow at ({x}, {y})"); + } + for (x, y) in [(23, 55), (87, 55)] { + assert_eq!(pixel(&pixels, size, x, y)[3], 0, "past the glow at ({x}, {y})"); + } +} + +#[test] +fn later_shadows_stack_over_earlier_ones_beneath_the_content() { + use core_types::Color as GraphicColor; + use glam::DVec2; + + let size = UVec2::new(128, 128); + let shadow = |color, offset: f64| drop_shadow(color, DVec2::splat(offset), 0., 0.); + + // Both shadows are cast from the content rather than from each other, and the later one is on top where they overlap + let effects = vec![shadow(GraphicColor::BLACK, 10.), shadow(GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 1.), 5.)]; + let Some(pixels) = render_square_with_effects(effects, 1., 30., 80., size) else { return }; + assert_eq!(pixel(&pixels, size, 82, 82), [0, 0, 255, 255], "the later shadow is on top"); + assert_eq!(pixel(&pixels, size, 88, 88), [0, 0, 0, 255], "the earlier shadow reaches further"); + assert_eq!(pixel(&pixels, size, 93, 93)[3], 0, "no shadow of a shadow"); +} + +#[test] +fn nested_effects_groups_render_inside_out() { + use core_types::Color as GraphicColor; + use glam::DVec2; + use graphic_types::{EffectOperation, Effects}; + + let size = UVec2::new(128, 128); + let square = Rect::new(30., 30., 80., 80.); + + // A hard shadow around a group whose content is itself a blurred square + let shadow = Effects::from_operations([drop_shadow(GraphicColor::BLACK, DVec2::new(20., 0.), 0., 0.)]); + let blur = Effects::from_operations([EffectOperation::Blur { + radius: 3., + box_blur: false, + gamma: false, + }]); + let draw = |scene: &mut VelloSceneBuilder| { + scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), DAffine2::IDENTITY, &mut |scene| { + scene.draw_effects(&blur, 1., Some(square), DAffine2::IDENTITY, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) + }); + }); + }; + + let Some(pixels) = render(size, draw) else { return }; + let edge = pixel(&pixels, size, 30, 55); + assert!((100..=155).contains(&edge[3]), "the blur softens the edge to half coverage, not {edge:?}"); + // Ten pixels past the content's blurred edge, where the shadow is cast from ten pixels inside it + let shadow = pixel(&pixels, size, 90, 55); + assert!(shadow[3] >= 250 && shadow[0] <= 5, "the shadow is cast by the blurred group, not {shadow:?}"); +} + +#[test] +fn cpu_evaluated_effects_match_the_gpu_passes() { + use core_types::Color as GraphicColor; + use core_types::list::Item; + use core_types::transfer_curve::TransferCurve; + use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::vector_types::gradient::{Gradient, GradientStop}; + use graphic_types::{Effect, EffectOperation, GlowTechnique, Graphic, stamp_effect}; + use raster_kernels::evaluate_raster_effects; + + let size = UVec2::new(160, 160); + let (min, max) = (50, 100); + let shadow_color = GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75); + let blur = |radius, box_blur, gamma| EffectOperation::Blur { radius, box_blur, gamma }; + + let gradient_glow = |color, technique, spread, size, range, contour| EffectOperation::OuterGlow { + color, + technique, + spread, + size, + range, + contour, + }; + let glow = |technique, spread, size, range, contour| gradient_glow(shadow_color.into(), technique, spread, size, range, contour); + let stop = |position, color| GradientStop { position, midpoint: 0.5, color }; + let fading = Graphic::from(Gradient::new([ + stop(0., GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 1.)), + stop(0.4, GraphicColor::from_rgbaf32_unchecked(0.9, 0.2, 0.1, 0.8)), + stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0., 0.6, 0.)), + ])); + let opaque = Graphic::from(Gradient::new([ + stop(0., GraphicColor::from_rgbaf32_unchecked(0.1, 0.8, 0.3, 1.)), + stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0.1, 0.9, 1.)), + ])); + let bow = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]); + + let cases = [ + vec![blur(3., false, false)], + vec![blur(20., false, true)], + vec![blur(5.5, true, false)], + vec![drop_shadow(shadow_color, DVec2::new(6.5, -3.), 8., 25.)], + vec![drop_shadow(shadow_color, DVec2::new(2., 3.), 40., 0.)], + vec![EffectOperation::InnerShadow { + color: shadow_color, + angle: 135., + distance: 5., + choke: 50., + size: 6., + contour: TransferCurve::default(), + }], + vec![glow(GlowTechnique::Softer, 30., 9., 50., TransferCurve::default()), blur(2., false, false)], + vec![glow(GlowTechnique::Precise, 0., 12., 75., bow.clone())], + vec![glow(GlowTechnique::Precise, 50., 16., 100., TransferCurve::default())], + vec![glow(GlowTechnique::Precise, 80., 10., 100., TransferCurve::default())], + vec![glow(GlowTechnique::Softer, 0., 6., 50., bow.clone())], + vec![gradient_glow(fading, GlowTechnique::Precise, 0., 14., 75., TransferCurve::default())], + vec![gradient_glow(opaque, GlowTechnique::Softer, 25., 12., 50., bow)], + ]; + + for effects in cases { + for fill in [1., 0.5] { + let Some(gpu) = render_square_with_effects(effects.clone(), fill, min as f64, max as f64, size) else { + return; + }; + + // The same square as a raster covering the render one pixel to one pixel + let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT); + for y in min..max { + for x in min..max { + image.data[(y * size.x + x) as usize] = GraphicColor::WHITE; + } + } + let mut item = Item::new_from_element(Raster::new_cpu(image)) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())) + .with_attribute(ATTR_OPACITY_FILL, fill as f64); + effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + let evaluated = evaluate_raster_effects(item); + + // Reads the evaluated image at the center of each render pixel through its grown placement + let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); + let raster = evaluated.element(); + let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); + + let mut worst = 0; + for y in 0..size.y { + for x in 0..size.x { + let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); + let cpu = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize]; + let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels(); + let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); + + // Compared premultiplied, so a nearly transparent pixel's color can't dominate + let gpu = pixel(&gpu, size, x, y); + let gpu_alpha = gpu[3] as f32 / 255.; + for channel in 0..4 { + let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; + worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); + } + } + } + assert!(worst <= 2, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); + } + } +} + +#[test] +fn minified_images_average_their_pixels() { + use raster_types::{Image, Raster}; + + // Stripes half black and half white in every eight columns, drawn at an eighth of their size, where sampling only the two + // columns nearest each pixel's center would find black + let stripes = Image { + width: 64, + height: 64, + data: (0..64 * 64) + .map(|index| if (2..6).contains(&(index % 8)) { core_types::Color::BLACK } else { core_types::Color::WHITE }) + .collect(), + }; + let stripes = Raster::new_cpu(stripes); + let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(stripes.clone(), peniko::ImageSampler::new(), Affine::scale(1. / 8.)); + + let size = UVec2::new(8, 8); + let Some(pixels) = render(size, draw) else { return }; + for (index, pixel) in pixels.iter().enumerate() { + assert!( + (115..=140).contains(&pixel[0]) && pixel[1] == pixel[0] && pixel[2] == pixel[0] && pixel[3] == 255, + "pixel {index} is {pixel:?} rather than the gray of its average" + ); + } +} + #[test] fn rasters_upload_once_across_scenes_until_modified() { use raster_types::{Image, Raster}; diff --git a/node-graph/node-macro/Cargo.toml b/node-graph/node-macro/Cargo.toml index 1b859545a3f..6a128c730a5 100644 --- a/node-graph/node-macro/Cargo.toml +++ b/node-graph/node-macro/Cargo.toml @@ -24,8 +24,8 @@ quote = { workspace = true } convert_case = { workspace = true } indoc = { workspace = true } -proc-macro-crate = "3.1.0" -proc-macro-error2 = "2" +proc-macro-crate = "3.1" +proc-macro-error3 = "3.1" [dev-dependencies] core-types = { workspace = true } diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 5950b309059..977eba83fcf 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -55,7 +55,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn // Separate data fields from regular fields let (data_fields, regular_fields): (Vec<_>, Vec<_>) = fields_iter.partition(|f| f.is_data_field); - // The primary's position among the regular fields, which `#[scope]` fields may precede (`#[data]` fields are already partitioned out) + // The primary's position among the regular fields, which is 0 unless the node has no parameters, since validation keeps environment fields after them let primary_regular_index = regular_fields.iter().position(|field| !field.is_environment()); // Extract function generics used by data fields @@ -205,6 +205,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn } } ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId), + ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath), _ => quote!(RegistryValueSource::None), }) .collect(); @@ -523,18 +524,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote!(#[derive(Debug, Clone)]) }; - // Generate serialize method if serialize attribute is specified - let serialize_impl = if let Some(serialize_fn) = &parsed.attributes.serialize { - let data_field_refs = data_field_names.iter().map(|name| quote!(&self.#name)); - quote! { - fn serialize(&self) -> Option> { - #serialize_fn(#(#data_field_refs),*) - } - } - } else { - quote!() - }; - let eval_prelude = quote! { use #core_types::misc::Clampable; @@ -646,8 +635,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { #landed_call }); __cell.merge(__state) } - - #serialize_impl } } else { quote! { @@ -661,8 +648,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; #fold } - - #serialize_impl } }; @@ -756,8 +741,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; __cell.run(__kernel) } - - #serialize_impl } }); @@ -831,8 +814,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; __cell.run(__kernel) } - - #serialize_impl } }); @@ -1057,7 +1038,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn #register_node_impl - #[cfg_attr(not(target_family = "wasm"), ctor)] + #[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))] fn register_metadata() { let metadata = NodeMetadata { display_name: #display_name, @@ -1429,7 +1410,7 @@ fn generate_register_node_impl( } } Ok(quote! { - #[cfg_attr(not(target_family = "wasm"), ctor)] + #[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))] fn register_node() { let mut registry = NODE_REGISTRY.lock().unwrap(); registry.insert( diff --git a/node-graph/node-macro/src/destructure.rs b/node-graph/node-macro/src/destructure.rs index e3993b9981d..d47770c6c3d 100644 --- a/node-graph/node-macro/src/destructure.rs +++ b/node-graph/node-macro/src/destructure.rs @@ -236,7 +236,7 @@ pub fn derive_destructure_impl(item: TokenStream2) -> syn::Result } }; - // Memoize lets the node's outputs share one evaluation, and Monitor lets the editor inspect the struct + // Memoize lets the node's outputs share one evaluation let registration_module = format_ident!("_{struct_snake_name}_registration"); let wasm_registration = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, Ordering::SeqCst), struct_ident); let registration = quote! { @@ -245,16 +245,16 @@ pub fn derive_destructure_impl(item: TokenStream2) -> syn::Result use super::*; use #gcore::ctor::ctor; - #[cfg_attr(not(target_family = "wasm"), ctor)] - fn register_memoize_and_monitor() { - #graphene_core::memo::register_memoize_and_monitor::<#struct_ident>(); - #graphene_core::memo::register_memoize_and_monitor::<#mapped_ident>(); + #[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = core_types::ctor))] + fn register_memoize() { + #graphene_core::memo::register_memoize::<#struct_ident>(); + #graphene_core::memo::register_memoize::<#mapped_ident>(); } #[cfg(target_family = "wasm")] #[unsafe(no_mangle)] extern "C" fn #wasm_registration() { - register_memoize_and_monitor(); + register_memoize(); } } }; diff --git a/node-graph/node-macro/src/lib.rs b/node-graph/node-macro/src/lib.rs index 99033fa7a55..b988d7d3af7 100644 --- a/node-graph/node-macro/src/lib.rs +++ b/node-graph/node-macro/src/lib.rs @@ -1,5 +1,5 @@ use proc_macro::TokenStream; -use proc_macro_error2::proc_macro_error; +use proc_macro_error3::proc_macro_error; mod codegen; mod crate_ident; diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index 3f5b0d30ebb..06241e9efde 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -65,8 +65,6 @@ pub(crate) struct NodeFnAttributes { pub(crate) inspector_string: Option, /// whether to `#[cfg]` gate the node implementation, defaults to None pub(crate) cfg: Option, - /// Custom serialization function path (e.g., "my_module::custom_serialize") - pub(crate) serialize: Option, pub(crate) flags: NodeFlags, /// Fn producing an placeholder value used while node evaluation is pending pub(crate) placeholder: Option, @@ -81,6 +79,7 @@ pub enum ParsedValueSource { Default(TokenStream2), Scope(Box), SourceId, + NodePath, } // #[widget(ParsedWidgetOverride::Hidden)] @@ -174,10 +173,10 @@ impl ParsedField { } } - /// Whether the field is environment rather than an argument: `#[data]` state or a `#[scope]`-injected wire. + /// Whether the field is environment rather than an argument: `#[data]` state, a `#[scope]`-injected wire, or a `#[source_id]` or `#[node_path]` value the compiler fills in. /// Environment fields never classify the node, never supply the element-wise frame, and broadcast by clone. pub(crate) fn is_environment(&self) -> bool { - self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId) + self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId | ParsedValueSource::NodePath) } } @@ -440,7 +439,6 @@ impl Parse for NodeFnAttributes { let mut path = None; let mut inspector_string = None; let mut cfg = None; - let mut serialize = None; let mut flags = NodeFlags::default(); let mut placeholder = None; let mut version = None; @@ -543,20 +541,6 @@ impl Parse for NodeFnAttributes { let meta = meta.require_list()?; cfg = Some(meta.tokens.clone()); } - // Function name for custom serialization of this node's data. This is only used by the Monitor node. - // - // Example usage: - // #[node_macro::node(..., serialize(my_module::custom_serialize), ...)] - "serialize" => { - let meta = meta.require_list()?; - if serialize.is_some() { - return Err(Error::new_spanned(meta, "Multiple 'serialize' attributes are not allowed")); - } - let parsed_path: Path = meta - .parse_args() - .map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'serialize', e.g., serialize(my_module::custom_serialize)"))?; - serialize = Some(parsed_path); - } // Instructs the preprocessor to insert a Memoize node after this node in the generated subnetwork, // caching its output across evaluations with identical inputs. // @@ -620,7 +604,7 @@ impl Parse for NodeFnAttributes { indoc!( r#" Unsupported attribute in `node`. - Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'. + Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'. Example usage: #[node_macro::node(..., name("Test Node"), ...)] "# @@ -650,7 +634,6 @@ impl Parse for NodeFnAttributes { path, inspector_string, cfg, - serialize, flags, placeholder, version, @@ -879,6 +862,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul // Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation let source_id = extract_attribute(attrs, "source_id").is_some(); + // Gives a node the path of the document node it was placed as + let node_path = extract_attribute(attrs, "node_path").is_some(); + // Validate data field attributes if is_data_field { if default_value.is_some() { @@ -905,6 +891,18 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul if source_id { return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute")); } + if node_path { + return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[node_path] attribute")); + } + } + if source_id && node_path { + return Err(Error::new_spanned(&pat_ident, "Cannot have both `source_id` and `node_path` attributes")); + } + if exposed && (source_id || node_path) { + return Err(Error::new_spanned( + &pat_ident, + "Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose]). They aren't set in the graph", + )); } if exposed && ident.to_string().starts_with('_') { return Err(Error::new_spanned( @@ -916,9 +914,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul let value_source = match (default_value, scope) { (Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")), (Some(_), _) | (_, Some(_)) if source_id => return Err(Error::new_spanned(&pat_ident, "`source_id` cannot have a `default` or `scope` attribute")), + (Some(_), _) | (_, Some(_)) if node_path => return Err(Error::new_spanned(&pat_ident, "`node_path` cannot have a `default` or `scope` attribute")), (Some(default_value), _) => ParsedValueSource::Default(default_value), (_, Some(scope)) => ParsedValueSource::Scope(Box::new(scope)), _ if source_id => ParsedValueSource::SourceId, + _ if node_path => ParsedValueSource::NodePath, _ => ParsedValueSource::None, }; @@ -1172,7 +1172,6 @@ impl ParsedNodeFn { ident: ident.clone(), colon_token: Some(Default::default()), bounds, - eq_token: None, default: None, })); self.input.ty = parse_quote!(#ident); @@ -1881,6 +1880,24 @@ mod tests { parse_node_fn(attr, input).unwrap(); } + #[test] + #[should_panic(expected = "Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose])")] + fn test_exposed_node_path() { + let attr = quote!(category("Invalid")); + let input = quote!( + fn invalid_node( + _: impl Ctx, + content: Item, + #[expose] + #[node_path] + node_path: Item, + ) -> Item { + content + } + ); + parse_node_fn(attr, input).unwrap(); + } + #[test] #[should_panic(expected = "Unsupported attribute in `node`")] fn test_unsupported_attribute() { diff --git a/node-graph/node-macro/src/validation.rs b/node-graph/node-macro/src/validation.rs index 7d4d9a5c0ce..0cdab673a44 100644 --- a/node-graph/node-macro/src/validation.rs +++ b/node-graph/node-macro/src/validation.rs @@ -1,5 +1,5 @@ use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier}; -use proc_macro_error2::{abort_if_dirty, emit_error}; +use proc_macro_error3::{abort_if_dirty, emit_error}; use quote::quote; use syn::spanned::Spanned; use syn::{GenericParam, Type}; @@ -16,6 +16,7 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> { validate_element_wise, validate_ranked_inputs, validate_async, + validate_non_parameters_trail, ]; for validator in validators { @@ -460,6 +461,26 @@ fn validate_async(parsed: &ParsedNodeFn) { } } +/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters. +/// That keeps the primary input at index 0, where the editor's chain flow and other nodes feeding the primary input expect it. +fn validate_non_parameters_trail(parsed: &ParsedNodeFn) { + if let Some((span, message)) = non_parameter_order_violation(parsed) { + emit_error!(span, "{}", message); + } +} + +fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2::Span, String)> { + let non_parameter = parsed.fields.iter().find(|field| field.is_environment())?; + let parameter = parsed.fields.iter().skip_while(|field| !field.is_environment()).find(|field| !field.is_environment())?; + + let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident); + let message = format!( + "The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow feeds.", + parameter.ident + ); + Some((parameter.span(), message)) +} + fn validate_node_implementation(impl_: &Implementation, input_type: &Type, output_type: &Type, fn_generics: &[GenericParam]) { if contains_generic_param(&impl_.input, fn_generics) || contains_generic_param(&impl_.output, fn_generics) { emit_error!( @@ -664,6 +685,48 @@ mod tests { assert_eq!(data_field_messages, Vec::::new()); } + fn order_violation(input: TokenStream) -> Option { + let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse"); + non_parameter_order_violation(&parsed).map(|(_, message)| message) + } + + #[test] + fn a_parameter_after_a_non_parameter_is_rejected() { + let primary = order_violation(quote::quote!( + fn render(_: impl Ctx, #[scope("executor")] executor: Item, data: Item) -> Item { + data + } + )); + let primary = primary.expect("the scope input before the primary should be rejected"); + assert!(primary.contains("The parameter `data` comes after `executor`"), "{primary}"); + + let secondary = order_violation(quote::quote!( + fn render(_: impl Ctx, data: Item, #[data] cache: u64, opacity: Item) -> Item { + data + } + )); + let secondary = secondary.expect("the data field before a secondary parameter should be rejected"); + assert!(secondary.contains("The parameter `opacity` comes after `cache`"), "{secondary}"); + } + + #[test] + fn non_parameters_after_the_parameters_pass() { + let trailing = order_violation(quote::quote!( + fn render(_: impl Ctx, data: Item, #[scope("executor")] executor: Item, #[data] cache: u64) -> Item { + data + } + )); + assert_eq!(trailing, None); + + // A node with only non-parameters, like a scope provider, has no primary input to keep first + let only_non_parameters = order_violation(quote::quote!( + fn executor(_: impl Ctx, #[scope("application-io")] application_io: Item, #[data] cache: u64) -> Item { + application_io + } + )); + assert_eq!(only_non_parameters, None); + } + fn row_count_violations(input: TokenStream) -> Vec { let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse"); implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect() diff --git a/node-graph/nodes/blending/src/effects.rs b/node-graph/nodes/blending/src/effects.rs new file mode 100644 index 00000000000..3fa57f0654a --- /dev/null +++ b/node-graph/nodes/blending/src/effects.rs @@ -0,0 +1,190 @@ +use core_types::list::Item; +use core_types::transfer_curve::TransferCurve; +use core_types::{Color, Ctx}; +use graphic_types::raster_types::{CPU, GPU, Raster}; +use graphic_types::{Effect, EffectOperation, GlowTechnique, Graphic, Vector, stamp_effect}; +use vector_types::Gradient; + +/// Blurs the input graphics, whether vector shapes, images, or text. +#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"), version(2))] +fn blur( + _: impl Ctx, + /// The content to blur. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String)] + content: Item, + /// How far the blur spreads each point of the content. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..100)] + radius: Item, + /// Use a box kernel instead of a circular Gaussian kernel, which averages evenly and leaves boxy artifacts. + box_blur: Item, + /// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software. + gamma: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::Blur { + radius: *radius.element(), + box_blur: *box_blur.element(), + gamma: *gamma.element(), + }), + ); + content +} + +/// Casts a soft shadow of the input graphics' silhouette beneath them. +#[node_macro::node(category("Raster: Effect"), icon("NodeDropShadow"))] +fn drop_shadow( + _: impl Ctx, + /// The content casting the shadow. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String)] + content: Item, + /// The shadow's color, with its opacity. + #[default("#000000bf")] + color: Item, + /// The direction the light comes from, which the shadow falls away from. + #[unit("°")] + #[range] + #[soft(-180..180)] + #[default(120.)] + angle: Item, + /// How far the shadow falls from the content. + #[unit(" px")] + #[hard(0..)] + #[default(5.)] + distance: Item, + /// How much of the size hardens the shadow by growing its edge outward, rather than softening it. + #[unit("%")] + #[range] + #[hard(0..100)] + spread: Item, + /// How far the shadow reaches past the content's silhouette. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..250)] + #[default(5.)] + size: Item, + /// Reshapes how the shadow's strength falls off across its size. + contour: Item, + /// Hides the shadow behind the content even where the content's fill is faded. + #[default(true)] + knockout: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::DropShadow { + color: *color.element(), + angle: *angle.element(), + distance: *distance.element(), + spread: *spread.element(), + size: *size.element(), + contour: contour.into_element(), + knockout: *knockout.element(), + }), + ); + content +} + +/// Casts a soft shadow inward from the edges of the input graphics, as if they were cut out of the surface. +#[node_macro::node(category("Raster: Effect"), icon("NodeInnerShadow"))] +fn inner_shadow( + _: impl Ctx, + /// The content the shadow falls inside. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String)] + content: Item, + /// The shadow's color, with its opacity. + #[default("#000000bf")] + color: Item, + /// The direction the light comes from, which the edges facing it cast the shadow away from. + #[unit("°")] + #[range] + #[soft(-180..180)] + #[default(120.)] + angle: Item, + /// How far the shadow falls from the edges casting it. + #[unit(" px")] + #[hard(0..)] + #[default(5.)] + distance: Item, + /// How much of the size hardens the shadow by growing its edge inward, rather than softening it. + #[unit("%")] + #[range] + #[hard(0..100)] + choke: Item, + /// How far the shadow reaches in from the content's edges. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..250)] + #[default(5.)] + size: Item, + /// Reshapes how the shadow's strength falls off across its size. + contour: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::InnerShadow { + color: *color.element(), + angle: *angle.element(), + distance: *distance.element(), + choke: *choke.element(), + size: *size.element(), + contour: contour.into_element(), + }), + ); + content +} + +/// Surrounds the input graphics with a soft glow of their silhouette. +#[node_macro::node(category("Raster: Effect"), icon("NodeOuterGlow"))] +fn outer_glow( + _: impl Ctx, + /// The content to glow around. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String)] + content: Item, + /// The glow's color with its opacity, or a gradient that runs from the content's edge outward across the glow. + #[default("#ffffbebf")] + color: Item, + /// Whether the glow fades like a blur or evenly with the distance from the content. + technique: Item, + /// How much of the size hardens the glow by growing its edge outward, rather than softening it. + #[unit("%")] + #[range] + #[hard(0..100)] + spread: Item, + /// How far the glow reaches past the content's silhouette. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..250)] + #[default(5.)] + size: Item, + /// The share of the glow's strength at which it reaches full opacity, so a lower range makes it denser. + #[unit("%")] + #[range] + #[hard(1..100)] + #[default(50.)] + range: Item, + /// Reshapes how the glow's strength falls off across its size. + contour: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::OuterGlow { + color: color.into_element(), + technique: *technique.element(), + spread: *spread.element(), + size: *size.element(), + range: *range.element(), + contour: contour.into_element(), + }), + ); + content +} diff --git a/node-graph/nodes/blending/src/lib.rs b/node-graph/nodes/blending/src/lib.rs index 406c99d1021..ab030517e89 100644 --- a/node-graph/nodes/blending/src/lib.rs +++ b/node-graph/nodes/blending/src/lib.rs @@ -1,3 +1,5 @@ +pub mod effects; + use core_types::list::Item; use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx}; use graphic_types::Graphic; diff --git a/node-graph/nodes/gcore/src/context.rs b/node-graph/nodes/gcore/src/context.rs index 6076cc79575..44750ada4b0 100644 --- a/node-graph/nodes/gcore/src/context.rs +++ b/node-graph/nodes/gcore/src/context.rs @@ -10,8 +10,6 @@ use raster_types::{CPU, Raster}; pub enum ReadContextError { #[error("No {0} to read: this node only works inside a loop over {0} items, like in a Map node")] NoLoopItem(&'static str), - #[error("No loop index to read: this node only works inside a loop, like in a Repeat or Map node")] - NoLoopIndex, #[error("No position to read: this node only works inside a loop over points, like in a Repeat on Points node")] NoLoopPosition, #[error("Loop Level {level} is too high: the outermost loop around this node is level {outermost}")] @@ -80,6 +78,8 @@ fn read_position( /// Produces the index of the current iteration of a loop by reading from the evaluation context, which is supplied by downstream nodes such as *Repeat*. /// /// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops. +/// +/// Outside of any loop, the index is 0. #[node_macro::node(category("Data: Context"), icon("NodeReadIndex"), path(core_types::vector))] fn read_index( ctx: impl Ctx + ExtractIndex, @@ -90,7 +90,9 @@ fn read_index( #[hard(0..)] loop_level: Item, ) -> Result, ReadContextError> { - let indices = ctx.try_index().ok_or(ReadContextError::NoLoopIndex)?; + // The graph outside any loop runs once, as index 0 + let Some(indices) = ctx.try_index() else { return Ok(Item::new_from_element(0.)) }; + Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64)) } @@ -119,9 +121,14 @@ mod tests { assert_eq!(level(1).unwrap(), 4.); assert_eq!(level(2).unwrap_err().to_string(), "Loop Level 2 is too high: the outermost loop around this node is level 1"); assert!(matches!(level(i64::MAX), Err(ReadContextError::LoopLevelTooHigh { .. }))); + } + + #[test] + fn read_index_outside_a_loop_is_zero() { + let outside = |level: i64| read_index(OwnedContextImpl::default().into_context(), (), Item::new_from_element(level)).map(|index| *index.element()); - let outside = read_index(OwnedContextImpl::default().into_context(), (), Item::new_from_element(0)); - assert!(matches!(outside, Err(ReadContextError::NoLoopIndex))); + assert_eq!(outside(0).unwrap(), 0.); + assert_eq!(outside(3).unwrap(), 0.); } #[test] diff --git a/node-graph/nodes/gcore/src/memo.rs b/node-graph/nodes/gcore/src/memo.rs index d9a33519246..d8496070f13 100644 --- a/node-graph/nodes/gcore/src/memo.rs +++ b/node-graph/nodes/gcore/src/memo.rs @@ -1,7 +1,6 @@ use core_types::graphene_hash::CacheHash; -use core_types::memo::*; use core_types::registry::{DowncastBothNode, DynAnyNode, NODE_REGISTRY, NodeConstructor, PanicNode, TypeErasedBox}; -use core_types::{Context, Interrupt, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type}; +use core_types::{Context, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type}; use dyn_any::StaticType; use std::hash::DefaultHasher; use std::hash::Hasher; @@ -36,39 +35,13 @@ fn memoize(input: I, conten state } -type MonitorValue = Arc>>>>; - -/// The Monitor node is used by the editor to access the data flowing through it. -#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), inspector("monitor_inspector"), skip_impl, forwards_input)] -fn monitor( - input: I, - content: impl Node, - #[allow(clippy::type_complexity)] - #[data] - io: MonitorValue, -) -> Result { - let output = content.eval(input.clone())?; - *io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() })); - Ok(output) -} - -fn serialize_monitor(io: &MonitorValue) -> Option> { - let io = io.lock().unwrap(); - io.as_ref().map(|output| output.clone() as Arc) -} - -/// Registers the Memoize and Monitor implementations for `T`, as `#[derive(node_macro::Destructure)]` does for each multi-output node struct. -pub fn register_memoize_and_monitor + 'static>() { +/// Registers the Memoize implementation for `T`, as `#[derive(node_macro::Destructure)]` does for each multi-output node struct. +pub fn register_memoize + 'static>() { let memoize_constructor: NodeConstructor = |mut arguments| { let node = MemoizeNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); let any: DynAnyNode = DynAnyNode::new(node); Box::new(any) as TypeErasedBox }; - let monitor_constructor: NodeConstructor = |mut arguments| { - let node = MonitorNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); - let any: DynAnyNode = DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }; let memoize_types: NodeIOTypes = { let node = MemoizeNode::new(PanicNode::::new()); @@ -76,16 +49,9 @@ pub fn register_memoize_and_monitor::Static); node_io }; - let monitor_types: NodeIOTypes = { - let node = MonitorNode::new(PanicNode::::new()); - let mut node_io = NodeIO::::to_node_io(&node, vec![fn_type!(Context, T)]); - node_io.call_argument = concrete!(::Static); - node_io - }; let mut registry = NODE_REGISTRY.lock().unwrap(); registry.entry(memoize::IDENTIFIER).or_default().push((memoize_constructor, memoize_types)); - registry.entry(monitor::IDENTIFIER).or_default().push((monitor_constructor, monitor_types)); } #[cfg(test)] diff --git a/node-graph/nodes/graphic/src/graphic.rs b/node-graph/nodes/graphic/src/graphic.rs index ca0fb57e4d0..57b0b879456 100644 --- a/node-graph/nodes/graphic/src/graphic.rs +++ b/node-graph/nodes/graphic/src/graphic.rs @@ -445,6 +445,41 @@ fn map( Ok(rows) } +/// Feeds the content through the same steps over and over, each time starting from the previous result. Inside the steps, a **Read** node like **Read String** or **Read Vector** reads the result so far, and **Read Index** reads how many times around it has been. +#[node_macro::node(category("Routing"), icon("NodeIterate"))] +fn iterate( + ctx: impl Ctx + CloneVarArgs + ExtractAll, + /// The starting value, which the steps rework each time around. + #[implementations(String, f64, Vector, Graphic, Raster, Color, Gradient)] + content: Item, + /// The steps applied each time around, reading the result so far with a **Read** node. + #[expose] + #[implementations( + Context -> Item, + Context -> Item, + Context -> Item, + Context -> Item, + Context -> Item>, + Context -> Item, + Context -> Item, + )] + steps: impl Node, Output = Item>, + /// How many times to apply the steps. Zero passes the content through unchanged. + #[default(1)] + #[hard(0..)] + count: Item, +) -> Result, Interrupt> { + let count = count.into_element().max(0) as usize; + + let mut result = content; + for index in 0..count { + let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(result)).with_index(index); + result = steps.eval(owned_ctx.into_context())?; + } + + Ok(result) +} + #[derive(Debug, thiserror::Error)] pub enum MirrorError { #[error("Text and fills have no bounds to mirror relative to, so set Relative to Bounds to None")] @@ -547,12 +582,7 @@ fn mirror( Ok(result_list) } -/// Returns the path identifying the subgraph (network) that contains this proto node — i.e. the input `node_path` -/// with its own trailing entry dropped. The terminating element of the returned path is the document node whose -/// encapsulated network we live in, so the path doubles as a unique reference to that node at any nesting depth. -/// Used as the value source for stamping the `editor:layer_path` attribute on each item of a layer's output, which lets -/// editor tools (e.g. selection, click target routing) trace data back to its owning layer regardless of whether -/// the layer is at the root document network or nested inside a custom subgraph. +/// Returns this node's `node_path` without its own trailing entry, identifying the document node that holds its network at any nesting depth. #[node_macro::node(name("Path of Subgraph"), category(""))] fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item { let node_path = node_path.into_element().0; @@ -560,6 +590,27 @@ fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item( + _: impl Ctx, + #[implementations(String, bool, f64, i64, DVec2, DAffine2, Vector, Graphic, Raster, Raster, Color, Gradient, Artboard, Stroke)] content: Item, + /// How many entries to drop from the end of this node's path, itself included, to reach the layer or else the network holding it. + levels_up: Item, + /// The layer's ID if the network holding it was reached, which is empty if the layer itself was. + layer_beside: Item, + #[node_path] node_path: Item, +) -> Item { + let node_path = node_path.into_element().0; + let kept = node_path.len().saturating_sub(levels_up.into_element().max(0) as usize); + let layer_path = node_path.into_iter().take(kept).chain(layer_beside.into_element().0).collect(); + + let mut content = content; + content.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path)); + + content +} + /// Sets a named attribute on the input list, computing one value per item via the value-producing input. That input /// is evaluated once per item, with the item's index and the item itself (as a list containing only that item, /// passed as a vararg) provided via context, so the upstream pipeline can return a different value per item that may @@ -607,6 +658,20 @@ fn write_attribute( Ok(content) } +/// Reads a named attribute of a collection type from every item, where **Write Attribute** stores a whole list per item. +/// A stored list contributes all of its items with their own attributes, and a lone value contributes itself. +fn read_collection_attribute(content: &ListDyn, name: &str) -> List { + let mut result = List::with_capacity(content.len()); + for index in 0..content.len() { + if let Some(list) = content.attribute::>(name, index) { + result.extend(list.clone()); + } else if let Some(value) = content.attribute::(name, index) { + result.push(Item::new_from_element(value.clone())); + } + } + result +} + /// Reads a named `Vector` attribute from the input list, outputting each value as an element of a new `Vector[]`. #[node_macro::node(category("Data: Attribute"), icon("NodeReadAttribute"))] fn read_attribute_vector( @@ -616,13 +681,7 @@ fn read_attribute_vector( #[constant] name: Item, ) -> List { - let name = name.into_element(); - let mut result = List::with_capacity(content.len()); - for index in 0..content.len() { - let Some(value) = content.attribute::(&name, index) else { continue }; - result.push(Item::new_from_element(value.clone())); - } - result + read_collection_attribute(&content, &name.into_element()) } /// Reads a named `Number` or `Integer` attribute from the input list, outputting each value as an element of a new `Number[]`. @@ -833,13 +892,7 @@ fn read_attribute_gradient_stops( #[constant] name: Item, ) -> List { - let name = name.into_element(); - let mut result = List::with_capacity(content.len()); - for index in 0..content.len() { - let Some(value) = content.attribute::(&name, index) else { continue }; - result.push(Item::new_from_element(value.clone())); - } - result + read_collection_attribute(&content, &name.into_element()) } /// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `Artboard[]`. @@ -851,13 +904,7 @@ fn read_attribute_artboard( #[constant] name: Item, ) -> List { - let name = name.into_element(); - let mut result = List::with_capacity(content.len()); - for index in 0..content.len() { - let Some(value) = content.attribute::(&name, index) else { continue }; - result.push(Item::new_from_element(value.clone())); - } - result + read_collection_attribute(&content, &name.into_element()) } /// Reads a named `Raster` attribute from the input list, outputting each value as an element of a new `Raster[]`. @@ -869,13 +916,7 @@ fn read_attribute_raster( #[constant] name: Item, ) -> List> { - let name = name.into_element(); - let mut result = List::with_capacity(content.len()); - for index in 0..content.len() { - let Some(value) = content.attribute::>(&name, index) else { continue }; - result.push(Item::new_from_element(value.clone())); - } - result + read_collection_attribute(&content, &name.into_element()) } /// Joins two lists of the same type, extending the base list with the items from the new list. @@ -938,7 +979,7 @@ fn legacy_layer_extend( new: List, nested_node_path: Item, ) -> List { - // Drop this internal node's own trailing entry so the stamped path ends at the user-facing parent layer-style node (which encapsulates it) + // Drop this internal node's own trailing entry so the written path ends at the user-facing parent layer-style node (which encapsulates it) let nested_node_path = nested_node_path.into_element().0; let layer_path = { let len = nested_node_path.len(); @@ -956,7 +997,7 @@ fn legacy_layer_extend( /// Nests the input graphical content in a wrapper graphic, collecting it all into a single group. /// The inverse of this node is 'Flatten Graphic'. -#[node_macro::node(category("Graphic"), icon("NodeIntoGroup"))] +#[node_macro::node(category("Graphic"), icon("NodeGroup"))] fn into_group>( _: impl Ctx, #[implementations( @@ -984,7 +1025,7 @@ fn as_graphic(_: impl Ctx, value: Item) -> Item { } /// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled. -#[node_macro::node(category("Graphic"), icon("NodeFlattenGraphic"))] +#[node_macro::node(category("Graphic"), icon("NodeUngroup"))] fn flatten_graphic(_: impl Ctx, content: List, fully_flatten: Item) -> List { let fully_flatten = fully_flatten.into_element(); @@ -1033,12 +1074,12 @@ fn flatten_graphic(_: impl Ctx, content: List, fully_flatten: Item) -> List { let mut output: List = content.clone().into_flattened_list(); - // TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node. + // TODO: Replace this snapshot hack with per-layer metadata driven by observing each layer's content. // TODO: Flattening here erases the upstream `List` hierarchy that editor metadata collection walks // TODO: to populate `upstream_footprints` / `local_transforms` / `click_targets` per child layer. As a workaround // TODO: we stash the pre-flattened list on the output so `List::collect_metadata` can recurse into it, // TODO: which conflates render output with editor metadata and forces the pre-compensation dance below. - // TODO: The cleaner fix is to drive each layer's metadata from its own Monitor's captured `(Context, List)`, + // TODO: The cleaner fix is to drive each layer's metadata from an observation of its `List` content and context, // TODO: at which point this attribute (and the equivalents in Boolean Operation, Solidify Stroke, Combine Paths, // TODO: Morph, Rasterize) become unnecessary. if !output.is_empty() && !is_lone_anonymous_leaf(&content) { @@ -1121,6 +1162,36 @@ mod test { elements.into_iter().map(Item::new_from_element).collect() } + /// Appends the loop index to the string read from the context, the way a Read String node reads it. + #[derive(Clone)] + struct AppendIndexNode; + + impl core_types::Node for AppendIndexNode { + type Output = Item; + + fn eval(&self, input: &I) -> core_types::Poll> { + let so_far = input + .vararg(0) + .ok() + .and_then(|value| (value as &dyn std::any::Any).downcast_ref::>().map(|item| item.element().clone())); + let index = input.try_index().and_then(|mut indices| indices.next()); + core_types::Poll::Final(Item::new_from_element(format!("{}{}", so_far.unwrap_or_default(), index.unwrap_or_default()))) + } + } + + #[test] + fn iterate_feeds_each_result_into_the_next_time_around() { + let status = core_types::Status::new(); + let iterated = |count: i64| { + let steps = core_types::LazyInput::new(&AppendIndexNode, &status, 1); + let start = Item::new_from_element("x".to_string()); + iterate(OwnedContextImpl::default().into_context(), start, steps, Item::new_from_element(count)).unwrap().into_element() + }; + + assert_eq!(iterated(0), "x"); + assert_eq!(iterated(3), "x012"); + } + /// Stands in for the embedding adapter a compiled graph inserts ahead of a `List` connector. fn embed_colors(colors: List) -> List { colors.into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect() @@ -1130,6 +1201,30 @@ mod test { list.iter_element_values().cloned().collect() } + #[test] + fn reads_every_item_of_a_stored_vector_list_with_its_attributes() { + let placement = DAffine2::from_translation(DVec2::new(3., 4.)); + let shapes: List = [placement, DAffine2::IDENTITY] + .into_iter() + .map(|transform| Item::new_from_element(Vector::default()).with_attribute(ATTR_TRANSFORM, transform)) + .collect(); + let content: List = Item::new_from_element(0.).with_attribute("shapes", shapes).into(); + + let read = read_attribute_vector((), content.into(), Item::new_from_element("shapes".to_string())); + + assert_eq!(read.len(), 2); + assert_eq!(read.attribute::(ATTR_TRANSFORM, 0), Some(&placement)); + } + + #[test] + fn reads_a_lone_gradient_attribute() { + let content: List = Item::new_from_element(0.).with_attribute("ramp", Gradient::default()).into(); + + let read = read_attribute_gradient_stops((), content.into(), Item::new_from_element("ramp".to_string())); + + assert_eq!(read.len(), 1); + } + #[test] fn sorts_elements_by_their_natural_order() { let list = list_of(["banana".to_string(), "apple".to_string(), "cherry".to_string()]); diff --git a/node-graph/nodes/gstd/Cargo.toml b/node-graph/nodes/gstd/Cargo.toml index 28b7d967b9c..332f3651b00 100644 --- a/node-graph/nodes/gstd/Cargo.toml +++ b/node-graph/nodes/gstd/Cargo.toml @@ -45,6 +45,7 @@ wgpu-executor = { workspace = true } core-types = { workspace = true } vector-types = { workspace = true } graphic-types = { workspace = true } +raster-kernels = { workspace = true } blending-nodes = { workspace = true } text-nodes = { workspace = true } transform-nodes = { workspace = true } diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index 422267f438c..3f4c4e6658c 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -13,7 +13,7 @@ pub use graphene_application_io as application_io; pub use graphene_core; pub use graphene_core::debug; pub use graphic_nodes; -pub use graphic_types::{Appearance, Artboard, Cover, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage}; +pub use graphic_types::{Appearance, Artboard, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowTechnique, Graphic, Vector, stamp_coverage}; pub use math_nodes; pub use path_bool_nodes; pub use raster_nodes; diff --git a/node-graph/nodes/gstd/src/platform_application_io.rs b/node-graph/nodes/gstd/src/platform_application_io.rs index d2a85f7188e..c9778594c0d 100644 --- a/node-graph/nodes/gstd/src/platform_application_io.rs +++ b/node-graph/nodes/gstd/src/platform_application_io.rs @@ -173,7 +173,7 @@ fn string_to_bytes(_: impl Ctx, string: Item) -> Item { /// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files. #[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))] fn image_to_bytes(_: impl Ctx, image: Item>) -> Item { - let bytes: Vec = image + let bytes: Vec = raster_kernels::evaluate_raster_effects(image) .element() .data .iter() @@ -218,11 +218,14 @@ fn bytes_to_image(_: impl Ctx, data: Item) -> Result> Ok(Item::new_from_element(Raster::new_cpu(image))) } -/// Renders a view of the input graphic within an area defined by the *Footprint*. -#[node_macro::node(category(""), placeholder = pending_raster)] +/// Renders a view of the input graphics within an area defined by the *Footprint*, producing a raster image. +#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster)] async fn rasterize( _: impl Ctx, + /// The graphics to render as an image. data: List, + /// The area of the document to render, and the resolution to render it at. + #[default(0., 0., 1000., 1000.)] footprint: Item, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>, ) -> Result>, NodeError> { @@ -278,21 +281,28 @@ fn application_io(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item #[error("Resource {0} was not found")] pub struct ResourceError(ResourceHash); -#[node_macro::node(category(""), placeholder = pending_stored_resource)] +#[node_macro::node(category(""), version(2), placeholder = pending_stored_resource)] async fn resource( _: impl Ctx, + /// The content hash identifying which stored resource to load. + hash: Item, /// The scope-provided application IO giving access to the platform's resource storage. #[scope(application_io::IDENTIFIER)] application_io: Item>, - /// The content hash identifying which stored resource to load. - hash: Item, ) -> Result, ResourceError> { let hash = hash.into_element(); + + // The empty resource needs no storage, and stands in for one the document can't find so its consumers draw a fallback + let empty = Resource::empty(); + if hash == empty.hash() { + return Ok(Item::new_from_element(empty)); + } + let resource = application_io.element().load_resource(hash).await.ok_or(ResourceError(hash))?; Ok(Item::new_from_element(resource)) } -fn pending_stored_resource(_application_io: &Item>, _hash: &Item) -> Item { +fn pending_stored_resource(_hash: &Item, _application_io: &Item>) -> Item { Item::new_from_element(Resource::empty()) } diff --git a/node-graph/nodes/gstd/src/render_background.rs b/node-graph/nodes/gstd/src/render_background.rs index 52ca59a2f79..527d5a9fa6c 100644 --- a/node-graph/nodes/gstd/src/render_background.rs +++ b/node-graph/nodes/gstd/src/render_background.rs @@ -11,11 +11,11 @@ use rendering::{RenderParams, SvgRender, SvgRenderOutput}; use std::fmt::Write; use wgpu_executor::{Buffer, WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; -#[node_macro::node(category(""))] +#[node_macro::node(category(""), version(2))] fn render_background( ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, - #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: impl Node, Output = Item>, data: Item, + #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: impl Node, Output = Item>, ) -> Result, Interrupt> { let footprint = ctx.footprint(); let render_params = ctx @@ -51,6 +51,7 @@ fn render_background( RenderOutputType::Svg { svg: foreground_svg, image_data: foreground_images, + effect_maps, } => { let mut render = SvgRender::new(); @@ -114,7 +115,7 @@ fn render_background( let svg = format!("{}{}", background.svg, foreground_svg); let image_data = foreground_images; - RenderOutputType::Svg { svg, image_data } + RenderOutputType::Svg { svg, image_data, effect_maps } } _ => unreachable!("Render background node received unsupported render output type"), }; diff --git a/node-graph/nodes/gstd/src/render_cache.rs b/node-graph/nodes/gstd/src/render_cache.rs index 845db394aca..38587bfd780 100644 --- a/node-graph/nodes/gstd/src/render_cache.rs +++ b/node-graph/nodes/gstd/src/render_cache.rs @@ -317,11 +317,11 @@ fn split_oversized_region(region: RenderRegion, max_region_size: u32) -> Vec, Output = Item>, data: impl Node, Output = Item> + Send + Sync, + #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node, Output = Item>, #[data] tile_cache: TileCache, ) -> Poll> { let footprint = ctx.footprint(); diff --git a/node-graph/nodes/gstd/src/render_node.rs b/node-graph/nodes/gstd/src/render_node.rs index 5b8bc811593..65f53be2797 100644 --- a/node-graph/nodes/gstd/src/render_node.rs +++ b/node-graph/nodes/gstd/src/render_node.rs @@ -70,11 +70,11 @@ fn render_intermediate( Ok(Item::new_from_element(intermediate)) } -#[node_macro::node(category(""))] +#[node_macro::node(category(""), version(2))] fn render( ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, - #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node, Output = Item>, data: Item, + #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node, Output = Item>, ) -> Result, Interrupt> { let footprint = ctx.footprint(); let render_params = ctx @@ -99,9 +99,19 @@ fn render( let output = SvgRenderOutput::from(render); assert!(output.svg_defs.is_empty()); + // Without a GPU, the filters' maps keep their placeholders, which leave those effects out + let effect_maps = match output.effect_maps.is_empty() { + true => Vec::new(), + false => match executor.eval(Context::default()) { + Ok(executor) => executor.element().render_effect_maps(&output.effect_maps, *footprint), + Err(_) => Vec::new(), + }, + }; + RenderOutputType::Svg { svg: output.svg, image_data: output.image_data.into_iter().collect(), + effect_maps, } } (RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => { diff --git a/node-graph/nodes/gstd/src/render_pixel_preview.rs b/node-graph/nodes/gstd/src/render_pixel_preview.rs index 00648a60a3c..b3e629e68dd 100644 --- a/node-graph/nodes/gstd/src/render_pixel_preview.rs +++ b/node-graph/nodes/gstd/src/render_pixel_preview.rs @@ -8,11 +8,11 @@ use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams}; use vector_types::vector::style::RenderMode; use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; -#[node_macro::node(category(""))] +#[node_macro::node(category(""), version(2))] fn render_pixel_preview( ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, - #[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: impl Node, Output = Item>, data: impl Node, Output = Item> + Send + Sync, + #[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: impl Node, Output = Item>, ) -> Result, Interrupt> { let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::()).cloned() else { log::error!("invalid render params for pixel preview"); diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 593f7f9d93c..7b8d375c184 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -13,13 +13,13 @@ use math_parser::lexer::Constant; use math_parser::matrix::{Affine2, Linear2, Matrix}; use math_parser::object::Object; use math_parser::parser::{MessagePart, ParseError}; -use math_parser::reducer::classify_reducer; +use math_parser::reducer::{Reducer, classify_reducer}; use math_parser::value::{Value, Vector2, Vector3}; -use rand::{Rng, SeedableRng}; +use rand::{RngExt, SeedableRng}; use std::sync::{Arc, Mutex, PoisonError}; use vector_types::Gradient; -/// Why the "Math f(x)" or "Math f(…)" node's expression gives no result. +/// Why a math node's expression or operator gives no result. #[derive(Debug, thiserror::Error)] pub enum MathExpressionError { #[error("The expression is empty")] @@ -32,6 +32,10 @@ pub enum MathExpressionError { OutputType { result: String, output_type: String }, #[error("The input can't be read as {0}")] InputType(String), + #[error("`{0}` alone is an operator, which the Math Aggregate node applies across all the items")] + LoneOperator(String), + #[error("The operator must be a lone operator or function name, like `+` or `max`")] + NotAnOperator, #[error("`{reducer}` gives no result for an empty list")] EmptyReduction { reducer: String }, #[error("`{reducer}` gives no result across these items")] @@ -95,7 +99,7 @@ trait ExpressionValue: Copy + Default + 'static { fn items(items: impl Iterator) -> Items; } -/// The items of the "Math f(…)" node's list, of one sort throughout, bound positionally as `a`, `b`, `c` or as `A`, `B`, `C`. +/// The items of a math node's list, of one sort throughout, which "Math Formula" binds positionally as `a`, `b`, `c` or as `A`, `B`, `C`. enum Items { Values(Vec), Matrices(Vec), @@ -212,7 +216,7 @@ impl ExpressionValue for DAffine2 { } } -/// Supplies the value of `x`, or the matrix of `X`, for the "Math f(x)" node's expression. +/// Supplies the value of `x`, or the matrix of `X`, for the "Math Function" node's expression. struct SingleVariableMathContext<'a> { x: &'a Object, } @@ -228,11 +232,11 @@ impl ValueProvider for SingleVariableMathContext<'_> { } } -/// Evaluates a math expression written in terms of the single variable `x`, which carries the input value, or `X` when the input is a Transform. +/// Maps a value through a math expression written as a function of `x`, which stands for the value, or of `X` when it's a Transform. Each item of a list is mapped on its own. /// /// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. A boolean input reads as 0 or 1 and a Vec2 input as such a vector. -#[node_macro::node(name("Math f(x)"), category("Math"), icon("NodeMathFx"))] -fn math_fx( +#[node_macro::node(category("Math"), icon("NodeMathFunction"), version(2))] +fn math_function( _: impl Ctx, /// The value passed into the expression as `x`. #[implementations( @@ -277,7 +281,7 @@ fn math_fx( } } -/// Binds the items of the "Math f(…)" node's list to the positional variables `a`, `b`, `c`, and so on, or `A`, `B`, `C` for matrices. +/// Binds the items of the "Math Formula" node's list to the positional variables `a`, `b`, `c`, and so on, or `A`, `B`, `C` for matrices. struct PositionalMathContext { items: Items, } @@ -310,11 +314,11 @@ impl ValueProvider for PositionalMathContext { } } -/// Evaluates a math expression across all of the input items at once. A full expression reads the items as `a`, `b`, `c`, …, or as `A`, `B`, `C`, … for Transforms, while a math operator or N-argument function name (like `*` or `min`) applies across every item. +/// Evaluates one math expression over all the items, taking them in order as its arguments `a`, `b`, `c`, …, or `A`, `B`, `C`, … for Transforms. /// -/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts. -#[node_macro::node(name("Math f(…)"), category("Math"), icon("NodeMathF"))] -fn math_f( +/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. +#[node_macro::node(category("Math"), icon("NodeMathFormula"), version(2))] +fn math_formula( _: impl Ctx, /// The items the expression reads. #[implementations( @@ -325,9 +329,9 @@ fn math_f( List, List, List, List, List, )] values: List, - /// The expression evaluated over the items, such as `a * b + c`, or a lone operator or function applied across all of them. + /// The expression evaluated over the items, such as `a * b + c`. #[name("f(…) =")] - #[widget(ParsedWidgetOverride::Custom = "math_expression_or_reducer")] + #[widget(ParsedWidgetOverride::Custom = "math_expression")] f: Item, /// The type the result is read as. #[implementations( @@ -342,33 +346,133 @@ fn math_f( let _ = output_type; let expression = f.element(); + if classify_reducer(expression, NothingMap).is_some() { + return Err(MathExpressionError::LoneOperator(expression.trim().to_string())); + } + let bindings = PositionalMathContext { items: T::items(values.iter_element_values().copied()), }; - - // A lone operator or variadic function name applies across all items rather than parsing as an expression - if let Some(reducer) = classify_reducer(expression, &bindings) { - let result = match &bindings.items { - Items::Values(values) => reducer.evaluate(values).map(Object::Value), - Items::Matrices(matrices) => reducer.evaluate_matrices(matrices), - }; - let Some(result) = result else { - let name = expression.trim(); - return match bindings.items.len() { - // Like the dedicated nodes, the minimum, maximum and mean of no values are 0 - 0 if matches!(bindings.items, Items::Values(_)) && matches!(name.trim_start_matches('\\'), "min" | "max" | "mean") => Ok(Item::new_from_element(U::default())), - 0 => Err(MathExpressionError::EmptyReduction { reducer: name.to_string() }), - _ => Err(MathExpressionError::NoReduction { reducer: name.to_string() }), - }; - }; - return Ok(Item::new_from_element(output(&result)?)); - } - let tree = parsed.parse(expression)?; let result = evaluate_expression(&tree, bindings)?; Ok(Item::new_from_element(output(&result)?)) } +/// The operator or function name a "Math Aggregate" or "Math Running" node applies across its items. +fn operator_reducer(operator: &str) -> Result { + classify_reducer(operator, NothingMap).ok_or(MathExpressionError::NotAnOperator) +} + +/// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`. +/// +/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts. +#[node_macro::node(category("Math"), icon("NodeMathAggregate"))] +fn math_aggregate( + _: impl Ctx, + /// The items reduced to one value. + #[implementations( + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + )] + values: List, + /// The operator folded across the items, like `+` or `*`, or a function given all of them, like `max` or `mean`. + #[default("+")] + #[widget(ParsedWidgetOverride::Custom = "math_operator")] + operator: Item, + /// The type the result is read as. + #[implementations( + f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2 + )] + #[widget(ParsedWidgetOverride::Custom = "type_choice")] + #[name("Output Type")] + output_type: Item, +) -> Result, MathExpressionError> { + // The output type input is a type witness: its type selects the implementation, and its value is never read + let _ = output_type; + + let operator = operator.element(); + let reducer = operator_reducer(operator)?; + let items = T::items(values.iter_element_values().copied()); + + let result = match &items { + Items::Values(values) => reducer.evaluate(values).map(Object::Value), + Items::Matrices(matrices) => reducer.evaluate_matrices(matrices), + }; + let Some(result) = result else { + let name = operator.trim(); + return match items.len() { + // Like the dedicated nodes, the minimum, maximum and mean of no values are 0 + 0 if matches!(items, Items::Values(_)) && matches!(name.trim_start_matches('\\'), "min" | "max" | "mean") => Ok(Item::new_from_element(U::default())), + 0 => Err(MathExpressionError::EmptyReduction { reducer: name.to_string() }), + _ => Err(MathExpressionError::NoReduction { reducer: name.to_string() }), + }; + }; + Ok(Item::new_from_element(output(&result)?)) +} + +/// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far. +/// +/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up. +#[node_macro::node(category("Math"), icon("NodeMathRunning"))] +fn math_running( + _: impl Ctx, + /// The items scanned along, each giving one result. + #[implementations( + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + )] + values: List, + /// The operator folded along the items, like `+` or `*`, or a function given the items so far, like `max` or `mean`. + #[default("+")] + #[widget(ParsedWidgetOverride::Custom = "math_operator")] + operator: Item, + /// The type each result is read as. + #[implementations( + f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2 + )] + #[widget(ParsedWidgetOverride::Custom = "type_choice")] + #[name("Output Type")] + output_type: Item, +) -> Result, (List, MathExpressionError)> { + // The output type input is a type witness: its type selects the implementation, and its value is never read + let _ = output_type; + + let operator = operator.element(); + let reducer = match operator_reducer(operator) { + Ok(reducer) => reducer, + Err(error) => return Err((values.into_iter().map(|item| Item::from_parts(U::default(), item.into_parts().1)).collect(), error)), + }; + + // Each item's run is folded on from the run before it, where a failed fold fails every run after it + let items = T::items(values.iter_element_values().copied()); + let running = match &items { + Items::Values(values) => reducer.evaluate_running(values).into_iter().map(|result| result.map(Object::Value)).collect(), + Items::Matrices(matrices) => reducer.evaluate_running_matrices(matrices), + }; + + // A failing item takes the default, and the first failure is the one reported + let mut first_error = None; + let results = running.into_iter().map(|result| { + let no_reduction = || MathExpressionError::NoReduction { reducer: operator.trim().to_string() }; + result.ok_or_else(no_reduction).and_then(|result| output(&result)).unwrap_or_else(|error| { + first_error.get_or_insert(error); + U::default() + }) + }); + let list = values.into_iter().zip(results).map(|(item, result)| Item::from_parts(result, item.into_parts().1)).collect(); + + match first_error { + Some(error) => Err((list, error)), + None => Ok(list), + } +} + /// An Integer result too large or too small for the Integer type to hold. #[derive(Debug, thiserror::Error)] pub enum IntegerOverflowError { @@ -2301,7 +2405,7 @@ mod test { #[test] fn integer_lane_keeps_integers_and_rounds_fractions() { let integer = |value: i64, expression: &str| { - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(value), @@ -2318,7 +2422,7 @@ mod test { let items: List = [1_i64, 2, 4].into_iter().map(Item::new_from_element).collect(); assert_eq!( - math_f((), &ParseCache::default(), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)) + math_aggregate((), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)) .unwrap() .into_element(), 2, @@ -2330,7 +2434,7 @@ mod test { fn output_type_witness_picks_the_output_rung() { // The witness input's type, not the input value's, decides how the result is read assert_eq!( - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(2.5), @@ -2342,7 +2446,7 @@ mod test { 5 ); assert!( - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(3_i64), @@ -2353,7 +2457,7 @@ mod test { .into_element() ); assert_eq!( - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(true), @@ -2367,7 +2471,7 @@ mod test { let items: List = [1., 2.].into_iter().map(Item::new_from_element).collect(); assert_eq!( - math_f((), &ParseCache::default(), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)) + math_aggregate((), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)) .unwrap() .into_element(), 2, @@ -2385,7 +2489,7 @@ mod test { #[test] fn test_basic_expression() { - let result = math_fx( + let result = math_function( (), &ParseCache::default(), Item::new_from_element(0.), @@ -2397,7 +2501,7 @@ mod test { #[test] fn test_complex_expression() { - let result = math_fx( + let result = math_function( (), &ParseCache::default(), Item::new_from_element(0.), @@ -2409,7 +2513,7 @@ mod test { #[test] fn test_variable_binding() { - let result = math_fx( + let result = math_function( (), &ParseCache::default(), Item::new_from_element(7.), @@ -2421,7 +2525,7 @@ mod test { #[test] fn test_invalid_expression() { - let result = math_fx( + let result = math_function( (), &ParseCache::default(), Item::new_from_element(0.), @@ -2445,44 +2549,36 @@ mod test { // Booleans read as exactly 0 and 1, and logical results convert back let as_bool = Item::new_from_element(false); assert!( - !math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string()), as_bool.clone()) + !math_function((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string()), as_bool.clone()) .unwrap() .into_element() ); assert!( - math_fx((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string()), as_bool.clone()) + math_function((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string()), as_bool.clone()) .unwrap() .into_element() ); // A result that is not exactly 0 or 1 cannot be a truth value, so the input passes through - let (stand_in, error) = math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err(); + let (stand_in, error) = math_function((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err(); assert!(stand_in.into_element()); assert!(matches!(&error, MathExpressionError::OutputType { output_type, .. } if output_type == "Bool")); // An input that is not exactly 0 or 1 cannot pass through as a truth value either, so the output falls back to false - let (stand_in, error) = math_fx((), &ParseCache::default(), Item::new_from_element(2.), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err(); + let (stand_in, error) = math_function((), &ParseCache::default(), Item::new_from_element(2.), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err(); assert!(!stand_in.into_element()); assert!(matches!(&error, MathExpressionError::InputType(output_type) if output_type == "Bool")); let bools = || [true, true, false].into_iter().map(Item::new_from_element).collect::>(); - assert!( - !math_f((), &ParseCache::default(), bools(), Item::new_from_element("&&".to_string()), as_bool.clone()) - .unwrap() - .into_element() - ); - assert!( - math_f((), &ParseCache::default(), bools(), Item::new_from_element("||".to_string()), as_bool.clone()) - .unwrap() - .into_element() - ); - assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("xor".to_string()), as_bool).unwrap().into_element()); + assert!(!math_aggregate((), bools(), Item::new_from_element("&&".to_string()), as_bool.clone()).unwrap().into_element()); + assert!(math_aggregate((), bools(), Item::new_from_element("||".to_string()), as_bool.clone()).unwrap().into_element()); + assert!(!math_aggregate((), bools(), Item::new_from_element("xor".to_string()), as_bool).unwrap().into_element()); } #[test] fn test_transform_items() { fn fx(value: T, expression: &str, output_type: U) -> Result { - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(value), @@ -2512,25 +2608,28 @@ mod test { // A Transform can't pass through as a Number, so the output falls back to its default assert_eq!(fx(shear, "x", 0.), Err(0.)); - // A Transform list binds as `A`, `B`, `C`, and a lone operator composes, averages, or counts across it + // A Transform list binds as `A`, `B`, `C` in a formula, and an operator composes, averages, or counts across it let scale = DAffine2::from_scale(DVec2::splat(2.)); - fn f(items: [DAffine2; 2], expression: &str, output_type: U) -> Result { - let items: List = items.into_iter().map(Item::new_from_element).collect(); - math_f((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)).map(Item::into_element) + let items = || [shear, scale].into_iter().map(Item::new_from_element).collect::>(); + fn formula(items: List, expression: &str, output_type: U) -> Result { + math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)).map(Item::into_element) + } + fn aggregate(items: List, operator: &str, output_type: U) -> Result { + math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(output_type)).map(Item::into_element) } - assert_eq!(f([shear, scale], "A B", DAffine2::IDENTITY).unwrap(), shear * scale); - assert_eq!(f([shear, scale], "A C", DAffine2::IDENTITY).unwrap(), shear); - assert_eq!(f([shear, scale], "*", DAffine2::IDENTITY).unwrap(), shear * scale); - assert_eq!(f([shear, scale], "/", DAffine2::IDENTITY).unwrap(), shear * scale.inverse()); - assert_eq!(f([shear, scale], "mean", DAffine2::IDENTITY).unwrap().translation, DVec2::new(2.5, 2.)); - assert_eq!(f([shear, scale], "count", 0.).unwrap(), 2.); - assert_eq!(f([shear, scale], "det(A)", 0.).unwrap(), 1.); - assert!(matches!(f([shear, scale], "min", DAffine2::IDENTITY), Err(MathExpressionError::NoReduction { .. }))); - assert!(f([shear, scale], "a", DAffine2::IDENTITY).is_err()); + assert_eq!(formula(items(), "A B", DAffine2::IDENTITY).unwrap(), shear * scale); + assert_eq!(formula(items(), "A C", DAffine2::IDENTITY).unwrap(), shear); + assert_eq!(aggregate(items(), "*", DAffine2::IDENTITY).unwrap(), shear * scale); + assert_eq!(aggregate(items(), "/", DAffine2::IDENTITY).unwrap(), shear * scale.inverse()); + assert_eq!(aggregate(items(), "mean", DAffine2::IDENTITY).unwrap().translation, DVec2::new(2.5, 2.)); + assert_eq!(aggregate(items(), "count", 0.).unwrap(), 2.); + assert_eq!(formula(items(), "det(A)", 0.).unwrap(), 1.); + assert!(matches!(aggregate(items(), "min", DAffine2::IDENTITY), Err(MathExpressionError::NoReduction { .. }))); + assert!(formula(items(), "a", DAffine2::IDENTITY).is_err()); // A sum of Transforms doubles the weight row, so it reads as no Transform assert!(matches!( - f([shear, scale], "+", DAffine2::IDENTITY), + aggregate(items(), "+", DAffine2::IDENTITY), Err(MathExpressionError::OutputType { output_type, .. }) if output_type == "Transform" )); } @@ -2538,7 +2637,7 @@ mod test { #[test] fn test_vec2_items() { fn fx(value: T, expression: &str, output_type: U) -> U { - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(value), @@ -2548,9 +2647,14 @@ mod test { .unwrap_or_else(|(_, error)| panic!("`{expression}` fails: {error}")) .into_element() } - fn f(expression: &str, output_type: U) -> U { - let items: List = [DVec2::new(1., 5.), DVec2::new(3., 2.)].into_iter().map(Item::new_from_element).collect(); - math_f((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)) + let items = || [DVec2::new(1., 5.), DVec2::new(3., 2.)].into_iter().map(Item::new_from_element).collect::>(); + fn formula(items: List, expression: &str, output_type: U) -> U { + math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)) + .unwrap() + .into_element() + } + fn aggregate(items: List, operator: &str, output_type: U) -> U { + math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(output_type)) .unwrap() .into_element() } @@ -2567,10 +2671,10 @@ mod test { assert_eq!(fx(DVec2::new(3., 4.), "x + 2.6", 0_i64), 3); assert!(fx(DVec2::new(3., 4.), "x + 1", false)); - assert_eq!(f("+", DVec2::ZERO), DVec2::new(4., 7.)); - assert_eq!(f("min", DVec2::ZERO), DVec2::new(1., 2.)); - assert_eq!(f("a - b", DVec2::ZERO), DVec2::new(-2., 3.)); - assert_eq!(f("dot(a, b)", 0.), 13.); + assert_eq!(aggregate(items(), "+", DVec2::ZERO), DVec2::new(4., 7.)); + assert_eq!(aggregate(items(), "min", DVec2::ZERO), DVec2::new(1., 2.)); + assert_eq!(formula(items(), "a - b", DVec2::ZERO), DVec2::new(-2., 3.)); + assert_eq!(formula(items(), "dot(a, b)", 0.), 13.); } #[test] @@ -2587,27 +2691,74 @@ mod test { } #[test] - fn test_positional_and_reducer_expressions() { + fn formula_reads_positions_and_aggregate_folds_operators() { let values = || [4., 1., 7.].into_iter().map(Item::new_from_element).collect::>(); + let formula = |expression: &str| math_formula((), &ParseCache::default(), values(), Item::new_from_element(expression.to_string()), Item::new_from_element(0.)).map(Item::into_element); + let aggregate = |operator: &str| math_aggregate((), values(), Item::new_from_element(operator.to_string()), Item::new_from_element(0.)).map(Item::into_element); - // A full expression reads the items positionally as `a`, `b`, `c`, while a lone token applies across all of them - let as_number = Item::new_from_element(0.); - assert_eq!( - math_f((), &ParseCache::default(), values(), Item::new_from_element("a - b + c".to_string()), as_number.clone()) - .unwrap() - .into_element(), - 10. - ); - assert_eq!( - math_f((), &ParseCache::default(), values(), Item::new_from_element("min".to_string()), as_number.clone()) - .unwrap() - .into_element(), - 1. - ); + // A formula reads the items positionally as `a`, `b`, `c`, while an aggregate applies its operator across all of them + assert_eq!(formula("a - b + c").unwrap(), 10.); + assert_eq!(aggregate("min").unwrap(), 1.); + assert_eq!(aggregate("+").unwrap(), 12.); + + // Each node takes only its own kind of string + assert!(matches!(formula(" + "), Err(MathExpressionError::LoneOperator(operator)) if operator == "+")); + assert!(matches!(formula("max"), Err(MathExpressionError::LoneOperator(_)))); + assert!(matches!(aggregate("a + b"), Err(MathExpressionError::NotAnOperator))); + assert!(matches!(aggregate(""), Err(MathExpressionError::NotAnOperator))); + } + + #[test] + fn running_results_follow_each_item() { + let numbers = |values: &[f64]| values.iter().copied().map(Item::new_from_element).collect::>(); + let running = |items: List, operator: &str| { + math_running((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(0.)) + .map(|list| list.iter_element_values().copied().collect::>()) + .map_err(|(_, error)| error) + }; + + // Each item gets the fold of it and those before it, like a running total or the highest value so far + assert_eq!(running(numbers(&[3., 1., 4., 1., 5.]), "+").unwrap(), [3., 4., 8., 9., 14.]); + assert_eq!(running(numbers(&[3., 1., 4., 1., 5.]), "max").unwrap(), [3., 3., 4., 4., 5.]); + assert_eq!(running(numbers(&[]), "-").unwrap(), Vec::::new()); + assert!(matches!(running(numbers(&[1., 2.]), "a + b"), Err(MathExpressionError::NotAnOperator))); + + let increasing = math_running((), numbers(&[1., 2., 5., 4., 6.]), Item::new_from_element("<".to_string()), Item::new_from_element(false)).unwrap(); + assert_eq!(increasing.iter_element_values().copied().collect::>(), [true, true, true, false, false]); + } + + #[test] + fn running_results_keep_attributes_and_fail_only_where_they_fail() { + let items = [1., 2., 3.] + .into_iter() + .map(|value| Item::new_from_element(value).with_attribute("weight", value * 10.)) + .collect::>(); + let totals = math_running((), items, Item::new_from_element("+".to_string()), Item::new_from_element(0.)).unwrap(); + assert_eq!(totals.iter_element_values().copied().collect::>(), [1., 3., 6.]); assert_eq!( - math_f((), &ParseCache::default(), values(), Item::new_from_element("+".to_string()), as_number).unwrap().into_element(), - 12. + (0..3).map(|index| totals.attribute::("weight", index).copied()).collect::>(), + [Some(10.), Some(20.), Some(30.)] ); + + // Only the running total 2 can't be read as a Bool, so it alone takes the default + let items = [0., 1., 1., -1.].into_iter().map(Item::new_from_element).collect::>(); + let (stand_in, error) = math_running((), items, Item::new_from_element("+".to_string()), Item::new_from_element(false)).unwrap_err(); + assert_eq!(stand_in.iter_element_values().copied().collect::>(), [false, true, false, true]); + assert!(matches!(error, MathExpressionError::OutputType { .. })); + } + + #[test] + fn running_transform_products_place_each_step() { + // Each step turns in place and then moves forward in its own direction, so the running product is where each step ends up + let forward = DAffine2::from_translation(DVec2::X); + let turn_then_forward = DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * forward; + let steps = [forward, turn_then_forward, turn_then_forward].into_iter().map(Item::new_from_element).collect::>(); + + let placed = math_running((), steps, Item::new_from_element("*".to_string()), Item::new_from_element(DAffine2::IDENTITY)).unwrap(); + let translations = placed.iter_element_values().map(|transform| transform.translation).collect::>(); + for (translation, expected) in translations.into_iter().zip([DVec2::new(1., 0.), DVec2::new(1., 1.), DVec2::new(0., 1.)]) { + assert!(translation.abs_diff_eq(expected, 1e-12), "{translation} is not {expected}"); + } } #[test] @@ -2671,7 +2822,7 @@ mod test { ); let fx = |value: f64, expression: &str| { - math_fx( + math_function( (), &ParseCache::default(), Item::new_from_element(value), @@ -2689,13 +2840,14 @@ mod test { assert!(!message.contains(", at "), "{message}"); let values = |values: &[f64]| values.iter().copied().map(Item::new_from_element).collect::>(); - let f = |items, expression: &str| math_f((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(0.)).map(Item::into_element); - assert!(matches!(f(values(&[1.]), ""), Err(MathExpressionError::Empty))); - assert!(matches!(f(values(&[1.]), "a +"), Err(MathExpressionError::Invalid(_)))); - assert_eq!(f(values(&[]), "min").unwrap(), 0.); - assert_eq!(f(values(&[]), "mean").unwrap(), 0.); - assert!(matches!(f(values(&[]), "-"), Err(MathExpressionError::EmptyReduction { .. }))); - assert!(matches!(f(values(&[0., 0.]), "/"), Err(MathExpressionError::NoReduction { .. }))); + let formula = |items, expression: &str| math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(0.)).map(Item::into_element); + let aggregate = |items, operator: &str| math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(0.)).map(Item::into_element); + assert!(matches!(formula(values(&[1.]), ""), Err(MathExpressionError::Empty))); + assert!(matches!(formula(values(&[1.]), "a +"), Err(MathExpressionError::Invalid(_)))); + assert_eq!(aggregate(values(&[]), "min").unwrap(), 0.); + assert_eq!(aggregate(values(&[]), "mean").unwrap(), 0.); + assert!(matches!(aggregate(values(&[]), "-"), Err(MathExpressionError::EmptyReduction { .. }))); + assert!(matches!(aggregate(values(&[0., 0.]), "/"), Err(MathExpressionError::NoReduction { .. }))); } #[test] diff --git a/node-graph/nodes/path-bool/src/lib.rs b/node-graph/nodes/path-bool/src/lib.rs index 616f8bd5ce5..06c3608cec9 100644 --- a/node-graph/nodes/path-bool/src/lib.rs +++ b/node-graph/nodes/path-bool/src/lib.rs @@ -1,11 +1,11 @@ use core_types::list::ATTR_PATHS; -use core_types::list::{ATTR_APPEARANCE, Item, List, NodeIdPath}; +use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List, NodeIdPath}; use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Ctx}; use glam::DAffine2; -use graphic_types::Appearance; -use graphic_types::graphic::bake_paint_transforms; +use graphic_types::graphic::bake_transform_into_attributes; use graphic_types::vector_types::vector::algorithms::weld::WeldExt; use graphic_types::vector_types::vector::{Path, SetVectorPaths, no_paths, paths_from_list_row_attributes, set_paths_at}; +use graphic_types::{Appearance, Effects}; use graphic_types::{Graphic, Vector}; use linesweeper::topology::Topology; use linesweeper::{BinaryOp, FillRule, binary_op}; @@ -56,14 +56,17 @@ fn boolean_operation( let result_vector = result_vector_list.element_mut(0).unwrap(); Vector::transform(result_vector, transform); - // The geometry is baked into identity space, so a copied stroke authoring space would be stale + // The geometry is baked into identity space, so the coverages and effects move onto it to keep measuring in the same space if let Some(appearance) = result_vector_list.attribute::(ATTR_APPEARANCE, 0) { let mut appearance = appearance.clone(); - for coverage in appearance.0.iter_element_values_mut() { - coverage.0.remove_attribute::(ATTR_TRANSFORM); - } + appearance.rebase_stamped_transforms(transform); result_vector_list.set_attribute(ATTR_APPEARANCE, 0, appearance); } + if let Some(effects) = result_vector_list.attribute::(ATTR_EFFECTS, 0) { + let mut effects = effects.clone(); + effects.rebase_stamped_transforms(transform); + result_vector_list.set_attribute(ATTR_EFFECTS, 0, effects); + } // Snapshot the input layers as the `editor:merged_layers` attribute so the renderer can recurse into them // for editor click-target preservation. @@ -162,7 +165,7 @@ fn boolean_operation_on_vector_list(vector: &List, boolean_operation: Bo // The result weaves its own paths rather than inheriting the operand's attributes.remove::>(ATTR_PATHS); - bake_paint_transforms(&mut attributes, copy_from_transform); + bake_transform_into_attributes(&mut attributes, copy_from_transform); Item::from_parts(Vector::default(), attributes) } else { diff --git a/node-graph/nodes/raster/Cargo.toml b/node-graph/nodes/raster/Cargo.toml index 3f9e6d56d91..c0ef7cf8047 100644 --- a/node-graph/nodes/raster/Cargo.toml +++ b/node-graph/nodes/raster/Cargo.toml @@ -16,9 +16,10 @@ workspace = true [features] default = ["serde"] -serde = ["dep:serde", "core-types/serde", "raster-types/serde", "vector-types/serde"] +serde = ["dep:serde", "core-types/serde", "graphic-types/serde", "raster-types/serde", "vector-types/serde"] wasm = [ "core-types/wasm", + "graphic-types/wasm", "raster-types/wasm", "vector-types/wasm", "tsify", @@ -33,18 +34,16 @@ core-types = { workspace = true } graphene-core = { workspace = true } graphene-resource = { workspace = true } graphene-hash = { workspace = true } +graphic-types = { workspace = true } +raster-kernels = { workspace = true } raster-types = { workspace = true } vector-types = { workspace = true } # Workspace dependencies bytemuck = { workspace = true } glam = { workspace = true } -num_enum = { workspace = true } image = { workspace = true } ndarray = { workspace = true } -rand = { workspace = true } -rand_chacha = { workspace = true } -fastnoise-lite = { workspace = true } serde = { workspace = true, optional = true } color = { workspace = true } thiserror = { workspace = true } diff --git a/node-graph/nodes/raster/src/adjust.rs b/node-graph/nodes/raster/src/adjust.rs index d0625fee9a1..78f8da84500 100644 --- a/node-graph/nodes/raster/src/adjust.rs +++ b/node-graph/nodes/raster/src/adjust.rs @@ -1,27 +1,46 @@ use core_types::color::Color; +use core_types::list::Item; +use graphic_types::Adjustment; +use raster_kernels::adjustments::{PreparedAdjustment, adjust_color, adjust_colors}; +use raster_kernels::evaluate_raster_effects; use raster_types::{CPU, Raster}; use vector_types::Gradient; -pub trait Adjust

{ - fn adjust(&mut self, map_fn: impl Fn(&P) -> P); +pub trait Adjust: Sized { + fn adjust(&mut self, adjustment: &Adjustment); + + /// The item with the effects stamped on it carried out, where the element holds the pixels they act on, so an adjustment after them applies to their result. + fn carry_out_effects(item: Item) -> Item { + item + } +} + +/// Applies the adjustment to the item's element, after the effects stamped on it before. +pub fn adjust_item(item: Item, adjustment: &Adjustment) -> Item { + let mut item = T::carry_out_effects(item); + item.element_mut().adjust(adjustment); + item } -impl Adjust for Color { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - *self = map_fn(self); +impl Adjust for Color { + fn adjust(&mut self, adjustment: &Adjustment) { + *self = adjust_color(adjustment, *self); } } -impl Adjust for Raster { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - for color in self.data_mut().data.iter_mut() { - *color = map_fn(color); - } +impl Adjust for Raster { + fn adjust(&mut self, adjustment: &Adjustment) { + adjust_colors(adjustment, &mut self.data_mut().data); + } + + fn carry_out_effects(item: Item) -> Item { + evaluate_raster_effects(item) } } -impl Adjust for Gradient { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - *self = self.map_colors(map_fn); +impl Adjust for Gradient { + fn adjust(&mut self, adjustment: &Adjustment) { + let adjustment = PreparedAdjustment::new(adjustment); + *self = self.map_colors(|color| adjustment.adjust(*color)); } } diff --git a/node-graph/nodes/raster/src/adjustments.rs b/node-graph/nodes/raster/src/adjustments.rs index c7e7b6508be..1fe0d4bc70c 100644 --- a/node-graph/nodes/raster/src/adjustments.rs +++ b/node-graph/nodes/raster/src/adjustments.rs @@ -1,105 +1,33 @@ #![allow(clippy::too_many_arguments)] -use crate::adjust::Adjust; -use crate::color_lookup_table::{LutCache, LutParseError}; -use core::fmt::Debug; +use crate::adjust::{Adjust, adjust_item}; +use crate::color_lookup_table::{LutParseError, parse_cached}; use core_types::color::Color; -use core_types::color::{linear_to_srgb, set_luminosity, srgb_to_linear}; use core_types::context::Ctx; use core_types::list::{Item, List}; -use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator}; +use core_types::transfer_curve::TransferCurve; use glam::DVec2; -use glam::Vec3; use graphene_resource::Resource; -use num_enum::{FromPrimitive, IntoPrimitive}; +use graphic_types::adjustment::{ + Adjustment, BlackAndWhiteSettings, ChannelMixerRow, ChannelMixerSettings, ColorBalanceSettings, ColorBalanceShifts, CurvesSettings, HueRangeSettings, HueSaturationSettings, HueSaturationSliders, + LevelsRecord, LevelsSettings, SelectiveColorInks, SelectiveColorSettings, +}; +pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute}; +pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType}; use raster_types::{CPU, Image, Raster}; use vector_types::Gradient; -/// Conversion from a color to grayscale. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, dyn_any::DynAny, node_macro::ChoiceType, bytemuck::NoUninit, FromPrimitive, IntoPrimitive)] -#[widget(Dropdown)] -#[repr(u32)] -pub enum DesaturateMethod { - /// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`. - /// - /// Accessibility contrast ratios and SVG luminance masks use this. - #[default] - #[label("Luminance (Rec. 709)")] - #[cfg_attr(feature = "serde", serde(alias = "SRGB"))] - LuminanceRec709, - /// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`. - /// - /// CSS filter functions such as `grayscale()` use this. - #[label("Luma (Rec. 709)")] - LumaRec709, - /// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`. - /// - /// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`. - #[label("Luma (Rec. 601)")] - LumaRec601, - /// Perceptually uniform scale from black to white, the L (lightness) of OkLab. - #[label("Lightness (OkLab)")] - #[cfg_attr(feature = "serde", serde(alias = "Perceptual"))] - LightnessOkLab, - /// Mean of the three linear-light RGB channels. - #[menu_separator] - #[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))] - ChannelsAverage, - /// Smallest of the three linear-light RGB channels. - #[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))] - ChannelsMinimum, - /// Largest of the three linear-light RGB channels, the V (value) of HSV. - #[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))] - ChannelsMaximum, - /// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL. - /// - /// The classic "Desaturate" command of many image editors uses this. - #[label("Lightness (HSL)")] - LightnessHsl, +fn adjust(item: Item, adjustment: Adjustment) -> Item { + adjust_item(item, &adjustment) } #[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))] -fn desaturate>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, method: Item) -> Item { - let mut input = input; - let method = method.into_element(); - - input.element_mut().adjust(|color| { - // Gamma-encoded formulas are decoded as if they were a gray - let gamma = || color.to_gamma_srgb_channels(); - let luminance = match method { - DesaturateMethod::LuminanceRec709 => color.luminance_rec_709(), - DesaturateMethod::LumaRec709 => { - let [r, g, b, _] = gamma(); - srgb_to_linear(0.2126 * r + 0.7152 * g + 0.0722 * b) - } - DesaturateMethod::LumaRec601 => { - let [r, g, b, _] = gamma(); - srgb_to_linear(0.299 * r + 0.587 * g + 0.114 * b) - } - DesaturateMethod::LightnessOkLab => { - // A gray's OkLab lightness is the cube root of its linear value, so cubing gives the gray of equal lightness - let lightness = color.lightness_oklab(); - lightness * lightness * lightness - } - DesaturateMethod::ChannelsAverage => color.average_rgb_channels(), - DesaturateMethod::ChannelsMinimum => color.minimum_rgb_channels(), - DesaturateMethod::ChannelsMaximum => color.maximum_rgb_channels(), - DesaturateMethod::LightnessHsl => { - // The transfer curve is monotonic, so the extremes are found first and only they are encoded - let max = linear_to_srgb(color.maximum_rgb_channels()); - let min = linear_to_srgb(color.minimum_rgb_channels()); - srgb_to_linear((max + min) / 2.) - } - }; - color.map_rgb(|_| luminance) - }); - input +fn desaturate(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, method: Item) -> Item { + adjust(input, Adjustment::Desaturate { method: method.into_element() }) } #[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))] -fn gamma_correction>( +fn gamma_correction( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[default(2.2)] @@ -109,13 +37,13 @@ fn gamma_correction>( gamma: Item, inverse: Item, ) -> Item { - let mut input = input; - let gamma = gamma.into_element(); - let inverse = inverse.into_element(); - - let exponent = if inverse { 1. / gamma } else { gamma }; - input.element_mut().adjust(|color| color.apply_gamma_exponent(exponent as f32)); - input + adjust( + input, + Adjustment::GammaCorrection { + gamma: gamma.into_element(), + inverse: inverse.into_element(), + }, + ) } /// The red, green, blue, and alpha channels of an image, split into separate node outputs. @@ -134,7 +62,7 @@ pub struct ImageChannels { /// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image. #[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))] fn image_to_channels(_: impl Ctx, image: Item>) -> ImageChannels { - let (image, attributes) = image.into_parts(); + let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts(); let (width, height) = (image.width, image.height); // O(4 × pixels), since all four channels are written even when only some outputs are connected @@ -155,104 +83,8 @@ fn image_to_channels(_: impl Ctx, image: Item>) -> ImageChannels { } #[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))] -fn make_opaque>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { - let mut input = input; - input.element_mut().adjust(|color| color.with_alpha(1.)); - input -} - -/// Remaps a gamma-space channel through the stages of a Levels adjustment: the input range, the midtones gamma, and the output range. -fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, inverse_gamma: f32, output_minimum: f32, output_maximum: f32) -> f32 { - let highlights_minus_shadows = (input_highlights - input_shadows).clamp(f32::EPSILON, 1.); - let value = ((value - input_shadows).max(0.) / highlights_minus_shadows).min(1.); - let value = value.powf(inverse_gamma); - - value * (output_maximum - output_minimum) + output_minimum -} - -/// The classic Brightness/Contrast algorithm: a Levels remap around the pivot, adding the brightness before a positive -/// contrast stretch and after a negative contrast squeeze. -fn brightness_contrast_classic(value: f32, brightness: f32, contrast: f32, pivot: f32) -> f32 { - // Full contrast is a hard step, sending values at the pivot or above to white (with half a 16-bit step of slack for float ties) - if contrast >= 1. { - return if value + brightness >= pivot - 1. / 65536. { 1. } else { 0. }; - } - - let result = if contrast > 0. { - let input_shadows = pivot * contrast - brightness; - apply_levels(value, input_shadows, input_shadows + 1. - contrast, 1., 0., 1.) - } else { - let output_minimum = brightness - pivot * contrast; - apply_levels(value, 0., 1., 1., output_minimum, output_minimum + 1. + contrast) - }; - - result.clamp(0., 1.) -} - -/// One brightness curve of the current algorithm, for a magnitude in 0..100: a line of slope 2^(b/110) up to an output of 0.5, -/// continued by a cubic Hermite segment that eases into (1, 1). -struct BrightnessCurve { - slope: f32, - knee: f32, - end_slope: f32, -} - -impl BrightnessCurve { - fn new(brightness: f32) -> Self { - let slope = 2_f32.powf(brightness / 110.); - let knee = 0.5 / slope; - let end_slope = (1. / (1. + 12. * (slope - 1.))).max(0.1); - - Self { slope, knee, end_slope } - } - - /// Evaluates the Hermite segment at its parameter t in 0..1, returning the value and its derivative with respect to x. - fn hermite(&self, t: f32) -> (f32, f32) { - let length = 1. - self.knee; - let start_tangent = length * self.slope; - let end_tangent = length * self.end_slope; - let t2 = t * t; - let t3 = t2 * t; - - let value = (2. * t3 - 3. * t2 + 1.) * 0.5 + (t3 - 2. * t2 + t) * start_tangent + (-2. * t3 + 3. * t2) + (t3 - t2) * end_tangent; - let derivative = ((6. * t2 - 6. * t) * 0.5 + (3. * t2 - 4. * t + 1.) * start_tangent + (-6. * t2 + 6. * t) + (3. * t2 - 2. * t) * end_tangent) / length; - - (value, derivative) - } - - fn forward(&self, x: f32) -> f32 { - if x < self.knee { - return self.slope * x; - } - - let t = ((x - self.knee) / (1. - self.knee)).min(1.); - self.hermite(t).0.min(1.) - } - - /// Inverts the curve, solving the monotone Hermite segment with a bracketed Newton iteration. - fn inverse(&self, y: f32) -> f32 { - if y <= 0.5 { - return y / self.slope; - } - - let mut low = 0.; - let mut high = 1.; - let mut t = (y - 0.5) * 2.; - for _ in 0..8 { - let (value, derivative) = self.hermite(t); - let error = value - y; - if error > 0. { - high = t; - } else { - low = t; - } - - let step = t - error / (derivative * (1. - self.knee)); - t = if step >= low && step <= high { step } else { (low + high) * 0.5 }; - } - - self.knee + t * (1. - self.knee) - } +fn make_opaque(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { + adjust(input, Adjustment::MakeOpaque) } // Aims for interoperable compatibility with: @@ -264,7 +96,7 @@ impl BrightnessCurve { // // TODO: A Lab-only mode once Graphite supports the CIE Lab color space. #[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))] -fn brightness_contrast>( +fn brightness_contrast( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[unit("%")] @@ -281,46 +113,20 @@ fn brightness_contrast>( #[default(127.)] classic_pivot: Item, ) -> Item { - let mut input = input; - let use_classic = use_classic.into_element(); - let classic_pivot = (classic_pivot.into_element() / 255.) as f32; - - // Each algorithm has its own slider range, matched here and in the Inspector - let (brightness_extent, contrast_minimum) = if use_classic { (100., -100.) } else { (150., -50.) }; - let brightness = (brightness.into_element() as f32).clamp(-brightness_extent, brightness_extent); - let contrast = (contrast.into_element() as f32).clamp(contrast_minimum, 100.) / 100.; - - // Beyond a magnitude of 100, the curve for 100 is applied first and the curve for the remainder after it - let magnitude = brightness.abs(); - let first_curve = BrightnessCurve::new(magnitude.min(100.)); - let second_curve = BrightnessCurve::new((magnitude - 100.).max(0.)); - - input.element_mut().adjust(|color| { - color.map_gamma_rgb(|c| { - if use_classic { - return brightness_contrast_classic(c, brightness / 255., contrast, classic_pivot); - } - - // Negative brightness runs the same curves in reverse - let brightened = if brightness >= 0. { - second_curve.forward(first_curve.forward(c)) - } else { - first_curve.inverse(second_curve.inverse(c)) - }; - - // Contrast pushes away from (or pulls toward) the midpoint, most strongly at the quarter tones - let contrasted = brightened + 0.76 * contrast * (2. * brightened - 1.) * brightened.min(1. - brightened); - contrasted.clamp(0., 1.) - }) - }); - - input + adjust( + input, + Adjustment::BrightnessContrast { + brightness: brightness.into_element(), + contrast: contrast.into_element(), + use_classic: use_classic.into_element(), + classic_pivot: classic_pivot.into_element(), + }, + ) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] /// The channel whose settings are shown, with RGB adjusting all three color channels together. pub enum AdjustmentChannel { @@ -333,97 +139,13 @@ pub enum AdjustmentChannel { Alpha, } -/// One Levels record in the node's units: percentage input and output points and the gamma value. -#[derive(Clone, Copy)] -struct LevelsRecord { - shadows: f32, - midtones: f32, - highlights: f32, - output_minimums: f32, - output_maximums: f32, -} - -/// A record's input curve followed by its output range. -#[derive(Clone, Copy)] -struct LevelsStage { - curve: LevelsCurve, - output_minimum: f32, - output_maximum: f32, -} - -impl LevelsRecord { - fn new(shadows: f32, midtones: f32, highlights: f32, output_minimums: f32, output_maximums: f32) -> Self { - Self { - shadows, - midtones, - highlights, - output_minimums, - output_maximums, - } - } - - fn stage(&self, gamma: f32) -> LevelsStage { - LevelsStage { - curve: LevelsCurve::from_points(self.shadows * 2.55, self.highlights * 2.55, gamma), - output_minimum: self.output_minimums / 100., - output_maximum: self.output_maximums / 100., - } - } -} - -impl LevelsStage { - fn apply(&self, value: f32) -> f32 { - self.curve.apply(value) * (self.output_maximum - self.output_minimum) + self.output_minimum - } -} - -/// A channel's record followed by the composite record. -#[derive(Clone, Copy)] -struct LevelsChain { - first: LevelsStage, - second: LevelsStage, - two_stages: bool, -} - -impl LevelsChain { - fn new(channel: LevelsRecord, composite: LevelsRecord) -> Self { - // For PSD interop, two power functions with nothing between them (the composite's input points and the - // channel's output range at their defaults) merge into one curve with the product of the gammas, toe included - let nothing_between = composite.shadows == 0. && composite.highlights == 100. && channel.output_minimums == 0. && channel.output_maximums == 100.; - if nothing_between { - let merged = LevelsRecord { - output_minimums: composite.output_minimums, - output_maximums: composite.output_maximums, - ..channel - }; - let stage = merged.stage(channel.midtones * composite.midtones); - Self { - first: stage, - second: stage, - two_stages: false, - } - } else { - Self { - first: channel.stage(channel.midtones), - second: composite.stage(composite.midtones), - two_stages: true, - } - } - } - - fn apply(&self, value: f32) -> f32 { - let value = self.first.apply(value); - if self.two_stages { self.second.apply(value) } else { value } - } -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=levl%27%20%3D%20Levels // // Some further analysis available at: // https://geraldbakker.nl/psnumbers/levels.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))] -fn levels>( +fn levels( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -568,62 +290,22 @@ fn levels>( alpha_output_maximums: Item, _channel: Item, ) -> Item { - let mut image = image; - let composite = LevelsRecord::new( - shadows.into_element() as f32, - midtones.into_element() as f32, - highlights.into_element() as f32, - output_minimums.into_element() as f32, - output_maximums.into_element() as f32, - ); - let red = LevelsChain::new( - LevelsRecord::new( - red_shadows.into_element() as f32, - red_midtones.into_element() as f32, - red_highlights.into_element() as f32, - red_output_minimums.into_element() as f32, - red_output_maximums.into_element() as f32, - ), - composite, - ); - let green = LevelsChain::new( - LevelsRecord::new( - green_shadows.into_element() as f32, - green_midtones.into_element() as f32, - green_highlights.into_element() as f32, - green_output_minimums.into_element() as f32, - green_output_maximums.into_element() as f32, - ), - composite, - ); - let blue = LevelsChain::new( - LevelsRecord::new( - blue_shadows.into_element() as f32, - blue_midtones.into_element() as f32, - blue_highlights.into_element() as f32, - blue_output_minimums.into_element() as f32, - blue_output_maximums.into_element() as f32, - ), - composite, - ); - - // Alpha stands apart from the composite record that the three color channels pass through - let alpha = LevelsRecord::new( - alpha_shadows.into_element() as f32, - alpha_midtones.into_element() as f32, - alpha_highlights.into_element() as f32, - alpha_output_minimums.into_element() as f32, - alpha_output_maximums.into_element() as f32, - ); - let alpha = alpha.stage(alpha.midtones); - - image.element_mut().adjust(|color| { - // Levels math operates in gamma space - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - Color::from_gamma_srgb_channels(red.apply(r), green.apply(g), blue.apply(b), alpha.apply(a)) - }); - image + let record = |shadows: Item, midtones: Item, highlights: Item, output_minimums: Item, output_maximums: Item| LevelsRecord { + shadows: shadows.into_element(), + midtones: midtones.into_element(), + highlights: highlights.into_element(), + output_minimums: output_minimums.into_element(), + output_maximums: output_maximums.into_element(), + }; + let settings = LevelsSettings { + composite: record(shadows, midtones, highlights, output_minimums, output_maximums), + red: record(red_shadows, red_midtones, red_highlights, red_output_minimums, red_output_maximums), + green: record(green_shadows, green_midtones, green_highlights, green_output_minimums, green_output_maximums), + blue: record(blue_shadows, blue_midtones, blue_highlights, blue_output_minimums, blue_output_maximums), + alpha: record(alpha_shadows, alpha_midtones, alpha_highlights, alpha_output_minimums, alpha_output_maximums), + }; + + adjust(image, Adjustment::Levels(Box::new(settings))) } // Aims for interoperable compatibility with: @@ -634,7 +316,7 @@ fn levels>( // points, and the per-channel curves apply before the composite one, like Levels. The value between those two stages // stays exact rather than rounding through an 8-bit table, which can leave results a level away from 8-bit pipelines. #[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))] -fn curves + Send>( +fn curves( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, curve: Item, @@ -644,25 +326,15 @@ fn curves + Send>( #[name("(Alpha) Curve")] alpha_curve: Item, _channel: Item, ) -> Item { - let mut image = image; - let composite = curve.into_element().evaluator(); - let red = red_curve.into_element().evaluator(); - let green = green_curve.into_element().evaluator(); - let blue = blue_curve.into_element().evaluator(); - let alpha = alpha_curve.into_element().evaluator(); - let map = |channel: &TransferCurveEvaluator, value: f32| composite.evaluate(channel.evaluate(value as f64).clamp(0., 1.)).clamp(0., 1.) as f32; - - image.element_mut().adjust(|color| { - // Curves math operates in gamma space - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - // Alpha stands apart from the composite curve that the three color channels pass through - let a = alpha.evaluate(a as f64).clamp(0., 1.) as f32; - - Color::from_gamma_srgb_channels(map(&red, r), map(&green, g), map(&blue, b), a) - }); + let settings = CurvesSettings { + composite: curve.into_element(), + red: red_curve.into_element(), + green: green_curve.into_element(), + blue: blue_curve.into_element(), + alpha: alpha_curve.into_element(), + }; - image + adjust(image, Adjustment::Curves(Box::new(settings))) } #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] @@ -691,7 +363,7 @@ fn points_to_transfer_curve( // https://stackoverflow.com/a/55233732/775283 // Works the same for gamma and linear color #[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))] -fn black_and_white>( +fn black_and_white( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, use_tint: Item, @@ -727,63 +399,23 @@ fn black_and_white>( #[soft(-200..300)] magentas: Item, ) -> Item { - let mut image = image; - let tint = tint.into_element(); - let use_tint = use_tint.into_element(); - let reds = reds.into_element(); - let yellows = yellows.into_element(); - let greens = greens.into_element(); - let cyans = cyans.into_element(); - let blues = blues.into_element(); - let magentas = magentas.into_element(); - - image.element_mut().adjust(|color| { - // Black & White channel weights are tuned for gamma-space values - let [r, g, b, alpha_part] = color.to_gamma_srgb_channels(); - - let reds = (reds / 100.) as f32; - let yellows = (yellows / 100.) as f32; - let greens = (greens / 100.) as f32; - let cyans = (cyans / 100.) as f32; - let blues = (blues / 100.) as f32; - let magentas = (magentas / 100.) as f32; - - let gray_base = r.min(g).min(b); - - let red_part = r - gray_base; - let green_part = g - gray_base; - let blue_part = b - gray_base; - - let additional = if red_part == 0. { - let cyan_part = green_part.min(blue_part); - cyan_part * cyans + (green_part - cyan_part) * greens + (blue_part - cyan_part) * blues - } else if green_part == 0. { - let magenta_part = red_part.min(blue_part); - magenta_part * magentas + (red_part - magenta_part) * reds + (blue_part - magenta_part) * blues - } else { - let yellow_part = red_part.min(green_part); - yellow_part * yellows + (red_part - yellow_part) * reds + (green_part - yellow_part) * greens - }; - - let luminance = (gray_base + additional).clamp(0., 1.); - if !use_tint { - return Color::from_gamma_srgb_channels(luminance, luminance, luminance, alpha_part); - } - - // The tint takes on the gray's luminosity the way the Luminosity blend mode would - let [tint_r, tint_g, tint_b, _] = tint.to_gamma_srgb_channels(); - let tint_luma = luma_rec_601_fixed_point(tint_r, tint_g, tint_b); - let [tinted_r, tinted_g, tinted_b] = set_luminosity(tint_r, tint_g, tint_b, tint_luma, luminance); + let settings = BlackAndWhiteSettings { + use_tint: use_tint.into_element(), + tint: tint.into_element(), + reds: reds.into_element(), + yellows: yellows.into_element(), + greens: greens.into_element(), + cyans: cyans.into_element(), + blues: blues.into_element(), + magentas: magentas.into_element(), + }; - Color::from_gamma_srgb_channels(tinted_r, tinted_g, tinted_b, alpha_part) - }); - image + adjust(image, Adjustment::BlackAndWhite(settings)) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] pub enum HueSaturationRange { #[default] @@ -796,182 +428,13 @@ pub enum HueSaturationRange { Magentas, } -/// HSL of gamma-encoded channels: hue in degrees, saturation and lightness in 0..1. -fn gamma_rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { - let maximum = r.max(g).max(b); - let minimum = r.min(g).min(b); - let chroma = maximum - minimum; - let lightness = (maximum + minimum) / 2.; - if chroma <= 0. { - return [0., 0., lightness]; - } - - let saturation = chroma / (1. - (2. * lightness - 1.).abs()).max(1e-6); - [hexagon_hue_degrees(r, g, b), saturation.min(1.), lightness] -} - -/// Hexagon hue in degrees of three channels in any encoding, 0 for gray. -fn hexagon_hue_degrees(r: f32, g: f32, b: f32) -> f32 { - let maximum = r.max(g).max(b); - let chroma = maximum - r.min(g).min(b); - if chroma <= 0. { - return 0.; - } - - let sector = if maximum == r { - wrap_positive((g - b) / chroma, 6.) - } else if maximum == g { - (b - r) / chroma + 2. - } else { - (r - g) / chroma + 4. - }; - sector * 60. -} - -/// `value` wrapped into the range from 0 to `modulus`. -fn wrap_positive(value: f32, modulus: f32) -> f32 { - value - (value / modulus).floor() * modulus -} - -/// Gamma-encoded channels from a hue in degrees and saturation and lightness in 0..1. -fn hsl_to_gamma_rgb(hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { - let chroma = (1. - (2. * lightness - 1.).abs()) * saturation; - let sector = wrap_positive(hue, 360.) / 60.; - let x = chroma * (1. - (wrap_positive(sector, 2.) - 1.).abs()); - let (r, g, b) = if sector < 1. { - (chroma, x, 0.) - } else if sector < 2. { - (x, chroma, 0.) - } else if sector < 3. { - (0., chroma, x) - } else if sector < 4. { - (0., x, chroma) - } else if sector < 5. { - (x, 0., chroma) - } else { - (chroma, 0., x) - }; - let m = lightness - chroma / 2.; - - [(r + m).clamp(0., 1.), (g + m).clamp(0., 1.), (b + m).clamp(0., 1.)] -} - -/// One set of Hue/Saturation sliders: a hue shift in degrees and saturation and lightness amounts in -1..1. -#[derive(Clone, Copy)] -struct HueSaturationSettings { - hue: f32, - saturation: f32, - lightness: f32, -} - -impl HueSaturationSettings { - fn new(hue: f32, saturation_percent: f32, lightness_percent: f32) -> Self { - Self { - hue, - saturation: saturation_percent / 100., - lightness: lightness_percent / 100., - } - } -} - -/// A hue range with its falloff: full weight from `range_start` to `range_end`, fading linearly to zero at the falloff ends. -#[derive(Clone, Copy)] -struct HueSaturationRangeSettings { - falloff_start: f32, - range_start: f32, - range_end: f32, - falloff_end: f32, - settings: HueSaturationSettings, -} - -impl HueSaturationRangeSettings { - fn new(falloff_start: f32, range_start: f32, range_end: f32, falloff_end: f32, settings: HueSaturationSettings) -> Self { - // For PSD interop, each edge rounds to 1536 hue units per turn over 359 rather than 360 degrees, landing up to a degree late - let edge = |degrees: f32| (degrees * 1536. / 359.).round() * 360. / 1536.; - - Self { - falloff_start: edge(falloff_start), - range_start: edge(range_start), - range_end: edge(range_end), - falloff_end: edge(falloff_end), - settings, - } - } - - fn weight(&self, hue: f32) -> f32 { - let distance = |from: f32, to: f32| wrap_positive(to - from, 360.); - if distance(self.range_start, hue) <= distance(self.range_start, self.range_end) { - return 1.; - } - let start_falloff = distance(self.falloff_start, self.range_start); - let end_falloff = distance(self.range_end, self.falloff_end); - if distance(self.falloff_start, hue) < start_falloff { - return distance(self.falloff_start, hue) / start_falloff; - } - if distance(self.range_end, hue) < end_falloff { - return 1. - distance(self.range_end, hue) / end_falloff; - } - 0. - } -} - -/// The six ranges' combined effect on one pixel, gathered before the master sliders apply. -struct HueSaturationRangeEffect { - hue_shift: f32, - saturation_factor: f32, - fully_saturate: bool, - rgb: [f32; 3], -} - -impl HueSaturationRangeEffect { - fn apply(&mut self, range: &HueSaturationRangeSettings, original_hue: f32, original_saturation: f32) { - // Range weights come from the original hue, and grays belong to no range - let weight = if original_saturation > 0. { range.weight(original_hue) } else { 0. }; - if weight <= 0. { - return; - } - - self.hue_shift += range.settings.hue * weight; - // For PSD interop, +100 saturates fully from the very edge of the falloff rather than scaling with the weight - if range.settings.saturation >= 1. { - self.fully_saturate = true; - } else { - self.saturation_factor *= 1. + (saturation_gain(range.settings.saturation) - 1.) * weight; - } - self.rgb = lightness_toward_max_or_min(self.rgb, range.settings.lightness * weight); - } -} - -/// The factor a saturation amount in -1..1 applies to HSL saturation, quantized for PSD interop: 1 - trunc(256 a) / 256 below zero and floor(65280 / (255 - trunc(254 a))) / 256 above. -fn saturation_gain(amount: f32) -> f32 { - if amount < 0. { - 1. - (-amount * 256.).trunc() / 256. - } else { - (65280. / (255. - (amount * 254.).trunc())).floor() / 256. - } -} - -/// Blends toward white for a positive amount and toward black for a negative one, as the master lightness slider does. -fn lightness_toward_white_or_black(value: f32, amount: f32) -> f32 { - if amount >= 0. { value + (1. - value) * amount } else { value * (1. + amount) } -} - -/// A range's lightness moves the channels toward the color's own maximum (positive) or minimum (negative) instead. -fn lightness_toward_max_or_min(rgb: [f32; 3], amount: f32) -> [f32; 3] { - let maximum = rgb[0].max(rgb[1]).max(rgb[2]); - let minimum = rgb[0].min(rgb[1]).min(rgb[2]); - let toward = if amount >= 0. { maximum } else { minimum }; - let blend = |value: f32| value + (toward - value) * amount.abs(); - [blend(rgb[0]), blend(rgb[1]), blend(rgb[2])] -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27hue%20%27%20%3D%20Old,saturation%2C%20Photoshop%205.0 // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=0%20%3D%20Use%20other.-,Hue/Saturation,-Hue/Saturation%20settings // // TODO: Residuals in 8-bit PSD interop: the byte-hue colorize table, the colorize lightness slider (up to 2.5 levels), and the range edges (a few tenths of a degree) #[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))] -fn hue_saturation>( +fn hue_saturation( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[unit("°")] @@ -1241,125 +704,80 @@ fn hue_saturation>( magentas_falloff_end: Item, _range: Item, ) -> Item { - let mut input = input; - let master = HueSaturationSettings::new(hue.into_element() as f32, saturation.into_element() as f32, lightness.into_element() as f32); - let colorize = colorize.into_element(); - let colorize_settings = HueSaturationSettings::new(colorize_hue.into_element() as f32, colorize_saturation.into_element() as f32, colorize_lightness.into_element() as f32); - let (reds, yellows, greens, cyans, blues, magentas) = ( - HueSaturationRangeSettings::new( - reds_falloff_start.into_element() as f32, - reds_range_start.into_element() as f32, - reds_range_end.into_element() as f32, - reds_falloff_end.into_element() as f32, - HueSaturationSettings::new(reds_hue.into_element() as f32, reds_saturation.into_element() as f32, reds_lightness.into_element() as f32), + let sliders = |hue: Item, saturation: Item, lightness: Item| HueSaturationSliders { + hue: hue.into_element(), + saturation: saturation.into_element(), + lightness: lightness.into_element(), + }; + let range = |sliders: HueSaturationSliders, falloff_start: Item, range_start: Item, range_end: Item, falloff_end: Item| HueRangeSettings { + sliders, + falloff_start: falloff_start.into_element(), + range_start: range_start.into_element(), + range_end: range_end.into_element(), + falloff_end: falloff_end.into_element(), + }; + let settings = HueSaturationSettings { + master: sliders(hue, saturation, lightness), + colorize: colorize.into_element(), + colorize_sliders: sliders(colorize_hue, colorize_saturation, colorize_lightness), + reds: range( + sliders(reds_hue, reds_saturation, reds_lightness), + reds_falloff_start, + reds_range_start, + reds_range_end, + reds_falloff_end, ), - HueSaturationRangeSettings::new( - yellows_falloff_start.into_element() as f32, - yellows_range_start.into_element() as f32, - yellows_range_end.into_element() as f32, - yellows_falloff_end.into_element() as f32, - HueSaturationSettings::new(yellows_hue.into_element() as f32, yellows_saturation.into_element() as f32, yellows_lightness.into_element() as f32), + yellows: range( + sliders(yellows_hue, yellows_saturation, yellows_lightness), + yellows_falloff_start, + yellows_range_start, + yellows_range_end, + yellows_falloff_end, ), - HueSaturationRangeSettings::new( - greens_falloff_start.into_element() as f32, - greens_range_start.into_element() as f32, - greens_range_end.into_element() as f32, - greens_falloff_end.into_element() as f32, - HueSaturationSettings::new(greens_hue.into_element() as f32, greens_saturation.into_element() as f32, greens_lightness.into_element() as f32), + greens: range( + sliders(greens_hue, greens_saturation, greens_lightness), + greens_falloff_start, + greens_range_start, + greens_range_end, + greens_falloff_end, ), - HueSaturationRangeSettings::new( - cyans_falloff_start.into_element() as f32, - cyans_range_start.into_element() as f32, - cyans_range_end.into_element() as f32, - cyans_falloff_end.into_element() as f32, - HueSaturationSettings::new(cyans_hue.into_element() as f32, cyans_saturation.into_element() as f32, cyans_lightness.into_element() as f32), + cyans: range( + sliders(cyans_hue, cyans_saturation, cyans_lightness), + cyans_falloff_start, + cyans_range_start, + cyans_range_end, + cyans_falloff_end, ), - HueSaturationRangeSettings::new( - blues_falloff_start.into_element() as f32, - blues_range_start.into_element() as f32, - blues_range_end.into_element() as f32, - blues_falloff_end.into_element() as f32, - HueSaturationSettings::new(blues_hue.into_element() as f32, blues_saturation.into_element() as f32, blues_lightness.into_element() as f32), + blues: range( + sliders(blues_hue, blues_saturation, blues_lightness), + blues_falloff_start, + blues_range_start, + blues_range_end, + blues_falloff_end, ), - HueSaturationRangeSettings::new( - magentas_falloff_start.into_element() as f32, - magentas_range_start.into_element() as f32, - magentas_range_end.into_element() as f32, - magentas_falloff_end.into_element() as f32, - HueSaturationSettings::new(magentas_hue.into_element() as f32, magentas_saturation.into_element() as f32, magentas_lightness.into_element() as f32), + magentas: range( + sliders(magentas_hue, magentas_saturation, magentas_lightness), + magentas_falloff_start, + magentas_range_start, + magentas_range_end, + magentas_falloff_end, ), - ); - - input.element_mut().adjust(|color| { - let [r, g, b, alpha] = color.to_gamma_srgb_channels(); - - if colorize { - let [_, _, lightness] = gamma_rgb_to_hsl(r, g, b); - let lightness = lightness_toward_white_or_black(lightness, colorize_settings.lightness); - let [r, g, b] = hsl_to_gamma_rgb(colorize_settings.hue, colorize_settings.saturation, lightness); - return Color::from_gamma_srgb_channels(r, g, b, alpha); - } - - // Each range weights its sliders by its falloff around the original hue: hue shifts add and saturation gains multiply - let [original_hue, original_saturation, _] = gamma_rgb_to_hsl(r, g, b); - let mut effect = HueSaturationRangeEffect { - hue_shift: master.hue, - saturation_factor: 1., - fully_saturate: false, - rgb: [r, g, b], - }; - effect.apply(&reds, original_hue, original_saturation); - effect.apply(&yellows, original_hue, original_saturation); - effect.apply(&greens, original_hue, original_saturation); - effect.apply(&cyans, original_hue, original_saturation); - effect.apply(&blues, original_hue, original_saturation); - effect.apply(&magentas, original_hue, original_saturation); - let HueSaturationRangeEffect { - hue_shift, - mut saturation_factor, - mut fully_saturate, - rgb, - } = effect; - if master.saturation >= 1. { - fully_saturate = true; - } else { - saturation_factor *= saturation_gain(master.saturation); - } - - // The master lightness blends toward white or black before the hue and saturation, which work in HSL of the gamma channels - let rgb = [ - lightness_toward_white_or_black(rgb[0], master.lightness), - lightness_toward_white_or_black(rgb[1], master.lightness), - lightness_toward_white_or_black(rgb[2], master.lightness), - ]; - let [hue, saturation, lightness] = gamma_rgb_to_hsl(rgb[0], rgb[1], rgb[2]); - let saturation = if saturation <= 0. { - 0. - } else if fully_saturate { - 1. - } else { - (saturation * saturation_factor).min(1.) - }; - let [r, g, b] = hsl_to_gamma_rgb(hue + hue_shift, saturation, lightness); + }; - Color::from_gamma_srgb_channels(r, g, b, alpha) - }); - input + adjust(input, Adjustment::HueSaturation(Box::new(settings))) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27%20%3D%20Color%20Lookup-,%27nvrt%27%20%3D%20Invert,-%27post%27%20%3D%20Posterize #[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))] -fn invert>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { - let mut input = input; - input.element_mut().adjust(|color| color.map_gamma_rgb(|channel| 1. - channel)); - input +fn invert(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { + adjust(input, Adjustment::Invert) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=post%27%20%3D%20Posterize-,%27thrs%27%20%3D%20Threshold,-%27grdm%27%20%3D%20Gradient #[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))] -fn threshold>( +fn threshold( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -1373,19 +791,13 @@ fn threshold>( #[default(100.)] max_luminance: Item, ) -> Item { - let mut image = image; - let min_luminance = (min_luminance.into_element() / 100.) as f32; - let max_luminance = (max_luminance.into_element() / 100.) as f32; - - image.element_mut().adjust(|color| { - // For PSD interop, we compare this 14-bit fixed-point Rec. 601 luma against the level unrounded - let [r, g, b, _] = color.to_gamma_srgb_channels(); - let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.; - - let output = if luminance >= min_luminance && luminance <= max_luminance { Color::WHITE } else { Color::BLACK }; - output.with_alpha(color.a()) - }); - image + adjust( + image, + Adjustment::Threshold { + min_luminance: min_luminance.into_element(), + max_luminance: max_luminance.into_element(), + }, + ) } // Aims for interoperable compatibility with: @@ -1402,35 +814,26 @@ fn threshold>( // TODO: `(c[i + 1] - c[i - 1]) / 2`, the end stops repeated past the ends, so two stops give `0.5 p + 1.5 p^2 - p^3`. // TODO: - The ramp is `(1 - s) * linear + s * smooth` for smoothness s, clamped per interval to its two stop colors. #[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))] -fn gradient_map + Send>( +fn gradient_map( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[default(Color::BLACK, Color::WHITE)] gradient: Item, reverse: Item, ) -> Item { - let mut image = image; - let settings = vector_types::GradientSettings::from(&gradient); - let evaluator = gradient.into_element().evaluator(settings); - let reverse = reverse.into_element(); - - image.element_mut().adjust(|color| { - // The classic 0.3/0.59/0.11 luma of the gamma-encoded channels picks the position along the gradient - let [r, g, b, alpha] = color.to_gamma_srgb_channels(); - let intensity = 0.3 * r + 0.59 * g + 0.11 * b; - let intensity = if reverse { 1. - intensity } else { intensity }; - - // The source alpha is kept and the gradient's own alpha stops are ignored - evaluator.evaluate(intensity as f64).with_alpha(alpha) - }); - - image + adjust( + image, + Adjustment::GradientMap { + gradient, + reverse: reverse.into_element(), + }, + ) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27-,vibA%27%20%3D%20Vibrance,-%27hue%20%27%20%3D%20Old // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Vibrance%20(Photoshop%20CS3) #[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))] -fn vibrance>( +fn vibrance( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -1442,78 +845,18 @@ fn vibrance>( #[hard(-100..100)] saturation: Item, ) -> Item { - let mut image = image; - let vibrance = (vibrance.into_element() / 100.) as f32; - let saturation_scale = (1. + saturation.into_element() / 100.) as f32; - - // Vibrance then saturation, both in linear light, which equals applying each alone in turn - image.element_mut().adjust(|color| { - let (r, g, b) = (color.r(), color.g(), color.b()); - let maximum = r.max(g).max(b); - let [chroma_factor, brightness_factor] = vibrance_factors(r, g, b, vibrance); - let after_vibrance = Color::from_rgbaf32_unchecked( - scale_about_maximum(r, maximum, chroma_factor, brightness_factor), - scale_about_maximum(g, maximum, chroma_factor, brightness_factor), - scale_about_maximum(b, maximum, chroma_factor, brightness_factor), - color.a(), - ); - - // For PSD interop, saturation scales each channel's distance from a gray weighted by ProPhoto's luminance coefficients - let gray = 0.288040 * after_vibrance.r() + 0.711874 * after_vibrance.g() + 0.000086 * after_vibrance.b(); - after_vibrance.map_rgb(|c| (gray + (c - gray) * saturation_scale).clamp(0., 1.)) - }); - image -} - -fn scale_about_maximum(channel: f32, maximum: f32, chroma_factor: f32, brightness_factor: f32) -> f32 { - (brightness_factor * (maximum + chroma_factor * (channel - maximum))).clamp(0., 1.) -} - -/// Share of the vibrance boost the skin-tone protection removes at full weight, a fitted constant. -const VIBRANCE_PROTECTION_LOSS: f32 = 0.4857; - -/// Vibrance on linear SDR channels as `[chroma factor about the max, brightness multiply]` for an amount in -1..1, both fading out toward black. -/// Negative desaturates and darkens low-chroma colors most. Positive boosts them, brightens a little, and spares reds. -fn vibrance_factors(r: f32, g: f32, b: f32, amount: f32) -> [f32; 2] { - let maximum = r.max(g).max(b); - let minimum = r.min(g).min(b); - if maximum <= 0. { - return [1., 1.]; - } - let ratio = minimum / maximum; - let saturation = 1. - ratio; - let q = ratio * saturation; - let toe = 1. - (16. * maximum).min(1.); - let rolloff = 1. - toe * toe; - let brightness = (2. * q - q * q) * (1. - maximum) * rolloff; - - if amount < 0. { - let amount = -amount; - let chroma_factor = (1. - amount / 4.) * (1. - amount * (1. - rolloff * saturation * (1. + saturation) / 2.)); - return [chroma_factor, 1. - amount * brightness]; - } - - let protection = skin_tone_window(hexagon_hue_degrees(r, g, b)) * (1. - saturation * saturation); - let amount = amount * (1. - protection * (1. - amount)); - let boost = (5. / 6.) * (1. - VIBRANCE_PROTECTION_LOSS * protection) * amount * ratio * (1. - minimum) * rolloff; - [1. / (1. - boost), 1. + amount * brightness / 4.] -} - -/// How fully a hue falls under the skin-tone protection: all of it from red to 30 degrees, fading out by 45, and back in from 300. -fn skin_tone_window(hue: f32) -> f32 { - if hue < 45. { - ((45. - hue) / 15.).min(1.) - } else if hue >= 300. { - (hue - 300.) / 60. - } else { - 0. - } + adjust( + image, + Adjustment::Vibrance { + vibrance: vibrance.into_element(), + saturation: saturation.into_element(), + }, + ) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Radio)] pub enum RedGreenBlue { #[default] @@ -1533,95 +876,13 @@ pub enum RedGreenBlueAlpha { Alpha, } -/// Style of noise pattern. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -#[widget(Dropdown)] -pub enum NoiseType { - #[default] - Perlin, - #[label("OpenSimplex2")] - OpenSimplex2, - #[label("OpenSimplex2S")] - OpenSimplex2S, - Cellular, - ValueCubic, - Value, - WhiteNoise, -} - -/// Style of layered levels of the noise pattern. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum FractalType { - #[default] - None, - #[label("Fractional Brownian Motion")] - FBm, - Ridged, - PingPong, - #[label("Progressive (Domain Warp Only)")] - DomainWarpProgressive, - #[label("Independent (Domain Warp Only)")] - DomainWarpIndependent, -} - -/// Distance function used by the cellular noise. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum CellularDistanceFunction { - #[default] - Euclidean, - #[label("Euclidean Squared (Faster)")] - EuclideanSq, - Manhattan, - Hybrid, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum CellularReturnType { - CellValue, - #[default] - #[label("Nearest (F1)")] - Nearest, - #[label("Next Nearest (F2)")] - NextNearest, - #[label("Average (F1 / 2 + F2 / 2)")] - Average, - #[label("Difference (F2 - F1)")] - Difference, - #[label("Product (F2 * F1 / 2)")] - Product, - #[label("Division (F1 / F2)")] - Division, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -#[widget(Dropdown)] -pub enum DomainWarpType { - #[default] - None, - #[label("OpenSimplex2")] - OpenSimplex2, - #[label("OpenSimplex2 Reduced")] - OpenSimplex2Reduced, - BasicGrid, -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27mixr%27%20%3D%20Channel%20Mixer // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Lab%20color%20only-,Channel%20Mixer,-Key%20is%20%27mixr // // TODO: CMYK source channels once Graphite supports the CMYK color space. #[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))] -fn channel_mixer>( +fn channel_mixer( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -1730,67 +991,26 @@ fn channel_mixer>( // Display-only parameters (not used within the node) _output_channel: Item, ) -> Item { - let mut image = image; - let monochrome = monochrome.into_element(); - let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = ( - monochrome_r.into_element() as f32, - monochrome_g.into_element() as f32, - monochrome_b.into_element() as f32, - monochrome_c.into_element() as f32, - ); - let (red_r, red_g, red_b, red_c) = (red_r.into_element() as f32, red_g.into_element() as f32, red_b.into_element() as f32, red_c.into_element() as f32); - let (green_r, green_g, green_b, green_c) = ( - green_r.into_element() as f32, - green_g.into_element() as f32, - green_b.into_element() as f32, - green_c.into_element() as f32, - ); - let (blue_r, blue_g, blue_b, blue_c) = (blue_r.into_element() as f32, blue_g.into_element() as f32, blue_b.into_element() as f32, blue_c.into_element() as f32); - - image.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - // Weights and constants are 10-bit fixed point truncated toward zero, which PSD interop depends on - let weight = |percent: f32| (percent * 1024. / 100.).trunc() / 1024.; - - let (out_r, out_g, out_b) = if monochrome { - let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = (weight(monochrome_r), weight(monochrome_g), weight(monochrome_b), weight(monochrome_c)); - - let gray = (r * monochrome_r + g * monochrome_g + b * monochrome_b + monochrome_c).clamp(0., 1.); - - (gray, gray, gray) - } else { - let (red_r, red_g, red_b, red_c) = (weight(red_r), weight(red_g), weight(red_b), weight(red_c)); - let (green_r, green_g, green_b, green_c) = (weight(green_r), weight(green_g), weight(green_b), weight(green_c)); - let (blue_r, blue_g, blue_b, blue_c) = (weight(blue_r), weight(blue_g), weight(blue_b), weight(blue_c)); - - let red = (r * red_r + g * red_g + b * red_b + red_c).clamp(0., 1.); - let green = (r * green_r + g * green_g + b * green_b + green_c).clamp(0., 1.); - let blue = (r * blue_r + g * blue_g + b * blue_b + blue_c).clamp(0., 1.); - - (red, green, blue) - }; + let row = |red: Item, green: Item, blue: Item, constant: Item| ChannelMixerRow { + red: red.into_element(), + green: green.into_element(), + blue: blue.into_element(), + constant: constant.into_element(), + }; + let settings = ChannelMixerSettings { + monochrome: monochrome.into_element(), + monochrome_mix: row(monochrome_r, monochrome_g, monochrome_b, monochrome_c), + red: row(red_r, red_g, red_b, red_c), + green: row(green_r, green_g, green_b, green_c), + blue: row(blue_r, blue_g, blue_b, blue_c), + }; - Color::from_gamma_srgb_channels(out_r, out_g, out_b, a) - }); - image + adjust(image, Adjustment::ChannelMixer(Box::new(settings))) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] -#[widget(Radio)] -pub enum RelativeAbsolute { - #[default] - Relative, - Absolute, -} - -#[repr(u32)] -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] pub enum SelectiveColorChoice { #[default] Reds, @@ -1813,7 +1033,7 @@ pub enum SelectiveColorChoice { // Algorithm based on: // https://blog.pkh.me/p/22-understanding-selective-coloring-in-adobe-photoshop.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))] -fn selective_color>( +fn selective_color( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -2010,133 +1230,39 @@ fn selective_color>( _colors: Item, ) -> Item { - let mut image = image; - let mode = mode.into_element(); - let (r_c, r_m, r_y, r_k) = (r_c.into_element() as f32, r_m.into_element() as f32, r_y.into_element() as f32, r_k.into_element() as f32); - let (y_c, y_m, y_y, y_k) = (y_c.into_element() as f32, y_m.into_element() as f32, y_y.into_element() as f32, y_k.into_element() as f32); - let (g_c, g_m, g_y, g_k) = (g_c.into_element() as f32, g_m.into_element() as f32, g_y.into_element() as f32, g_k.into_element() as f32); - let (c_c, c_m, c_y, c_k) = (c_c.into_element() as f32, c_m.into_element() as f32, c_y.into_element() as f32, c_k.into_element() as f32); - let (b_c, b_m, b_y, b_k) = (b_c.into_element() as f32, b_m.into_element() as f32, b_y.into_element() as f32, b_k.into_element() as f32); - let (m_c, m_m, m_y, m_k) = (m_c.into_element() as f32, m_m.into_element() as f32, m_y.into_element() as f32, m_k.into_element() as f32); - let (w_c, w_m, w_y, w_k) = (w_c.into_element() as f32, w_m.into_element() as f32, w_y.into_element() as f32, w_k.into_element() as f32); - let (n_c, n_m, n_y, n_k) = (n_c.into_element() as f32, n_m.into_element() as f32, n_y.into_element() as f32, n_k.into_element() as f32); - let (k_c, k_m, k_y, k_k) = (k_c.into_element() as f32, k_m.into_element() as f32, k_y.into_element() as f32, k_k.into_element() as f32); - - image.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - let min = |a: f32, b: f32, c: f32| a.min(b).min(c); - let max = |a: f32, b: f32, c: f32| a.max(b).max(c); - let med = |a: f32, b: f32, c: f32| a + b + c - min(a, b, c) - max(a, b, c); - - let max_channel = max(r, g, b); - let min_channel = min(r, g, b); - - let pixel_color_range = |choice| match choice { - SelectiveColorChoice::Reds => max_channel == r, - SelectiveColorChoice::Yellows => min_channel == b, - SelectiveColorChoice::Greens => max_channel == g, - SelectiveColorChoice::Cyans => min_channel == r, - SelectiveColorChoice::Blues => max_channel == b, - SelectiveColorChoice::Magentas => min_channel == g, - SelectiveColorChoice::Whites => r > 0.5 && g > 0.5 && b > 0.5, - // Every pixel, since the neutrals scale factor already vanishes at black, white, and fully saturated colors - SelectiveColorChoice::Neutrals => true, - SelectiveColorChoice::Blacks => r < 0.5 && g < 0.5 && b < 0.5, - }; - - let color_parameter_group_scale_factor_rgb = max(r, g, b) - med(r, g, b); - let color_parameter_group_scale_factor_cmy = med(r, g, b) - min(r, g, b); - - // Used to apply the r, g, or b channel slope (by multiplying it by 1) in relative mode, or no slope (by multiplying it by 0) in absolute mode - let (slope_r, slope_g, slope_b) = match mode { - RelativeAbsolute::Relative => (r - 1., g - 1., b - 1.), - RelativeAbsolute::Absolute => (-1., -1., -1.), - }; - - let array = [ - (SelectiveColorChoice::Reds, (r_c, r_m, r_y, r_k)), - (SelectiveColorChoice::Yellows, (y_c, y_m, y_y, y_k)), - (SelectiveColorChoice::Greens, (g_c, g_m, g_y, g_k)), - (SelectiveColorChoice::Cyans, (c_c, c_m, c_y, c_k)), - (SelectiveColorChoice::Blues, (b_c, b_m, b_y, b_k)), - (SelectiveColorChoice::Magentas, (m_c, m_m, m_y, m_k)), - (SelectiveColorChoice::Whites, (w_c, w_m, w_y, w_k)), - (SelectiveColorChoice::Neutrals, (n_c, n_m, n_y, n_k)), - (SelectiveColorChoice::Blacks, (k_c, k_m, k_y, k_k)), - ]; - let mut sum = Vec3::ZERO; - for &(color_parameter_group, (c, m, y, k)) in &array { - // Skip this color parameter group... - // ...if it's unchanged from the default of zero offset on all CMYK parameters, or... - // ...if this pixel's color isn't in the range affected by this color parameter group - if (c == 0. && m == 0. && y == 0. && k == 0.) || !pixel_color_range(color_parameter_group) { - continue; - } - - let color_parameter_group_scale_factor = match color_parameter_group { - SelectiveColorChoice::Reds | SelectiveColorChoice::Greens | SelectiveColorChoice::Blues => color_parameter_group_scale_factor_rgb, - SelectiveColorChoice::Cyans | SelectiveColorChoice::Magentas | SelectiveColorChoice::Yellows => color_parameter_group_scale_factor_cmy, - SelectiveColorChoice::Whites => min(r, g, b) * 2. - 1., - SelectiveColorChoice::Neutrals => 1. - ((max(r, g, b) - 0.5).abs() + (min(r, g, b) - 0.5).abs()), - SelectiveColorChoice::Blacks => 1. - max(r, g, b) * 2., - }; - - // For PSD interop, the combined percent (c + k + c k / 100) rounds half up to an integer - let ink = |color: f32| { - let percent = ((2. * (100. * (color + k) + color * k) + 100.) / 200.).floor(); - match mode { - // The multiplier is stored as one byte, 255 / b above 1 and b / 255 below, so 99% and 100% both act as 127/128 - RelativeAbsolute::Relative => { - let multiplier = 1. + percent / 100.; - if multiplier >= 1. { - 255. / (255. / multiplier).round() - 1. - } else { - (255. * multiplier).round() / 255. - 1. - } - } - RelativeAbsolute::Absolute => percent / 100., - } - }; - - let offset_r = (ink(c) * slope_r).max(-r).min(-r + 1.) * color_parameter_group_scale_factor; - let offset_g = (ink(m) * slope_g).max(-g).min(-g + 1.) * color_parameter_group_scale_factor; - let offset_b = (ink(y) * slope_b).max(-b).min(-b + 1.) * color_parameter_group_scale_factor; - - // An 8-bit PSD document sums the groups' 8-bit offsets, which this float node does not currently attempt to reproduce - sum += Vec3::new(offset_r, offset_g, offset_b); - } - - let rgb = Vec3::new(r, g, b); - let out = (sum + rgb).clamp(Vec3::ZERO, Vec3::ONE); + let inks = |cyan: Item, magenta: Item, yellow: Item, black: Item| SelectiveColorInks { + cyan: cyan.into_element(), + magenta: magenta.into_element(), + yellow: yellow.into_element(), + black: black.into_element(), + }; + let settings = SelectiveColorSettings { + mode: mode.into_element(), + reds: inks(r_c, r_m, r_y, r_k), + yellows: inks(y_c, y_m, y_y, y_k), + greens: inks(g_c, g_m, g_y, g_k), + cyans: inks(c_c, c_m, c_y, c_k), + blues: inks(b_c, b_m, b_y, b_k), + magentas: inks(m_c, m_m, m_y, m_k), + whites: inks(w_c, w_m, w_y, w_k), + neutrals: inks(n_c, n_m, n_y, n_k), + blacks: inks(k_c, k_m, k_y, k_k), + }; - Color::from_gamma_srgb_channels(out.x, out.y, out.z, a) - }); - image + adjust(image, Adjustment::SelectiveColor(Box::new(settings))) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=nvrt%27%20%3D%20Invert-,%27post%27%20%3D%20Posterize,-%27thrs%27%20%3D%20Threshold #[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))] -fn posterize>( +fn posterize( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[default(4)] #[hard(2..)] levels: Item, ) -> Item { - let mut input = input; - let levels = levels.into_element() as f32; - - input.element_mut().adjust(|color| { - color.map_gamma_rgb(|c| { - // Bins as floor(c * levels) with the outputs spread evenly to white. - // The sliver of slack keeps an input exactly on an edge in the upper bin despite float ties. - let bin = ((c + 2e-7) * levels).floor().min(levels - 1.); - bin / (levels - 1.) - }) - }); - input + adjust(input, Adjustment::Posterize { levels: levels.into_element() }) } // Aims for interoperable compatibility with: @@ -2146,7 +1272,7 @@ fn posterize>( // The exposure, offset, and gamma operations follow: // https://geraldbakker.nl/psnumbers/exposure.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))] -fn exposure>( +fn exposure( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[range] @@ -2161,32 +1287,19 @@ fn exposure>( #[soft(0.01..10)] gamma_correction: Item, ) -> Item { - let mut input = input; - let exposure = exposure.into_element() as f32; - let offset = offset.into_element() as f32; - let gamma_correction = gamma_correction.into_element() as f32; - - // Linearizes with a 2.2 power above a straight toe of slope 1/32, the two meeting at this constant - const TOE_END: f32 = 0.05568117; // 32^(-1. / 1.2) - - let decode = |value: f32| if value < TOE_END { value / 32. } else { value.powf(2.2) }; - let encode = |linear: f32| if linear < TOE_END / 32. { linear * 32. } else { linear.powf(1. / 2.2) }; - let adjust = |c: f32| { - let linear = decode(c) * 2_f32.powf(exposure) + offset; - encode(linear.max(0.).powf(1. / gamma_correction).min(1.)) - }; - - input.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - Color::from_gamma_srgb_channels(adjust(r), adjust(g), adjust(b), a) - }); - input + adjust( + input, + Adjustment::Exposure { + exposure: exposure.into_element(), + offset: offset.into_element(), + gamma_correction: gamma_correction.into_element(), + }, + ) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] pub enum TonalRange { Shadows, @@ -2195,91 +1308,13 @@ pub enum TonalRange { Highlights, } -/// A Levels-style tone curve: input black and white points on a 0..255 scale and a gamma exponent. For gamma above 1 the -/// power curve's slope is unbounded at black, so a cubic toe holds it to 2^gamma until past where that line meets the curve. -#[derive(Debug, Clone, Copy)] -struct LevelsCurve { - black: f32, - white: f32, - exponent: f32, - toe_end: f32, - toe_value: f32, - toe_slope_start: f32, - toe_slope_end: f32, -} - -impl LevelsCurve { - fn new(black: i32, white: i32, gamma: f32) -> Self { - Self::from_points(black as f32, white as f32, gamma) - } - - /// `gamma` is the Levels dialog value (pixel exponent 1/gamma). - fn from_points(black: f32, white: f32, gamma: f32) -> Self { - let gamma = gamma.max(0.01); - let black = black.min(white - 1.); - let exponent = 1. / gamma; - - let mut curve = Self { - black, - white, - exponent, - toe_end: 0., - toe_value: 0., - toe_slope_start: 0., - toe_slope_end: 0., - }; - if gamma > 1. { - let slope = 2_f32.powf(gamma); - let intersection = 255. * slope.powf(-1. / (1. - exponent)); - // The cubic toe joins the power curve at twice the intersection - if intersection > 1e-3 { - let toe_end = 2. * intersection; - curve.toe_end = toe_end; - curve.toe_value = 255. * (toe_end / 255.).powf(exponent); - curve.toe_slope_start = slope; - curve.toe_slope_end = exponent * (toe_end / 255.).powf(exponent - 1.); - } - } - curve - } - - /// Maps one gamma-space channel value in 0..1. - fn apply(&self, value: f32) -> f32 { - let t = ((value * 255. - self.black) * 255. / (self.white - self.black)).clamp(0., 255.); - let y = if t < self.toe_end { - let u = t / self.toe_end; - let hermite_start = u * u * u - 2. * u * u + u; - let hermite_end_value = 3. * u * u - 2. * u * u * u; - let hermite_end_slope = u * u * u - u * u; - hermite_start * self.toe_end * self.toe_slope_start + hermite_end_value * self.toe_value + hermite_end_slope * self.toe_end * self.toe_slope_end - } else { - 255. * (t / 255.).powf(self.exponent) - }; - y / 255. - } -} - -/// One channel's Levels parameters from its own slider values, and (with preserve_luminosity) the slider -/// extremes across all three channels. The halvings truncate toward zero, as PSD interop requires. -fn color_balance_curve(s: i32, m: i32, h: i32, s_max: i32, m_max: i32, m_min: i32, h_min: i32, preserve_luminosity: bool) -> LevelsCurve { - let (black, white, tone) = if preserve_luminosity { - (s_max - s, 255 - (h - h_min), m - (m_max + m_min) / 2) - } else { - (0.max(-s), 255 - 0.max(h), (s + h) / 2 + m) - }; - - // Rounding the derived gamma to hundredths, the precision of a PSD Levels record, is needed for compatible results - let gamma = (2_f32.powf(tone as f32 / 100.) * 100.).round() / 100.; - LevelsCurve::new(black, white, gamma) -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27blnc%27%20%3D%20Color%20Balance // // Every channel is a Levels curve whose black point, white point, and two-decimal gamma are derived from -// the nine sliders, see `color_balance_curve`. +// the nine sliders, see `color_balance_curve` in the adjustment kernels. #[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))] -fn color_balance>( +fn color_balance( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -2336,48 +1371,26 @@ fn color_balance>( // Display-only parameter (not used within the node) _tone: Item, ) -> Item { - let mut image = image; - let preserve_luminosity = preserve_luminosity.into_element(); - - // The derivation below is integer arithmetic, so the sliders round to whole percentages first - let slider = |value: f32| value.round() as i32; - let (s_r, s_g, s_b) = ( - slider(shadows_cyan_red.into_element() as f32), - slider(shadows_magenta_green.into_element() as f32), - slider(shadows_yellow_blue.into_element() as f32), - ); - let (m_r, m_g, m_b) = ( - slider(midtones_cyan_red.into_element() as f32), - slider(midtones_magenta_green.into_element() as f32), - slider(midtones_yellow_blue.into_element() as f32), - ); - let (h_r, h_g, h_b) = ( - slider(highlights_cyan_red.into_element() as f32), - slider(highlights_magenta_green.into_element() as f32), - slider(highlights_yellow_blue.into_element() as f32), - ); - - let s_max = s_r.max(s_g).max(s_b); - let m_max = m_r.max(m_g).max(m_b); - let m_min = m_r.min(m_g).min(m_b); - let h_min = h_r.min(h_g).min(h_b); - let red = color_balance_curve(s_r, m_r, h_r, s_max, m_max, m_min, h_min, preserve_luminosity); - let green = color_balance_curve(s_g, m_g, h_g, s_max, m_max, m_min, h_min, preserve_luminosity); - let blue = color_balance_curve(s_b, m_b, h_b, s_max, m_max, m_min, h_min, preserve_luminosity); - - image.element_mut().adjust(|color| { - // The curves operate on gamma-space channel values - let [r, g, b, a] = color.to_gamma_srgb_channels(); - Color::from_gamma_srgb_channels(red.apply(r), green.apply(g), blue.apply(b), a) - }); - image + let shifts = |cyan_red: Item, magenta_green: Item, yellow_blue: Item| ColorBalanceShifts { + cyan_red: cyan_red.into_element(), + magenta_green: magenta_green.into_element(), + yellow_blue: yellow_blue.into_element(), + }; + let settings = ColorBalanceSettings { + shadows: shifts(shadows_cyan_red, shadows_magenta_green, shadows_yellow_blue), + midtones: shifts(midtones_cyan_red, midtones_magenta_green, midtones_yellow_blue), + highlights: shifts(highlights_cyan_red, highlights_magenta_green, highlights_yellow_blue), + preserve_luminosity: preserve_luminosity.into_element(), + }; + + adjust(image, Adjustment::ColorBalance(settings)) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27phfl%27%20%3D%20Photo%20Filter // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=of%20the%20file.-,Photo%20Filter,-Key%20is%20%27phfl #[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))] -fn photo_filter>( +fn photo_filter( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[default("#ec8a00")] color: Item, @@ -2388,53 +1401,14 @@ fn photo_filter>( density: Item, #[default(true)] preserve_luminosity: Item, ) -> Item { - let mut image = image; - let color = color.into_element(); - let density = (density.into_element() / 100.) as f32; - let preserve_luminosity = preserve_luminosity.into_element(); - - // The image is multiplied in XYZ by the filter color normalized to the white point, with density easing that multiplier toward 1 - let filter_xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [color.r(), color.g(), color.b()]); - let factor = [ - 1. + density * (filter_xyz[0] / WHITE_XYZ_D50[0] - 1.), - 1. + density * (filter_xyz[1] / WHITE_XYZ_D50[1] - 1.), - 1. + density * (filter_xyz[2] / WHITE_XYZ_D50[2] - 1.), - ]; - - image.element_mut().adjust(|pixel| { - let [r_in, g_in, b_in, alpha] = pixel.to_gamma_srgb_channels(); - let xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [srgb_to_linear(r_in), srgb_to_linear(g_in), srgb_to_linear(b_in)]); - let filtered = multiply_matrix(&XYZ_D50_TO_SRGB, [xyz[0] * factor[0], xyz[1] * factor[1], xyz[2] * factor[2]]); - let mut r = linear_to_srgb(filtered[0].clamp(0., 1.)); - let mut g = linear_to_srgb(filtered[1].clamp(0., 1.)); - let mut b = linear_to_srgb(filtered[2].clamp(0., 1.)); - - if preserve_luminosity { - let luma_in = luma_rec_601_fixed_point(r_in.clamp(0., 1.), g_in.clamp(0., 1.), b_in.clamp(0., 1.)); - [r, g, b] = set_luminosity(r, g, b, luma_rec_601_fixed_point(r, g, b), luma_in); - } - - Color::from_gamma_srgb_channels(r, g, b, alpha) - }); - image -} - -// sRGB colorants adapted to D50 as in the sRGB IEC61966-2.1 ICC profile, row major, and their inverse -pub(crate) const SRGB_TO_XYZ_D50: [[f32; 3]; 3] = [[0.43607, 0.38515, 0.14307], [0.22249, 0.71687, 0.06061], [0.01392, 0.09708, 0.71410]]; -pub(crate) const XYZ_D50_TO_SRGB: [[f32; 3]; 3] = [[3.134096, -1.6174, -0.490638], [-0.978793, 1.916295, 0.033454], [0.071971, -0.228987, 1.40538]]; -pub(crate) const WHITE_XYZ_D50: [f32; 3] = [0.96420, 1., 0.82491]; - -pub(crate) fn multiply_matrix(matrix: &[[f32; 3]; 3], vector: [f32; 3]) -> [f32; 3] { - [ - matrix[0][0] * vector[0] + matrix[0][1] * vector[1] + matrix[0][2] * vector[2], - matrix[1][0] * vector[0] + matrix[1][1] * vector[1] + matrix[1][2] * vector[2], - matrix[2][0] * vector[0] + matrix[2][1] * vector[1] + matrix[2][2] * vector[2], - ] -} - -/// The Rec. 601 luma in the 14-bit fixed point that PSD interop depends on. -fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { - (4915. * r + 9667. * g + 1802. * b) / 16384. + adjust( + image, + Adjustment::PhotoFilter { + color: color.into_element(), + density: density.into_element(), + preserve_luminosity: preserve_luminosity.into_element(), + }, + ) } // Aims for interoperable compatibility with: @@ -2444,7 +1418,7 @@ fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { // TODO: Support dither, which needs the pixel position that a per-color adjustment never sees. // TODO: Verify the tetrahedral interpolation, which is unconfirmed against other implementations. #[node_macro::node(category("Raster: Adjustment"), icon("NodeColorLookup"))] -fn color_lookup + Send>( +fn color_lookup( _: impl Ctx, /// The image whose colors are remapped by the LUT (lookup table). #[implementations(Raster, Color, Gradient)] @@ -2453,45 +1427,21 @@ fn color_lookup + Send>( #[name("LUT File")] #[widget(ParsedWidgetOverride::Custom = "lut_file")] lut_file: Item, - #[data] lut_cache: LutCache, ) -> Result, LutParseError> { - let mut image = image; - if lut_file.element().is_empty() { + let lut_file = lut_file.into_element(); + if lut_file.is_empty() { return Ok(image); } - let lut = lut_cache.parse(lut_file.element())?; - - image.element_mut().adjust(|color| { - // Lookup tables address the gamma-encoded channels - let [r, g, b, a] = color.to_gamma_srgb_channels(); - let [r, g, b] = lut.apply([r, g, b]); - Color::from_gamma_srgb_channels(r, g, b, a) - }); + // Parsed here to report a file that isn't a lookup table, then the kernel reuses the cached result + parse_cached(&lut_file)?; - Ok(image) + Ok(adjust(image, Adjustment::ColorLookup { lut_file })) } mod _graphene_hash_impls { - use super::{ - AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, - RelativeAbsolute, SelectiveColorChoice, TonalRange, - }; - graphene_hash::impl_via_hash!( - DesaturateMethod, - RedGreenBlue, - RedGreenBlueAlpha, - NoiseType, - FractalType, - CellularDistanceFunction, - CellularReturnType, - DomainWarpType, - RelativeAbsolute, - SelectiveColorChoice, - AdjustmentChannel, - TonalRange, - HueSaturationRange - ); + use super::{AdjustmentChannel, HueSaturationRange, RedGreenBlue, RedGreenBlueAlpha, SelectiveColorChoice, TonalRange}; + graphene_hash::impl_via_hash!(RedGreenBlue, RedGreenBlueAlpha, SelectiveColorChoice, AdjustmentChannel, TonalRange, HueSaturationRange); } #[cfg(test)] @@ -2511,6 +1461,32 @@ mod tests { } } + #[test] + fn an_adjustment_after_an_effect_applies_to_its_result() { + use core_types::ATTR_TRANSFORM; + use glam::DAffine2; + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + // A red shadow cast beside a white square by light from its left, which desaturating after the shadow turns gray + let shadow = EffectOperation::DropShadow { + color: Color::RED, + angle: 180., + distance: 4., + spread: 0., + size: 0., + contour: Default::default(), + knockout: true, + }; + let mut square = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.))); + stamp_effect(&mut square, Effect::new(&shadow)); + + let desaturated = desaturate((), square, DesaturateMethod::default().into()); + + let shaded = desaturated.element().data.iter().filter(|pixel| pixel.a() > 0.5 && pixel.r() < 0.99).collect::>(); + assert!(!shaded.is_empty(), "the shadow was carried out"); + assert!(shaded.iter().all(|pixel| (pixel.r() - pixel.g()).abs() < 0.01), "the shadow stayed red"); + } + /// Runs the node on one gamma-space gray value (0..255) and returns the gamma-space result on the same scale. fn run_brightness_contrast(value: f32, brightness: f64, contrast: f64, use_classic: bool) -> f32 { let pixel = Color::from_gamma_srgb_channels(value / 255., value / 255., value / 255., 1.); diff --git a/node-graph/nodes/raster/src/blending_nodes.rs b/node-graph/nodes/raster/src/blending_nodes.rs index 1be51ba6433..0bffc6772d9 100644 --- a/node-graph/nodes/raster/src/blending_nodes.rs +++ b/node-graph/nodes/raster/src/blending_nodes.rs @@ -1,8 +1,9 @@ -use crate::adjust::Adjust; +use crate::adjust::{Adjust, adjust_item}; use core_types::Ctx; use core_types::blending::BlendMode; use core_types::color::Color; use core_types::list::Item; +use graphic_types::Adjustment; use raster_types::{CPU, Raster}; use vector_types::Gradient; @@ -31,7 +32,7 @@ fn mix_colors( // TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay. #[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))] -fn color_overlay>( +fn color_overlay( _: impl Ctx, #[implementations( Raster, @@ -47,18 +48,12 @@ fn color_overlay>( #[default(100.)] opacity: Item, ) -> Item { - let mut image = image; - let color = color.into_element(); - let blend_mode = blend_mode.into_element(); - let opacity = (opacity.into_element() / 100.) as f32; - - image.element_mut().adjust(|pixel| { - let overlay = apply_blend_mode(color, *pixel, blend_mode); - let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity; - - Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a()) - }); - image + let adjustment = Adjustment::ColorOverlay { + color: color.into_element(), + blend_mode: blend_mode.into_element(), + opacity: opacity.into_element(), + }; + adjust_item(image, &adjustment) } #[cfg(test)] diff --git a/node-graph/nodes/raster/src/dehaze.rs b/node-graph/nodes/raster/src/dehaze.rs index 5ec82cc4e3f..7e41632d0d2 100644 --- a/node-graph/nodes/raster/src/dehaze.rs +++ b/node-graph/nodes/raster/src/dehaze.rs @@ -2,6 +2,7 @@ use core_types::context::Ctx; use core_types::list::Item; use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage}; use ndarray::{Array2, ArrayBase, Dim, OwnedRepr}; +use raster_kernels::evaluate_raster_effects; use raster_types::Image; use raster_types::{CPU, Raster}; use std::cmp::{max, min}; @@ -17,7 +18,7 @@ fn dehaze( ) -> Item> { let strength = *strength.element(); - let (image, attributes) = image_frame.into_parts(); + let (image, attributes) = evaluate_raster_effects(image_frame).into_parts(); let (width, height) = (image.width, image.height); // Prepare the image data for processing diff --git a/node-graph/nodes/raster/src/filter.rs b/node-graph/nodes/raster/src/filter.rs index 23306d5b688..1ffeddd73fc 100644 --- a/node-graph/nodes/raster/src/filter.rs +++ b/node-graph/nodes/raster/src/filter.rs @@ -1,123 +1,12 @@ -use crate::parallel_rows::fill_rows; -use bytemuck::{Pod, Zeroable}; -use core_types::color::{Alpha, Color, Pixel, RGB}; +use core_types::color::Color; use core_types::context::Ctx; use core_types::list::Item; +use raster_kernels::evaluate_raster_effects; +use raster_types::Bitmap; use raster_types::Image; -use raster_types::{Bitmap, BitmapMut}; +use raster_types::parallel_rows::fill_rows; use raster_types::{CPU, Raster}; -/// Working-buffer pixel for the blur algorithms' `gamma` mode: premultiplied sRGB-gamma `f32` channels. -/// Only used internally so the working buffer's color space is reflected in the type instead of stuffed into `Color` (which is linear-light by invariant). -#[repr(C)] -#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)] -struct PremultipliedGammaPixel { - r: f32, - g: f32, - b: f32, - a: f32, -} - -impl Pixel for PremultipliedGammaPixel {} - -impl RGB for PremultipliedGammaPixel { - type ColorChannel = f32; - fn red(&self) -> f32 { - self.r - } - fn green(&self) -> f32 { - self.g - } - fn blue(&self) -> f32 { - self.b - } -} - -impl Alpha for PremultipliedGammaPixel { - type AlphaChannel = f32; - const TRANSPARENT: Self = Self { r: 0., g: 0., b: 0., a: 0. }; - fn alpha(&self) -> f32 { - self.a - } - fn multiplied_alpha(&self, mult: f32) -> Self { - Self { - r: self.r * mult, - g: self.g * mult, - b: self.b * mult, - a: self.a * mult, - } - } -} - -fn premultiply_gamma(buffer: Image) -> Image { - Image { - width: buffer.width, - height: buffer.height, - data: buffer - .data - .into_iter() - .map(|px| { - let [r, g, b, a] = px.to_gamma_srgb_channels(); - PremultipliedGammaPixel { r: r * a, g: g * a, b: b * a, a } - }) - .collect(), - } -} - -fn unpremultiply_gamma_to_linear(buffer: Image) -> Image { - Image { - width: buffer.width, - height: buffer.height, - data: buffer - .data - .into_iter() - .map(|px| { - if px.a > 0. { - let inv_a = 1. / px.a; - Color::from_gamma_srgb_channels(px.r * inv_a, px.g * inv_a, px.b * inv_a, px.a) - } else { - Color::TRANSPARENT - } - }) - .collect(), - } -} - -/// Blurs the image with a Gaussian or box blur kernel filter. -#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"))] -fn blur( - _: impl Ctx, - /// The image to be blurred. - image_frame: Item>, - /// The radius of the blur kernel. - #[unit(" px")] - #[range] - #[hard(0..)] - #[soft(..100)] - radius: Item, - /// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts. - box_blur: Item, - /// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software. - gamma: Item, -) -> Item> { - let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element()); - - let (image, attributes) = image_frame.into_parts(); - - // TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a - // window that varies continuously rather than snapping to whole source pixels - let blurred_image = if radius < 0.1 { - // Minimum blur radius - image - } else if box_blur { - Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma)) - } else { - Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma)) - }; - - Item::from_parts(blurred_image, attributes) -} - /// Applies a median filter to reduce noise while preserving edges. #[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)] fn median_filter( @@ -133,7 +22,7 @@ fn median_filter( ) -> Item> { let radius = *radius.element(); - let (image, attributes) = image_frame.into_parts(); + let (image, attributes) = evaluate_raster_effects(image_frame).into_parts(); // TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a // window that varies continuously rather than snapping to whole source pixels @@ -147,155 +36,6 @@ fn median_filter( Item::from_parts(filtered_image, attributes) } -// 1D gaussian kernel -fn gaussian_kernel(radius: f64, image_extent: u32) -> Vec { - // Given radius, compute the size of the kernel that's approximately three times the radius - // Taps further out than the image extends never land on a pixel, so the kernel stops there while its weights keep the full radius - let kernel_radius = ((3. * radius).ceil() as usize).min(image_extent as usize); - let kernel_size = 2 * kernel_radius + 1; - let mut gaussian_kernel: Vec = vec![0.; kernel_size]; - - // Kernel values - let two_radius_squared = 2. * radius * radius; - let sum = gaussian_kernel - .iter_mut() - .enumerate() - .map(|(i, value_at_index)| { - let x = i as f64 - kernel_radius as f64; - let exponent = -(x * x) / two_radius_squared; - *value_at_index = exponent.exp(); - *value_at_index - }) - .sum::(); - - // Normalize - gaussian_kernel.iter_mut().for_each(|value_at_index| *value_at_index /= sum); - - gaussian_kernel -} - -fn gaussian_blur_algorithm(buffer: Image, radius: f64, gamma: bool) -> Image { - let kernel = gaussian_kernel(radius, buffer.width.max(buffer.height)); - if gamma { - let working = premultiply_gamma(buffer); - let blurred = gaussian_separable(working, &kernel, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a }); - unpremultiply_gamma_to_linear(blurred) - } else { - let mut working = buffer; - working.map_pixels(|px| px.to_associated_alpha()); - let mut blurred = gaussian_separable(working, &kernel, Color::from_rgbaf32_unchecked); - blurred.map_pixels(|px| px.to_unassociated_alpha()); - blurred - } -} - -fn box_blur_algorithm(buffer: Image, radius: f64, gamma: bool) -> Image { - if gamma { - let working = premultiply_gamma(buffer); - let blurred = box_separable(working, radius, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a }); - unpremultiply_gamma_to_linear(blurred) - } else { - let mut working = buffer; - working.map_pixels(|px| px.to_associated_alpha()); - let mut blurred = box_separable(working, radius, Color::from_rgbaf32_unchecked); - blurred.map_pixels(|px| px.to_unassociated_alpha()); - blurred - } -} - -fn gaussian_separable(buffer: Image

, kernel: &[f64], construct: F) -> Image

-where - P: Pixel + Copy + RGB + Alpha, - F: Fn(f32, f32, f32, f32) -> P, -{ - let (width, height) = buffer.dimensions(); - let half_kernel = kernel.len() / 2; - - let mut x_axis = Image::new(width, height, P::default()); - let mut y_axis = Image::new(width, height, P::default()); - - for pass in [false, true] { - let (max, old_buffer, current_buffer) = match pass { - false => (width, &buffer, &mut x_axis), - true => (height, &x_axis, &mut y_axis), - }; - let pass = pass as usize; - - for y in 0..height { - for x in 0..width { - let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.); - - for (i, &weight) in kernel.iter().enumerate() { - let p = [x, y][pass] as i32 + (i as i32 - half_kernel as i32); - - if p >= 0 - && p < max as i32 && let Some(px) = old_buffer.get_pixel([p as u32, x][pass], [y, p as u32][pass]) - { - r_sum += px.r() as f64 * weight; - g_sum += px.g() as f64 * weight; - b_sum += px.b() as f64 * weight; - a_sum += px.a() as f64 * weight; - weight_sum += weight; - } - } - - let (r, g, b, a) = if weight_sum > 0. { - ((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32) - } else { - let px = old_buffer.get_pixel(x, y).unwrap(); - (px.r(), px.g(), px.b(), px.a()) - }; - current_buffer.set_pixel(x, y, construct(r, g, b, a)); - } - } - } - - y_axis -} - -fn box_separable(buffer: Image

, radius: f64, construct: F) -> Image

-where - P: Pixel + Copy + RGB + Alpha, - F: Fn(f32, f32, f32, f32) -> P, -{ - let (width, height) = buffer.dimensions(); - let mut x_axis = Image::new(width, height, P::default()); - let mut y_axis = Image::new(width, height, P::default()); - - let radius = radius.min(width.max(height) as f64) as i32; - - for pass in [false, true] { - let (max, old_buffer, current_buffer) = match pass { - false => (width, &buffer, &mut x_axis), - true => (height, &x_axis, &mut y_axis), - }; - let pass = pass as usize; - - for y in 0..height { - for x in 0..width { - let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.); - - let i = [x, y][pass]; - for d in (i as i32 - radius).max(0)..=(i as i32 + radius).min(max as i32 - 1) { - if let Some(px) = old_buffer.get_pixel([d as u32, x][pass], [y, d as u32][pass]) { - let weight = 1.; - r_sum += px.r() as f64 * weight; - g_sum += px.g() as f64 * weight; - b_sum += px.b() as f64 * weight; - a_sum += px.a() as f64 * weight; - weight_sum += weight; - } - } - - let (r, g, b, a) = ((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32); - current_buffer.set_pixel(x, y, construct(r, g, b, a)); - } - } - } - - y_axis -} - fn median_filter_algorithm(original_buffer: Image, radius: u32) -> Image { let (width, height) = original_buffer.dimensions(); let mut output = Image::new(width, height, Color::TRANSPARENT); diff --git a/node-graph/nodes/raster/src/image_color_palette.rs b/node-graph/nodes/raster/src/image_color_palette.rs index 30b4e271bff..c6d6ff68b02 100644 --- a/node-graph/nodes/raster/src/image_color_palette.rs +++ b/node-graph/nodes/raster/src/image_color_palette.rs @@ -2,6 +2,7 @@ use color::{ColorSpace, Oklab}; use core_types::color::Color; use core_types::context::Ctx; use core_types::list::{Item, List}; +use raster_kernels::evaluate_raster_effects; use raster_types::{CPU, Raster}; use std::collections::BinaryHeap; use std::ops::{AddAssign, SubAssign}; @@ -25,6 +26,7 @@ fn image_color_palette( count: Item, ) -> List { let count = *count.element() as usize; + let image = evaluate_raster_effects(image); // O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)]; diff --git a/node-graph/nodes/raster/src/lib.rs b/node-graph/nodes/raster/src/lib.rs index c6eadef89d4..4a815c712ea 100644 --- a/node-graph/nodes/raster/src/lib.rs +++ b/node-graph/nodes/raster/src/lib.rs @@ -1,9 +1,8 @@ pub mod adjust; pub mod adjustments; pub mod blending_nodes; -pub mod color_lookup_table; +pub use raster_kernels::color_lookup_table; pub mod dehaze; pub mod filter; pub mod image_color_palette; -pub mod parallel_rows; pub mod std_nodes; diff --git a/node-graph/nodes/raster/src/std_nodes.rs b/node-graph/nodes/raster/src/std_nodes.rs index d0dca74b6a7..c7610f03f66 100644 --- a/node-graph/nodes/raster/src/std_nodes.rs +++ b/node-graph/nodes/raster/src/std_nodes.rs @@ -1,18 +1,18 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType}; -use crate::parallel_rows::fill_rows; use core_types::ATTR_TRANSFORM; use core_types::color::Color; -use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut}; +use core_types::color::{Alpha, AlphaMut, LinearChannel, Luminance, RGBMut}; use core_types::context::{Ctx, ExtractFootprint}; use core_types::list::Item; use core_types::math::bbox::Bbox; use core_types::transform::Transform; use dyn_any::DynAny; -use fastnoise_lite; -use glam::{DAffine2, DVec2, UVec2, Vec2}; +use glam::{DAffine2, DVec2, UVec2}; use graphene_resource::Resource; -use rand::prelude::*; -use rand_chacha::ChaCha8Rng; +use graphic_types::generator::{GeneratorPattern, NoiseSettings}; +use raster_kernels::evaluate_raster_effects; +use raster_kernels::generators::render_pattern; +use raster_types::parallel_rows::fill_rows; use raster_types::{Bitmap, BitmapMut}; use raster_types::{CPU, Raster}; use raster_types::{Image, ImageError}; @@ -52,51 +52,68 @@ fn channels_to_image( ) -> Result>, SizeMismatchError> { // An unconnected channel arrives as the default zero-sized raster, which counts as absent let present = |channel: Item>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel); - let (red, green, blue, alpha) = (present(red), present(green), present(blue), present(alpha)); - - // Take this item's transform and blending attributes from the first present channel - let Some(attributes) = [&red, &green, &blue, &alpha].iter().find_map(|channel| channel.as_ref()).map(|channel| channel.attributes().clone()) else { - return Ok(Item::default()); - }; + let channels = [red, green, blue, alpha].map(present); // All present channels must share the same dimensions - let channel_dimensions = [("Red", &red), ("Green", &green), ("Blue", &blue), ("Alpha", &alpha)] - .map(|(name, channel)| channel.as_ref().map(|channel| (name, UVec2::new(channel.element().width, channel.element().height)))); - let Some(&(first, first_size)) = channel_dimensions.iter().flatten().next() else { + let dimensions = |channel: &Item>| UVec2::new(channel.element().width, channel.element().height); + let mut present_channels = ["Red", "Green", "Blue", "Alpha"] + .into_iter() + .zip(&channels) + .filter_map(|(name, channel)| Some((name, channel.as_ref()?))); + let Some((first, first_channel)) = present_channels.next() else { return Ok(Item::default()); }; - if let Some(&(second, second_size)) = channel_dimensions.iter().flatten().find(|&&(_, size)| size != first_size) { + let (first_size, transform) = (dimensions(first_channel), first_channel.attribute_cloned_or_default::(ATTR_TRANSFORM)); + if let Some((second, second_channel)) = present_channels.find(|(_, channel)| dimensions(channel) != first_size) { return Err(SizeMismatchError { first, first_size, second, - second_size, + second_size: dimensions(second_channel), }); } let (width, height) = (first_size.x, first_size.y); + // A channel's effects grow it by the margin they cast past its edges, so every channel is placed within the widest margin + let channels = channels.map(|channel| channel.map(evaluate_raster_effects)); + let margin = |channel: &Item>| ((channel.element().width - width) / 2, (channel.element().height - height) / 2); + let (margin_x, margin_y) = channels + .iter() + .flatten() + .map(margin) + .fold((0, 0), |(x, y), (channel_x, channel_y)| (x.max(channel_x), y.max(channel_y))); + + // Take this item's blending attributes from the first present channel, whose effects are carried out by now + let Some(mut attributes) = channels.iter().flatten().next().map(|channel| channel.attributes().clone()) else { + return Ok(Item::default()); + }; + let size = DVec2::new(width as f64, height as f64); + let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size; + attributes.insert( + ATTR_TRANSFORM, + transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin), + ); + + // A channel's value at a pixel of the output, with nothing past its own edges, or `None` if the channel is absent + let value = |channel: &Option>>, x: u32, y: u32| { + channel.as_ref().map(|channel| { + let (channel_margin_x, channel_margin_y) = margin(channel); + let (x, y) = ((x + channel_margin_x).checked_sub(margin_x), (y + channel_margin_y).checked_sub(margin_y)); + x.zip(y).and_then(|(x, y)| channel.element().get_pixel(x, y)).map_or(0., |pixel| pixel.l().cast_linear_channel()) + }) + }; + // Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1 - let mut image = Image::new(width, height, Color::TRANSPARENT); + let [red, green, blue, alpha] = &channels; + let mut image = Image::new(width + 2 * margin_x, height + 2 * margin_y, Color::TRANSPARENT); for y in 0..image.height() { for x in 0..image.width() { let image_pixel = image.get_pixel_mut(x, y).unwrap(); - match red.as_ref().and_then(|r| r.element().get_pixel(x, y)) { - Some(r) => image_pixel.set_red(r.l().cast_linear_channel()), - None => image_pixel.set_red(Channel::from_linear(0.)), - } - match green.as_ref().and_then(|g| g.element().get_pixel(x, y)) { - Some(g) => image_pixel.set_green(g.l().cast_linear_channel()), - None => image_pixel.set_green(Channel::from_linear(0.)), - } - match blue.as_ref().and_then(|b| b.element().get_pixel(x, y)) { - Some(b) => image_pixel.set_blue(b.l().cast_linear_channel()), - None => image_pixel.set_blue(Channel::from_linear(0.)), - } - match alpha.as_ref().and_then(|a| a.element().get_pixel(x, y)) { - Some(a) => image_pixel.set_alpha(a.l().cast_linear_channel()), - None => image_pixel.set_alpha(Channel::from_linear(1.)), - } + image_pixel.set_red(value(red, x, y).unwrap_or(0.)); + image_pixel.set_green(value(green, x, y).unwrap_or(0.)); + image_pixel.set_blue(value(blue, x, y).unwrap_or(0.)); + image_pixel.set_alpha(value(alpha, x, y).unwrap_or(1.)); } } @@ -112,6 +129,9 @@ fn mask( #[expose] stencil: Item>, ) -> Item> { + let image = evaluate_raster_effects(image); + let stencil = evaluate_raster_effects(stencil); + // An absent stencil arrives as the default empty raster, leaving the image unmasked if stencil.element().width == 0 || stencil.element().height == 0 { return image; @@ -151,6 +171,7 @@ fn mask( #[node_macro::node(category(""))] fn extend_image_to_bounds(_: impl Ctx, image: Item>, bounds: Item) -> Result>, (Item>, ImageError)> { + let image = evaluate_raster_effects(image); let bounds = *bounds.element(); let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); @@ -298,100 +319,23 @@ fn noise_pattern( let width = (size.x * footprint_scale.x) as u32; let height = (size.y * footprint_scale.y) as u32; - // All - let mut image = Image::try_new(width, height, Color::from_luminance(0.5))?; - let mut noise = fastnoise_lite::FastNoiseLite::with_seed(seed as i32); - noise.set_frequency(Some(1. / (scale as f32).max(f32::EPSILON))); - - // Domain Warp - let domain_warp_type = match domain_warp_type { - DomainWarpType::None => None, - DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2), - DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced), - DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid), - }; - let domain_warp_active = domain_warp_type.is_some(); - noise.set_domain_warp_type(domain_warp_type); - noise.set_domain_warp_amp(Some(domain_warp_amplitude as f32)); - - // Fractal - let noise_type = match noise_type { - NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin, - NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2, - NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S, - NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular, - NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic, - NoiseType::Value => fastnoise_lite::NoiseType::Value, - NoiseType::WhiteNoise => { - // TODO: Generate in layer space, not viewport space - - let mut rng = ChaCha8Rng::seed_from_u64(seed as u64); - - for y in 0..height { - for x in 0..width { - let pixel = image.get_pixel_mut(x, y).unwrap(); - let luminance = rng.random_range(0.0..1.) as f32; - *pixel = Color::from_luminance(luminance); - } - } - - return Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)); - } - }; - noise.set_noise_type(Some(noise_type)); - let fractal_type = match fractal_type { - FractalType::None => fastnoise_lite::FractalType::None, - FractalType::FBm => fastnoise_lite::FractalType::FBm, - FractalType::Ridged => fastnoise_lite::FractalType::Ridged, - FractalType::PingPong => fastnoise_lite::FractalType::PingPong, - FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive, - FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent, - }; - noise.set_fractal_type(Some(fractal_type)); - noise.set_fractal_octaves(Some(fractal_octaves as i32)); - noise.set_fractal_lacunarity(Some(fractal_lacunarity as f32)); - noise.set_fractal_gain(Some(fractal_gain as f32)); - noise.set_fractal_weighted_strength(Some(fractal_weighted_strength as f32)); - noise.set_fractal_ping_pong_strength(Some(fractal_ping_pong_strength as f32)); - - // Cellular - let cellular_distance_function = match cellular_distance_function { - CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean, - CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq, - CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan, - CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid, - }; - let cellular_return_type = match cellular_return_type { - CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue, - CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance, - CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2, - CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add, - CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub, - CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul, - CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div, - }; - noise.set_cellular_distance_function(Some(cellular_distance_function)); - noise.set_cellular_return_type(Some(cellular_return_type)); - noise.set_cellular_jitter(Some(cellular_jitter as f32)); - - let coordinate_offset = offset.as_vec2(); - let scale = size.as_vec2() / Vec2::new(width as f32, height as f32); - // Calculate the noise for every pixel - for y in 0..height { - for x in 0..width { - let pixel = image.get_pixel_mut(x, y).unwrap(); - let pos = Vec2::new(x as f32, y as f32); - let vec = pos * scale + coordinate_offset; - - let (mut x, mut y) = (vec.x, vec.y); - if domain_warp_active && domain_warp_amplitude > 0. { - (x, y) = noise.domain_warp_2d(x, y); - } - - let luminance = (noise.get_noise_2d(x, y) + 1.) * 0.5; - *pixel = Color::from_luminance(luminance); - } - } + let noise = GeneratorPattern::Noise(NoiseSettings { + seed, + scale, + noise_type, + domain_warp_type, + domain_warp_amplitude, + fractal_type, + fractal_octaves, + fractal_lacunarity, + fractal_gain, + fractal_weighted_strength, + fractal_ping_pong_strength, + cellular_distance_function, + cellular_return_type, + cellular_jitter, + }); + let image = render_pattern(&noise, [offset, offset + size], width, height)?; Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)) } @@ -415,38 +359,43 @@ fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Result>, Im let scale = footprint.scale(); let width = (size.x * scale.x) as u32; let height = (size.y * scale.y) as u32; - - let mut image = Image::try_new(width, height, Color::TRANSPARENT)?; - let max_iter = 255; - - let scale = 3. * size.as_vec2() / Vec2::new(width as f32, height as f32); - let coordinate_offset = offset.as_vec2() * 3. - Vec2::new(2., 1.5); - for y in 0..height { - for x in 0..width { - let pos = Vec2::new(x as f32, y as f32); - let c = pos * scale + coordinate_offset; - - let iter = mandelbrot_impl(c, max_iter); - *image.get_mut(x as usize, y as usize) = map_color(iter, max_iter); - } - } + let image = render_pattern(&GeneratorPattern::Mandelbrot, [offset, offset + size], width, height)?; Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size))) } -#[inline(always)] -fn mandelbrot_impl(c: Vec2, max_iter: usize) -> usize { - let mut z = Vec2::new(0., 0.); - for i in 0..max_iter { - z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c; - if z.length_squared() > 4. { - return i; - } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channels_stay_aligned_when_effects_grow_only_one() { + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + let gray = |value: f32| { + let image = Image::new(8, 8, Color::from_rgbaf32_unchecked(value, value, value, 1.)); + Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.))) + }; + + // Only the red channel is blurred, which grows it by the blur's margin + let mut red = gray(1.); + stamp_effect( + &mut red, + Effect::new(&EffectOperation::Blur { + radius: 1., + box_blur: false, + gamma: false, + }), + ); + let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap(); + + // The other channels are placed within the same margin, and the whole image keeps its place in the document + let raster = image.element(); + assert!(raster.width > 8 && raster.height > 8, "the image grows to hold the blur, rather than coming out empty"); + let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); + let to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse(); + let center = to_pixels.transform_point2(DVec2::splat(4.)).as_uvec2(); + let pixel = raster.get_pixel(center.x, center.y).unwrap(); + assert!((pixel.g() - 0.5).abs() < 1e-6 && (pixel.b() - 0.25).abs() < 1e-6, "the unblurred channels line up: {pixel:?}"); } - max_iter -} - -fn map_color(iter: usize, max_iter: usize) -> Color { - let v = iter as f32 / max_iter as f32; - Color::from_rgbaf32_unchecked(v, v, v, 1.) } diff --git a/node-graph/nodes/text/Cargo.toml b/node-graph/nodes/text/Cargo.toml index 162107a05f0..63a9b96afa1 100644 --- a/node-graph/nodes/text/Cargo.toml +++ b/node-graph/nodes/text/Cargo.toml @@ -26,6 +26,7 @@ graphene-hash = { workspace = true } graphene-resource = { workspace = true } vector-types = { workspace = true } node-macro = { workspace = true } +math-parser = { workspace = true } # Workspace dependencies dyn-any = { workspace = true } diff --git a/node-graph/nodes/text/src/font.rs b/node-graph/nodes/text/src/font.rs index 425994a5b4d..2abc1992c6f 100644 --- a/node-graph/nodes/text/src/font.rs +++ b/node-graph/nodes/text/src/font.rs @@ -41,6 +41,26 @@ impl Font { Self::new(font_family, core_types::consts::DEFAULT_FONT_STYLE.into()) } + pub fn from_data(data: &[u8]) -> Option { + use skrifa::string::StringId; + use skrifa::{FontRef, MetadataProvider}; + + let font = FontRef::from_index(data, 0).ok()?; + let name = |preferred: StringId, fallback: StringId| { + [preferred, fallback] + .into_iter() + .find_map(|id| font.localized_strings(id).english_or_first()) + .map(|name| name.to_string()) + .filter(|name| !name.is_empty()) + }; + + let font_family = name(StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME)?; + let subfamily = name(StringId::TYPOGRAPHIC_SUBFAMILY_NAME, StringId::SUBFAMILY_NAME).unwrap_or_else(|| "Regular".to_string()); + let weight = font.attributes().weight.value().round() as u32; + + Some(Self::new(font_family, format!("{subfamily} ({weight})"))) + } + pub fn named_weight(weight: u32) -> &'static str { // From https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping match weight { diff --git a/node-graph/nodes/text/src/l_system.rs b/node-graph/nodes/text/src/l_system.rs new file mode 100644 index 00000000000..673e5ea0c84 --- /dev/null +++ b/node-graph/nodes/text/src/l_system.rs @@ -0,0 +1,820 @@ +use core_types::Ctx; +use core_types::list::Item; +use core_types::math::float_noise::round_away_float_noise; +use core_types::misc::{format_f64, parse_f64}; +use math_parser::ast; +use math_parser::context::{EvalContext, NothingMap, ValueProvider}; +use math_parser::value::Value; +use rand::rngs::StdRng; +use rand::{RngExt, SeedableRng}; +use std::collections::HashMap; +use std::ops::Range; + +/// Why the "L-System" node's string stops short of what its inputs describe. +#[derive(Debug, thiserror::Error)] +pub enum LSystemError { + #[error("Line {line} of the rules isn't a valid rule: {reason}")] + InvalidRule { line: usize, reason: String }, + #[error("The axiom isn't valid: {0}")] + InvalidAxiom(String), + #[error("A rule's math gives no number: {0}")] + Evaluation(String), + #[error("A rule's chance came out as {0}, which isn't from 0 to 1")] + InvalidChance(f64), + #[error("The chances of the rules for `{symbol}` add up to {total}, which is more than 1")] + ChancesOverOne { symbol: char, total: f64 }, + #[error("Stopped after {completed} generations, since the next would grow past the Max Symbols limit of {limit}")] + TooLong { completed: i64, limit: usize }, + #[error("Stopped after {limit} generations, since Max Symbols also limits how many generations run")] + TooManyGenerations { limit: usize }, +} + +/// Grows a string by rewriting all of its symbols at once with the rules, once per generation, for drawing with the **Turtle Path** node. +/// +/// Since every symbol with a rule is replaced in each generation, patterns repeat inside themselves at ever finer scales, like the branching of plants or the folds of fractal curves. +#[node_macro::node(name("L-System"), category("String"), icon("NodeLSystem"))] +fn l_system( + _: impl Ctx, + /// The string to start growing from. + axiom: Item, + /// One rule per line, like `F = F+F-F-F+F` (or `F -> F+F-F-F+F`), which replaces every `F` with `F+F-F-F+F` in each generation. Symbols without a rule stay as they are. + /// + /// A rule can also check the symbols around one, as in `A < B > C = D`, which rewrites a `B` only between an `A` and a `C`. A rule ending with a chance from 0 to 1, like `F = F[+F]F : 0.6`, applies only that often and otherwise leaves the symbol as it is. The chances of a symbol's rules can add up to 1 at most. + /// + /// Symbols can carry numbers, like `F(10)`. A rule names them to work out new numbers with math, and to apply only when the condition after `:` holds, as in `F(x) : x > 2 = F(x/2)[+F(x/2)]`. A chance can be worked out from them too. + /// + /// A `%` cuts off the rest of its branch, up to the `]` that ends it. + /// + /// Lines starting with `//` are skipped. + #[default("F = F+F-F-F+F")] + #[widget(ParsedWidgetOverride::Custom = "text_area")] + rules: Item, + /// Symbols to look past when a rule checks the symbols around one, usually the turns between them. + /// + /// Listing `[` and `]` reads the string straight through its branches, as if it had no brackets. + #[default("+-")] + ignored_symbols: Item, + /// How many times the rules rewrite the whole string. Each generation can multiply its length. + #[default(3)] + #[hard(0..)] + generations: Item, + /// Seed to determine unique variations on where the rules with chances apply. + #[hard(0..)] + seed: Item, + /// The longest the string may grow, in symbols, and the most generations that run. A generation past either is left out, guarding against a number of generations that would freeze the editor. + #[default(1_000_000)] + #[hard(1..)] + max_symbols: Item, +) -> Result, (Item, LSystemError)> { + // The grown string takes the axiom's place in its item, keeping the attributes it carries + let mut string = axiom; + + let mut axiom = match parse_axiom(string.element()) { + Ok(axiom) => axiom, + Err(reason) => { + string.element_mut().clear(); + return Err((string, LSystemError::InvalidAxiom(reason))); + } + }; + cut_branches(&mut axiom); + let (rule_set, rule_error) = RuleSet::parse(rules.element()); + let ignored_symbols: Vec = ignored_symbols.element().chars().filter(|symbol| !symbol.is_whitespace()).collect(); + let max_symbols = (*max_symbols.element()).max(1) as usize; + + let (modules, rewrite_error) = rewrite(axiom, &rule_set, *generations.element(), max_symbols, &ignored_symbols, *seed.element() as u64); + *string.element_mut() = modules_to_string(&modules); + + // An invalid rule is reported first, since it is usually being typed and explains any other surprise + match rule_error.or(rewrite_error) { + Some(error) => Err((string, error)), + None => Ok(string), + } +} + +/// One symbol of an L-system string, with the numbers in parentheses after it, like `F(10, 2)`. +#[derive(Clone, Debug, PartialEq)] +struct Module { + symbol: char, + parameters: Vec, +} + +/// A symbol a rule matches, with names for the numbers it carries, like `F(x, y)`. +struct Pattern { + symbol: char, + parameter_names: Vec, +} + +/// A symbol a rule writes, with the math that works out each of its numbers. +struct WrittenSymbol { + symbol: char, + parameters: Vec, +} + +/// One line of the rules: `left < symbol > right : condition = successor : chance`, where all but the symbol and successor are optional. +struct Rule { + /// The symbols that must come before the rewritten one, in reading order. + left_context: Vec, + predecessor: Pattern, + /// The symbols that must come after the rewritten one, in reading order. + right_context: Vec, + condition: Option, + successor: Vec, + /// How often this rule applies, from 0 to 1, where it matches. + chance: Option, +} + +/// A rule's chance, as a written number or as math to work out from the numbers it names. +enum Chance { + Fixed(f64), + Computed(ast::Node), +} + +/// The rules, looked up by the symbol each one rewrites. +struct RuleSet { + rules: Vec, + by_symbol: HashMap>, + uses_context: bool, +} + +impl RuleSet { + /// Parses one rule per line, keeping the valid rules and the error of the first invalid one. + fn parse(text: &str) -> (Self, Option) { + let mut rules = Vec::new(); + let mut first_error = None; + + for (index, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with("//") { + continue; + } + + match parse_rule(line) { + Ok(rule) => rules.push(rule), + Err(reason) if first_error.is_none() => first_error = Some(LSystemError::InvalidRule { line: index + 1, reason }), + Err(_) => {} + } + } + + let mut by_symbol: HashMap> = HashMap::new(); + for (index, rule) in rules.iter().enumerate() { + by_symbol.entry(rule.predecessor.symbol).or_default().push(index); + } + let uses_context = rules.iter().any(|rule| !rule.left_context.is_empty() || !rule.right_context.is_empty()); + + (Self { rules, by_symbol, uses_context }, first_error) + } +} + +/// The numbers a matched rule's names stand for. +#[derive(Default)] +struct Bindings<'a>(Vec<(&'a str, f64)>); + +impl ValueProvider for Bindings<'_> { + fn get_value(&self, name: &str) -> Option { + self.0.iter().find(|(bound_name, _)| *bound_name == name).map(|&(_, value)| Value::from_f64(value)) + } +} + +impl<'a> Bindings<'a> { + /// Names the numbers of a module that matches the pattern, or gives `false` when the symbol or count of numbers differs. + fn bind(&mut self, pattern: &'a Pattern, module: &Module) -> bool { + if pattern.symbol != module.symbol || pattern.parameter_names.len() != module.parameters.len() { + return false; + } + + self.0.extend(pattern.parameter_names.iter().map(String::as_str).zip(module.parameters.iter().copied())); + true + } +} + +/// Rewrites every module once per generation, giving the last complete generation and why it stopped early, if it did. +fn rewrite(axiom: Vec, rule_set: &RuleSet, generations: i64, max_symbols: usize, ignored_symbols: &[char], seed: u64) -> (Vec, Option) { + let mut rng = StdRng::seed_from_u64(seed); + let mut modules = axiom; + + for generation in 0..generations { + // Running more generations than Max Symbols without passing it takes a string that stopped growing, which could otherwise run long enough to freeze the editor + if generation >= max_symbols as i64 { + return (modules, Some(LSystemError::TooManyGenerations { limit: max_symbols })); + } + + let partners = if rule_set.uses_context { bracket_partners(&modules) } else { Vec::new() }; + let neighbors = Neighbors { + modules: &modules, + partners: &partners, + ignored_symbols, + }; + + let mut next = Vec::with_capacity(modules.len()); + let mut rolled = false; + for (index, module) in modules.iter().enumerate() { + let chosen = match choose_rule(rule_set, &neighbors, index, &mut rng, &mut rolled) { + Ok(chosen) => chosen, + Err(error) => return (modules, Some(error)), + }; + + let Some((rule, bindings)) = chosen else { + next.push(module.clone()); + continue; + }; + for written in &rule.successor { + let parameters = match written.parameters.iter().map(|expression| evaluate_number(expression, &bindings)).collect() { + Ok(parameters) => parameters, + Err(reason) => return (modules, Some(LSystemError::Evaluation(reason))), + }; + next.push(Module { symbol: written.symbol, parameters }); + } + + if next.len() > max_symbols { + return ( + modules, + Some(LSystemError::TooLong { + completed: generation, + limit: max_symbols, + }), + ); + } + } + + cut_branches(&mut next); + + // A generation that changed nothing without rolling any chances would repeat forever, so growth has settled + let settled = !rolled && next == modules; + modules = next; + if settled { + break; + } + } + + (modules, None) +} + +/// Erases each `%` along with the rest of its branch, up to the `]` that ends it, or to the end of the string outside any branch. O(n). +fn cut_branches(modules: &mut Vec) { + if !modules.iter().any(|module| module.symbol == '%') { + return; + } + + // While cutting, the count of branches opened since the `%`, so the `]` ending the cut branch is kept + let mut cut_depth: Option = None; + modules.retain(|module| match (cut_depth, module.symbol) { + (None, '%') => { + cut_depth = Some(0); + false + } + (None, _) => true, + (Some(0), ']') => { + cut_depth = None; + true + } + (Some(depth), '[') => { + cut_depth = Some(depth + 1); + false + } + (Some(depth), ']') => { + cut_depth = Some(depth - 1); + false + } + (Some(_), _) => false, + }); +} + +/// The rule that rewrites the module at `index` with its names bound. The first matching rule applies, unless it gives a chance, in which case one roll picks among the matching rules that give chances, or none with the chance left over. +/// Making that roll sets `rolled`. +fn choose_rule<'a>(rule_set: &'a RuleSet, neighbors: &Neighbors, index: usize, rng: &mut StdRng, rolled: &mut bool) -> Result)>, LSystemError> { + let module = &neighbors.modules[index]; + let Some(candidates) = rule_set.by_symbol.get(&module.symbol) else { return Ok(None) }; + + let mut chance_matches = Vec::new(); + for &rule_index in candidates { + let rule = &rule_set.rules[rule_index]; + let Some(bindings) = matching_bindings(rule, neighbors, index).map_err(LSystemError::Evaluation)? else { + continue; + }; + + let chance = match &rule.chance { + Some(Chance::Fixed(chance)) => *chance, + Some(Chance::Computed(expression)) => evaluate_number(expression, &bindings).map_err(LSystemError::Evaluation)?, + None if chance_matches.is_empty() => return Ok(Some((rule, bindings))), + None => continue, + }; + if !(0. ..=1.).contains(&chance) { + return Err(LSystemError::InvalidChance(chance)); + } + chance_matches.push((rule, bindings, chance)); + } + + // Rounding lets chances like 0.7 and 0.2 and 0.1 add up to exactly 1 + let total = round_away_float_noise(chance_matches.iter().map(|(_, _, chance)| chance).sum()); + if total > 1. { + return Err(LSystemError::ChancesOverOne { symbol: module.symbol, total }); + } + if total == 0. { + return Ok(None); + } + + // When the chances add up to 1, the last rule also takes any sliver that float rounding leaves past it + *rolled = true; + let mut roll = rng.random::(); + let last = chance_matches.len() - 1; + for (position, (rule, bindings, chance)) in chance_matches.into_iter().enumerate() { + if roll < chance || (position == last && total == 1.) { + return Ok(Some((rule, bindings))); + } + roll -= chance; + } + + Ok(None) +} + +/// The rule's names bound to the numbers of the module at `index` and its context, or `None` when the rule doesn't match there. +fn matching_bindings<'a>(rule: &'a Rule, neighbors: &Neighbors, index: usize) -> Result>, String> { + let mut bindings = Bindings::default(); + if !bindings.bind(&rule.predecessor, &neighbors.modules[index]) { + return Ok(None); + } + + // The left context is checked from the nearest symbol outward, so in reverse reading order + let mut position = index; + for pattern in rule.left_context.iter().rev() { + let Some(previous) = neighbors.previous(position) else { return Ok(None) }; + if !bindings.bind(pattern, &neighbors.modules[previous]) { + return Ok(None); + } + position = previous; + } + + let mut position = index; + for pattern in &rule.right_context { + let Some(next) = neighbors.next(position) else { return Ok(None) }; + if !bindings.bind(pattern, &neighbors.modules[next]) { + return Ok(None); + } + position = next; + } + + if let Some(condition) = &rule.condition + && evaluate_number(condition, &bindings)? == 0. + { + return Ok(None); + } + + Ok(Some(bindings)) +} + +/// A generation's modules, read the way context sees them: along the turtle's path, past side branches and ignored symbols. +struct Neighbors<'a> { + modules: &'a [Module], + /// The index of each bracket's partner, from [`bracket_partners`]. + partners: &'a [Option], + ignored_symbols: &'a [char], +} + +impl Neighbors<'_> { + /// The nearest module before `index` on the way back toward the start, stepping over whole branches and out of the one `index` sits in. + fn previous(&self, index: usize) -> Option { + let mut current = index; + while current > 0 { + current -= 1; + match self.modules[current].symbol { + symbol if self.ignored_symbols.contains(&symbol) => {} + ']' => current = self.partners[current]?, + '[' => {} + _ => return Some(current), + } + } + None + } + + /// The nearest module after `index` along the same branch, stepping over side branches, or `None` where the branch ends. + fn next(&self, index: usize) -> Option { + let mut current = index + 1; + while current < self.modules.len() { + match self.modules[current].symbol { + symbol if self.ignored_symbols.contains(&symbol) => current += 1, + '[' => current = self.partners[current]? + 1, + ']' => return None, + _ => return Some(current), + } + } + None + } +} + +/// The index of each `[` and `]` module's partner, so context matching can step over whole branches in O(1). +fn bracket_partners(modules: &[Module]) -> Vec> { + let mut partners = vec![None; modules.len()]; + let mut open = Vec::new(); + + for (index, module) in modules.iter().enumerate() { + match module.symbol { + '[' => open.push(index), + ']' => { + if let Some(opening) = open.pop() { + partners[index] = Some(opening); + partners[opening] = Some(index); + } + } + _ => {} + } + } + + partners +} + +/// Writes modules back out as a string, with each one's numbers in parentheses after it. +fn modules_to_string(modules: &[Module]) -> String { + let mut text = String::with_capacity(modules.len()); + + for module in modules { + text.push(module.symbol); + if !module.parameters.is_empty() { + let numbers: Vec = module.parameters.iter().map(|&number| format_f64(number)).collect(); + text.push('('); + text.push_str(&numbers.join(",")); + text.push(')'); + } + } + + text +} + +/// Reads the axiom's modules, whose numbers may be written as math like `F(10*2)`. +fn parse_axiom(text: &str) -> Result, String> { + split_symbols(text)? + .into_iter() + .map(|(symbol, parameters)| { + let parameters = arguments(parameters).into_iter().map(evaluate_constant).collect::>()?; + Ok(Module { symbol, parameters }) + }) + .collect() +} + +/// Parses one line of the rules. +fn parse_rule(line: &str) -> Result { + let Some(separator) = rule_separator(line) else { + return Err("it needs an `=` between the symbol and what it becomes".to_string()); + }; + let (left_side, right_side) = (&line[..separator.start], &line[separator.end..]); + if rule_separator(right_side).is_some() { + return Err("it has a second `=`, but a condition checks equality with `==`".to_string()); + } + + // The left side reads `left < symbol > right : condition`, where all but the symbol are optional + let (pattern_text, condition_text) = split_at_first(left_side, ':'); + let (left_context_text, rest) = match split_at_first(pattern_text, '<') { + (left_context, Some(rest)) => (Some(left_context), rest), + (rest, None) => (None, rest), + }; + let (predecessor_text, right_context_text) = split_at_first(rest, '>'); + + let mut predecessor = parse_patterns(predecessor_text)?; + if predecessor.len() != 1 { + return Err("the left side must name exactly one symbol to rewrite".to_string()); + } + let predecessor = predecessor.remove(0); + + let left_context = left_context_text.map(parse_patterns).transpose()?.unwrap_or_default(); + let right_context = right_context_text.map(parse_patterns).transpose()?.unwrap_or_default(); + let condition = condition_text.map(parse_expression).transpose()?; + + // The right side reads `successor : chance`, where the chance is optional + let (successor_text, chance_text) = match right_side.rfind(':') { + Some(colon) => (&right_side[..colon], Some(right_side[colon + 1..].trim())), + None => (right_side, None), + }; + let chance = chance_text + .map(|text| match parse_f64(text) { + Some(chance) if (0. ..=1.).contains(&chance) => Ok(Chance::Fixed(chance)), + Some(_) => Err(format!("the chance `{text}` isn't a number from 0 to 1")), + None => parse_expression(text).map(Chance::Computed), + }) + .transpose()?; + + let successor = split_symbols(successor_text)? + .into_iter() + .map(|(symbol, parameters)| { + let parameters = arguments(parameters).into_iter().map(parse_expression).collect::>()?; + Ok(WrittenSymbol { symbol, parameters }) + }) + .collect::>()?; + + Ok(Rule { + left_context, + predecessor, + right_context, + condition, + successor, + chance, + }) +} + +/// Reads symbols with names for their numbers, like `A(x)B`, as a rule's predecessor or context. +fn parse_patterns(text: &str) -> Result, String> { + split_symbols(text)? + .into_iter() + .map(|(symbol, parameters)| { + let parameter_names = arguments(parameters) + .into_iter() + .map(|name| { + let name = name.trim(); + let mut characters = name.chars(); + let valid = characters.next().is_some_and(|first| first.is_ascii_lowercase()) && characters.all(|character| character.is_ascii_alphanumeric() || character == '_'); + if valid { + Ok(name.to_string()) + } else { + Err(format!("`{name}` can't name a number, since names start with a lowercase letter, like `x`")) + } + }) + .collect::>()?; + Ok(Pattern { symbol, parameter_names }) + }) + .collect() +} + +/// The bytes of the first `=` or `->` outside parentheses, which separates a rule's two sides, passing over comparisons like `==`, `<=`, `>=` and `!=`. +fn rule_separator(text: &str) -> Option> { + let bytes = text.as_bytes(); + let mut depth = 0; + + for (index, &byte) in bytes.iter().enumerate() { + let previous = index.checked_sub(1).map(|previous| bytes[previous]); + let next = bytes.get(index + 1).copied(); + + match byte { + b'(' => depth += 1, + b')' => depth -= 1, + b'-' if depth == 0 && next == Some(b'>') => return Some(index..index + 2), + b'=' if depth == 0 && !matches!(previous, Some(b'=' | b'<' | b'>' | b'!')) && next != Some(b'=') => return Some(index..index + 1), + _ => {} + } + } + + None +} + +/// Splits the text at the first `delimiter` outside parentheses, giving the text before it and, if found, the text after it. +fn split_at_first(text: &str, delimiter: char) -> (&str, Option<&str>) { + let mut depth = 0; + for (index, character) in text.char_indices() { + match character { + '(' => depth += 1, + ')' => depth -= 1, + _ if character == delimiter && depth == 0 => return (&text[..index], Some(&text[index + character.len_utf8()..])), + _ => {} + } + } + (text, None) +} + +/// Reads a string as symbols, each with the text inside any parentheses right after it. Whitespace between symbols is skipped. +fn split_symbols(text: &str) -> Result)>, String> { + let mut symbols = Vec::new(); + let mut characters = text.char_indices().peekable(); + + while let Some((index, character)) = characters.next() { + if character.is_whitespace() { + continue; + } + if matches!(character, '(' | ')') { + return Err(format!("`{character}` must come right after a symbol, like `F(10)`")); + } + + let after = index + character.len_utf8(); + if !text[after..].starts_with('(') { + symbols.push((character, None)); + continue; + } + + let Some(close) = closing_parenthesis(text, after) else { + return Err(format!("the `(` after `{character}` is never closed")); + }; + symbols.push((character, Some(&text[after + 1..close]))); + while characters.next_if(|&(index, _)| index <= close).is_some() {} + } + + Ok(symbols) +} + +/// The byte index of the `)` that closes the `(` at `open`. +fn closing_parenthesis(text: &str, open: usize) -> Option { + let mut depth = 0; + for (index, character) in text[open..].char_indices() { + match character { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(open + index); + } + } + _ => {} + } + } + None +} + +/// Splits the text inside a symbol's parentheses at its top-level commas, keeping the commas of nested calls like `max(a, b)`. +fn arguments(parameters: Option<&str>) -> Vec<&str> { + let Some(text) = parameters.filter(|text| !text.trim().is_empty()) else { return Vec::new() }; + + let mut pieces = Vec::new(); + let mut depth = 0; + let mut start = 0; + for (index, character) in text.char_indices() { + match character { + '(' => depth += 1, + ')' => depth -= 1, + ',' if depth == 0 => { + pieces.push(&text[start..index]); + start = index + 1; + } + _ => {} + } + } + pieces.push(&text[start..]); + + pieces +} + +fn parse_expression(text: &str) -> Result { + ast::Node::try_parse_from_str(text.trim()).map_err(|error| error.to_string()) +} + +/// Reads a written number, or works out the math of an expression like `10*2`. +fn evaluate_constant(text: &str) -> Result { + if let Some(number) = parse_f64(text.trim()) { + return Ok(number); + } + evaluate_number(&parse_expression(text)?, &Bindings::default()) +} + +/// Works out the math of an expression as a number, rounding away float noise so the string stays readable. +fn evaluate_number(expression: &ast::Node, bindings: &Bindings) -> Result { + let result = expression.eval(&EvalContext::new(bindings, NothingMap)).map_err(|error| error.to_string())?; + let number = result.as_value().and_then(|value| value.as_real()).ok_or_else(|| format!("`{result}` isn't a number"))?; + Ok(round_away_float_noise(number)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn grow(axiom: &str, rules: &str, generations: i64) -> Result { + grow_with(axiom, rules, generations, "+-", 0) + } + + fn grow_with(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64) -> Result { + grow_up_to(axiom, rules, generations, ignored_symbols, seed, 1_000_000) + } + + fn grow_up_to(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64, max_symbols: i64) -> Result { + let item = |text: &str| Item::new_from_element(text.to_string()); + let number = Item::new_from_element; + l_system((), item(axiom), item(rules), item(ignored_symbols), number(generations), number(seed), number(max_symbols)) + .map(Item::into_element) + .map_err(|(result, error)| (result.into_element(), error.to_string())) + } + + #[test] + fn accepts_an_arrow_between_a_rules_sides() { + assert_eq!(grow("F", "F -> F+F", 1).unwrap(), "F+F"); + assert_eq!(grow("F(3)", "F(x) : x > 2 -> F(x-1)", 1).unwrap(), "F(2)"); + } + + #[test] + fn rejects_a_single_equals_comparing_in_a_condition() { + let (_, error) = grow("F(0)", "F(m) : m=0 = X", 1).unwrap_err(); + assert_eq!(error, "Line 1 of the rules isn't a valid rule: it has a second `=`, but a condition checks equality with `==`"); + + // Neither comparisons nor a `where` inside a symbol's parentheses separate the sides + assert_eq!(grow("F(0)", "F(m) : m == 0 = F(n where n = m + 1)", 1).unwrap(), "F(1)"); + } + + #[test] + fn rewrites_every_symbol_at_once() { + assert_eq!(grow("F", "F = F+F-F-F+F", 1).unwrap(), "F+F-F-F+F"); + assert_eq!(grow("FX", "X = X+YF+\nY = -FX-Y", 2).unwrap(), "FX+YF++-FX-YF+"); + assert_eq!(grow("FX", "X = X+YF+", 0).unwrap(), "FX"); + } + + #[test] + fn skips_whitespace_and_comment_lines() { + assert_eq!(grow("F G", "// F = G\n\nF = F + F", 1).unwrap(), "F+FG"); + } + + #[test] + fn matches_context_past_ignored_symbols_and_branches() { + assert_eq!(grow("ABC", "A < B > C = X", 1).unwrap(), "AXC"); + assert_eq!(grow("ABD", "A < B > C = X", 1).unwrap(), "ABD"); + assert_eq!(grow("A+BC", "A < B > C = X", 1).unwrap(), "A+XC"); + + // Left context steps out of the branch a symbol starts and over whole branches before it + assert_eq!(grow("A[B]", "A < B = X", 1).unwrap(), "A[X]"); + assert_eq!(grow("A[C]B", "A < B = X", 1).unwrap(), "A[C]X"); + + // Right context ends with the branch + assert_eq!(grow("[AB]", "A > B = X", 1).unwrap(), "[XB]"); + assert_eq!(grow("[A]B", "A > B = X", 1).unwrap(), "[A]B"); + + // Ignoring the brackets reads straight through branches + assert_eq!(grow_with("A[B]", "A > B = X", 1, "[]", 0).unwrap(), "X[B]"); + assert_eq!(grow_with("A[Q]B", "A > B = X", 1, "[]", 0).unwrap(), "A[Q]B"); + assert_eq!(grow_with("A[Q]B", "Q < B = X", 1, "[]", 0).unwrap(), "A[Q]X"); + } + + #[test] + fn cuts_the_rest_of_a_branch_after_a_percent_sign() { + assert_eq!(grow("[AB[C]D]E", "A = F%", 1).unwrap(), "[F]E"); + assert_eq!(grow("AB[C]D", "A = F%", 1).unwrap(), "F"); + assert_eq!(grow("F[%G]%H", "", 0).unwrap(), "F[]"); + } + + #[test] + fn the_first_matching_rule_applies() { + assert_eq!(grow("ABB", "A < B = X\nB = Y", 1).unwrap(), "AXY"); + } + + #[test] + fn works_out_parameters_and_conditions() { + let rules = "F(x) : x > 2 = F(x/2)[+F(x/2)]"; + assert_eq!(grow("F(10)", rules, 1).unwrap(), "F(5)[+F(5)]"); + assert_eq!(grow("F(5*2)", rules, 2).unwrap(), "F(2.5)[+F(2.5)][+F(2.5)[+F(2.5)]]"); + + // Below the condition's threshold, nothing changes + assert_eq!(grow("F(1)", rules, 3).unwrap(), "F(1)"); + + // A symbol carrying a different count of numbers doesn't match + assert_eq!(grow("F(1,2)F", rules, 1).unwrap(), "F(1,2)F"); + + // Context binds its own names + assert_eq!(grow("A(3)B(4)", "A(x) < B(y) = B(x+y)", 1).unwrap(), "A(3)B(7)"); + } + + #[test] + fn picks_among_chances_the_same_way_for_a_seed() { + let rules = "F = A : 0.5\nF = B : 0.5"; + let first = grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap(); + assert_eq!(first, grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap()); + assert!(first.contains('A') && first.contains('B') && !first.contains('F')); + + // A chance of zero is never picked + assert_eq!(grow_with("FFFF", "F = A : 0\nF = B : 1", 1, "", 3).unwrap(), "BBBB"); + + // A chance can be worked out from the symbol's numbers + assert_eq!(grow_with("F(1)F(0)", "F(x) = A : x\nF(x) = B : 1 - x", 1, "", 0).unwrap(), "AB"); + let (_, error) = grow_with("F(2)", "F(x) = A : 1 - x", 1, "", 0).unwrap_err(); + assert_eq!(error, "A rule's chance came out as -1, which isn't from 0 to 1"); + } + + #[test] + fn leaves_a_symbol_unchanged_with_the_chance_left_over() { + let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.5", 1, "", 7).unwrap(); + assert!(grown.contains('A') && grown.contains('F')); + + // Chances adding up to exactly 1 always apply one of the rules + let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.7\nF = B : 0.2\nF = C : 0.1", 1, "", 7).unwrap(); + assert!(!grown.contains('F')); + + let (_, error) = grow_with("F", "F = A : 0.6\nF = B : 0.6", 1, "", 0).unwrap_err(); + assert_eq!(error, "The chances of the rules for `F` add up to 1.2, which is more than 1"); + let (_, error) = grow("F", "F = A : 2", 1).unwrap_err(); + assert_eq!(error, "Line 1 of the rules isn't a valid rule: the chance `2` isn't a number from 0 to 1"); + } + + #[test] + fn reports_the_first_invalid_line_and_keeps_the_valid_rules() { + let (result, error) = grow("F", "F = FF\nnonsense\nG(X) = G", 1).unwrap_err(); + assert_eq!(result, "FF"); + assert_eq!(error, "Line 2 of the rules isn't a valid rule: it needs an `=` between the symbol and what it becomes"); + + let (_, error) = grow("F", "G(X) = G", 1).unwrap_err(); + assert!(error.starts_with("Line 1 of the rules isn't a valid rule: `X` can't name a number")); + + let (result, error) = grow("F(", "", 1).unwrap_err(); + assert_eq!(result, ""); + assert_eq!(error, "The axiom isn't valid: the `(` after `F` is never closed"); + } + + #[test] + fn stops_before_a_generation_grows_past_max_symbols() { + let (result, error) = grow_up_to("F", "F = FFFFFFFFFF", 7, "", 0, 1000).unwrap_err(); + assert_eq!(result.len(), 1000); + assert_eq!(error, "Stopped after 3 generations, since the next would grow past the Max Symbols limit of 1000"); + } + + #[test] + fn settled_growth_ends_early_and_max_symbols_caps_generations() { + // Once nothing changes, any number of generations finishes at once + assert_eq!(grow("F", "F = F", i64::MAX), Ok("F".to_string())); + assert_eq!(grow("A(1)", "A(n) : n < 3 = A(n+1)", i64::MAX), Ok("A(3)".to_string())); + + // A string that keeps changing without growing stops at as many generations as Max Symbols + let (result, error) = grow_up_to("A(0)", "A(n) = A(n+1)", i64::MAX, "", 0, 100).unwrap_err(); + assert_eq!(result, "A(100)"); + assert_eq!(error, "Stopped after 100 generations, since Max Symbols also limits how many generations run"); + + // A generation left unchanged by a chance can still change in a later one + assert_eq!(grow("F", "F = F : 0.99\nF = G : 0.01", 2000), Ok("G".to_string())); + } +} diff --git a/node-graph/nodes/text/src/lib.rs b/node-graph/nodes/text/src/lib.rs index d7ab88bc3aa..b7bb6be82b6 100644 --- a/node-graph/nodes/text/src/lib.rs +++ b/node-graph/nodes/text/src/lib.rs @@ -1,6 +1,7 @@ pub mod fallback; mod font; pub mod json; +pub mod l_system; mod path_builder; pub mod regex; mod text_context; @@ -15,7 +16,7 @@ use core_types::misc::{format_f64, parse_f64}; use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl}; use dyn_any::DynAny; use glam::DVec2; -use rand::{Rng, SeedableRng}; +use rand::{RngExt, SeedableRng}; use unicode_segmentation::UnicodeSegmentation; // Re-export for convenience diff --git a/node-graph/nodes/text/src/path_builder.rs b/node-graph/nodes/text/src/path_builder.rs index a90bc8b63ca..80688f95693 100644 --- a/node-graph/nodes/text/src/path_builder.rs +++ b/node-graph/nodes/text/src/path_builder.rs @@ -137,7 +137,7 @@ impl PathBuilder { let font = run.font(); let font_size = run.font_size(); - let normalized_coords = run.normalized_coords().iter().map(|coord| NormalizedCoord::from_bits(*coord)).collect::>(); + let normalized_coords = run.normalized_coords().iter().map(|coord| NormalizedCoord::from_bits(coord.to_bits())).collect::>(); // TODO: This can be cached for better performance let font_collection_ref = font.data.as_ref(); diff --git a/node-graph/nodes/text/src/text_context.rs b/node-graph/nodes/text/src/text_context.rs index 140efc6e4a3..4bdc687b899 100644 --- a/node-graph/nodes/text/src/text_context.rs +++ b/node-graph/nodes/text/src/text_context.rs @@ -5,7 +5,7 @@ use core_types::list::List; use glam::DVec2; use graphene_resource::{Resource, ResourceHash}; use parley::fontique::{Blob, FamilyId, FontInfo}; -use parley::{AlignmentOptions, FontContext, GlyphRun, Layout, LayoutContext, LineHeight, PositionedLayoutItem, StyleProperty}; +use parley::{AlignmentOptions, FontContext, GlyphRun, Layout, LayoutContext, LineHeight, OverflowWrap, PositionedLayoutItem, StyleProperty}; use std::collections::HashMap; use vector_types::Vector; @@ -44,7 +44,7 @@ pub fn for_each_styled_glyph_run(layout: &Layout<()>, text: &str, typesetting: T if is_last_para_line && let Some(correction) = last_line_correction { let metrics = line.metrics(); - let content_advance = metrics.advance - metrics.trailing_whitespace; + let content_advance = metrics.advance - metrics.hanging_advance; let free_space = alignment_width - content_advance; match correction { @@ -134,6 +134,7 @@ impl TextContext { builder.push_default(StyleProperty::FontStyle(font_info.style())); builder.push_default(StyleProperty::FontWidth(font_info.width())); builder.push_default(LineHeight::FontSizeRelative(typesetting.line_height_ratio as f32)); + builder.push_default(StyleProperty::OverflowWrap(OverflowWrap::BreakWord)); let mut layout: Layout<()> = builder.build(text); diff --git a/node-graph/nodes/transform/src/transform_nodes.rs b/node-graph/nodes/transform/src/transform_nodes.rs index d6fbe0bf893..912a832858a 100644 --- a/node-graph/nodes/transform/src/transform_nodes.rs +++ b/node-graph/nodes/transform/src/transform_nodes.rs @@ -1,6 +1,8 @@ use core::f64; use core_types::color::Color; use core_types::list::{Item, List}; +use core_types::math::midpoint::apply_midpoint_inverse; +use core_types::math::spread::spread_factors; use core_types::transform::{ApplyTransform, ScaleType, Transform}; use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, Interrupt, ModifyFootprint, OwnedContextImpl}; use glam::{DAffine2, DMat2, DVec2}; @@ -216,3 +218,224 @@ fn decompose_scale(_: impl Ctx, transform: Item, scale_type: Item) -> Item { Item::new_from_element(transform.into_element().decompose_skew().atan().to_degrees()) } + +/// Rotates every item of the content about its origin by its own angle, selected from along a chosen range. +#[node_macro::node(category("Transform"), icon("NodeVaryRotations"), version(2))] +fn vary_rotations( + _: impl Ctx, + /// The content with items to rotate individually. + #[implementations(List, List, List>, List>, List, List, List)] + content: List, + /// The lower end of the range of angles given to the items. + #[unit("°")] + #[range] + #[soft(-180..180)] + #[default(-180.)] + min: Item, + /// The upper end of the range of angles given to the items. + #[unit("°")] + #[range] + #[soft(-180..180)] + #[default(180.)] + max: Item, + /// Where in the range the median angle falls, from its lower end (0) to its upper end (1). The default of 0.5 spreads the angles uniformly, while other values favor angles nearer one end. + #[range] + #[hard(0..1)] + #[default(0.5)] + bias: Item, + /// Whether to reverse the range. + reverse: Item, + /// Whether to randomize the angle selection for each item from throughout the range. + #[default(true)] + randomize: Item, + /// Seed to determine unique variations on the randomized angle selection. + #[widget(ParsedWidgetOverride::Custom = "vary_rotations_seed")] + #[hard(0..)] + seed: Item, + /// The number of items to span across the range before repeating. A 0 value will span the entire range once. + #[widget(ParsedWidgetOverride::Custom = "vary_rotations_repeat_every")] + #[hard(0..)] + repeat_every: Item, +) -> List { + let (min, max, bias, reverse) = (min.into_element(), max.into_element(), bias.into_element(), reverse.into_element()); + let (randomize, seed, repeat_every) = (randomize.into_element(), seed.into_element(), repeat_every.into_element()); + + let mut content = content; + let factors = item_factors(content.len(), randomize, seed, repeat_every, reverse); + + for (transform, factor) in content.iter_attribute_values_mut_or_default::(ATTR_TRANSFORM).zip(factors) { + let angle = min + (max - min) * apply_midpoint_inverse(factor, bias); + + // Turning only the linear part pivots each item about its own origin, in the axes of its parent + transform.matrix2 = DMat2::from_angle(angle.to_radians()) * transform.matrix2; + } + + content +} + +/// Scales every item of the content about its origin by its own factor, selected from along a chosen range. +#[node_macro::node(category("Transform"), icon("NodeVaryScales"))] +fn vary_scales( + _: impl Ctx, + /// The content with items to scale individually. + #[implementations(List, List, List>, List>, List, List, List)] + content: List, + /// The lower end of the range of scale factors given to the items. + #[unit("x")] + #[range] + #[soft(0..2)] + #[default(0.5)] + min: Item, + /// The upper end of the range of scale factors given to the items. + #[unit("x")] + #[range] + #[soft(0..2)] + #[default(2.)] + max: Item, + /// Where in the range the median scale factor falls, from its lower end (0) to its upper end (1). The default of 0.5 spreads the scale factors uniformly, while other values favor scale factors nearer one end. + #[range] + #[hard(0..1)] + #[default(0.5)] + bias: Item, + /// Whether to reverse the range. + reverse: Item, + /// Whether to randomize the scale factor selection for each item from throughout the range. + #[default(true)] + randomize: Item, + /// Seed to determine unique variations on the randomized scale factor selection. + #[widget(ParsedWidgetOverride::Custom = "vary_scales_seed")] + #[hard(0..)] + seed: Item, + /// The number of items to span across the range before repeating. A 0 value will span the entire range once. + #[widget(ParsedWidgetOverride::Custom = "vary_scales_repeat_every")] + #[hard(0..)] + repeat_every: Item, +) -> List { + let (min, max, bias, reverse) = (min.into_element(), max.into_element(), bias.into_element(), reverse.into_element()); + let (randomize, seed, repeat_every) = (randomize.into_element(), seed.into_element(), repeat_every.into_element()); + + let mut content = content; + let factors = item_factors(content.len(), randomize, seed, repeat_every, reverse); + + for (transform, factor) in content.iter_attribute_values_mut_or_default::(ATTR_TRANSFORM).zip(factors) { + let scale = min + (max - min) * apply_midpoint_inverse(factor, bias); + + transform.matrix2 *= scale; + } + + content +} + +/// The spread factor of each item for a vary node, handed out from the last item to the first when reversed. +fn item_factors(count: usize, randomize: bool, seed: i64, repeat_every: i64, reverse: bool) -> Vec { + let mut factors: Vec = spread_factors(count, randomize, seed as u64, repeat_every as u64).collect(); + if reverse { + factors.reverse(); + } + + factors +} + +#[cfg(test)] +mod test { + use super::*; + + fn colors(transforms: &[DAffine2]) -> List { + transforms + .iter() + .map(|&transform| Item::new_from_element(Color::RED).with_attribute(ATTR_TRANSFORM, transform)) + .collect() + } + + fn transforms(content: &List) -> Vec { + (0..content.len()).map(|index| content.attribute_cloned_or_default(ATTR_TRANSFORM, index)).collect() + } + + fn item(element: T) -> Item { + Item::new_from_element(element) + } + + fn rotate(content: List, min: f64, max: f64, bias: f64, reverse: bool) -> List { + vary_rotations((), content, item(min), item(max), item(bias), item(reverse), item(false), item(0), item(0)) + } + + fn scale(content: List, min: f64, max: f64, bias: f64, randomize: bool) -> List { + vary_scales((), content, item(min), item(max), item(bias), item(false), item(randomize), item(0), item(0)) + } + + fn angles(content: &List) -> Vec { + transforms(content).iter().map(|transform| transform.decompose_rotation().to_degrees()).collect() + } + + fn assert_near(actual: &[f64], expected: &[f64]) { + assert_eq!(actual.len(), expected.len()); + for (actual, expected) in actual.iter().zip(expected) { + assert!((actual - expected).abs() < 1e-9, "expected {expected:?}, found {actual:?}"); + } + } + + #[test] + fn rotations_spread_evenly_across_the_range() { + let rotated = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 90., 0.5, false); + assert_near(&angles(&rotated), &[0., 45., 90.]); + + let reversed = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 90., 0.5, true); + assert_near(&angles(&reversed), &[90., 45., 0.]); + } + + #[test] + fn reverse_runs_the_randomized_pattern_from_the_other_end() { + let randomized = |reverse| { + angles(&vary_rotations( + (), + colors(&[DAffine2::IDENTITY; 5]), + item(0.), + item(90.), + item(0.3), + item(reverse), + item(true), + item(7), + item(0), + )) + }; + + let mut forward = randomized(false); + forward.reverse(); + assert_near(&randomized(true), &forward); + } + + #[test] + fn bias_places_the_middle_item() { + let rotated = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 100., 0.2, false); + assert_near(&angles(&rotated), &[0., 20., 100.]); + } + + #[test] + fn rotation_pivots_about_the_item_origin_without_shearing() { + let original = DAffine2::from_translation(DVec2::new(5., 7.)) * DAffine2::from_scale(DVec2::new(2., 1.)); + let rotated = transforms(&rotate(colors(&[original]), 90., 90., 0.5, false))[0]; + + assert_eq!(rotated.translation, original.translation); + assert!(rotated.matrix2.x_axis.abs_diff_eq(DVec2::new(0., 2.), 1e-9)); + assert!(rotated.matrix2.y_axis.abs_diff_eq(DVec2::new(-1., 0.), 1e-9)); + } + + #[test] + fn scales_keep_the_item_origin() { + let original = DAffine2::from_translation(DVec2::new(5., 7.)); + let scaled = transforms(&scale(colors(&[original; 2]), 1., 3., 0.5, false)); + + assert_eq!(scaled[0], original); + assert_eq!(scaled[1], DAffine2::from_scale_angle_translation(DVec2::splat(3.), 0., original.translation)); + } + + #[test] + fn extreme_biases_stay_within_the_range() { + for bias in [0., 1.] { + for transform in transforms(&scale(colors(&[DAffine2::IDENTITY; 64]), 1., 2., bias, true)) { + let factor = transform.matrix2.x_axis.length(); + assert!((1. ..=2.).contains(&factor), "bias {bias} gave scale {factor}"); + } + } + } +} diff --git a/node-graph/nodes/vector/src/generator_nodes.rs b/node-graph/nodes/vector/src/generator_nodes.rs index 12697de4547..c381fb1287b 100644 --- a/node-graph/nodes/vector/src/generator_nodes.rs +++ b/node-graph/nodes/vector/src/generator_nodes.rs @@ -459,10 +459,93 @@ fn grid( .into_item()) } +/// Draws paths by following a string of turtle commands, like the ones an **L-System** grows. `F` and `G` move forward a step while drawing, `f` and `g` move without drawing, `+` and `-` turn left and right, `|` turns around, and `[` and `]` begin and end a branch. +/// +/// A number in parentheses gives one command its own amount, like `F(25)` or `+(30)`, and a second number on `F` or `G` is the width it draws to, like `F(25, 3)`. +/// +/// `H` and `h` go half a step, drawing or not. `"` and `_` multiply and divide the step from then on, as `;` and `@` do the angle and `!` and `?` the width. `~` turns a random amount, and `T` bends the heading toward the ground. `'` and `#` count up two numbers, U and V, for coloring or anything else downstream. +/// +/// `{` begins a filled shape, `.` adds an anchor where the turtle stands, and `}` closes it. Outside a shape, `.` places a point on no path instead, for **Vector to Points** and **Transform** to copy shapes onto. Its kind is 1, or a number like `.(2)` gives another, so different shapes can go to different points. +/// +/// Each point records its branch depth, distance traveled, heading, width, step length, UV, and kind as attributes. Drawn points have a kind of 0. +#[node_macro::node(category("String"), icon("NodeTurtlePath"))] +fn turtle_path( + _: impl Ctx, + /// The commands for the turtle to follow, starting at the origin and facing up. Symbols without a meaning are skipped. + commands: Item, + /// How far each step forward moves, unless a command gives its own distance like `F(25)`. + #[unit(" px")] + #[default(10.)] + step: Item, + /// The factor that `"` multiplies the step by and `_` divides it by, unless a command gives its own like `"(0.8)`. + #[unit("x")] + #[default(0.5)] + step_scale: Item, + /// How much longer or shorter each step may randomly be, as a fraction of its length. + #[range] + #[hard(0..1)] + step_jitter: Item, + /// How far `+` and `-` turn, unless a command gives its own angle like `+(30)`. + #[unit("°")] + #[default(90.)] + angle: Item, + /// The factor that `;` multiplies the angle by and `@` divides it by, unless a command gives its own like `;(0.8)`. + #[unit("x")] + #[default(0.5)] + angle_scale: Item, + /// How much wider or narrower each turn by `+` and `-` may randomly be, as a fraction of its angle. + #[range] + #[hard(0..1)] + angle_jitter: Item, + /// The width the turtle starts drawing with. + #[unit(" px")] + #[default(1.)] + width: Item, + /// The factor that `!` multiplies the width by and `?` divides it by, unless a command gives its own like `!(0.8)`. + #[unit("x")] + #[default(0.5)] + width_scale: Item, + /// How much thicker or thinner each line's width may randomly be, as a fraction of it. + #[range] + #[hard(0..1)] + width_jitter: Item, + /// How far `T` bends a sideways heading toward the ground like branches sagging under gravity, and less the nearer it is to vertical, unless a command gives its own amount like `T(5)`. A negative amount bends toward the sky instead. + #[unit("°")] + #[default(10.)] + #[range] + #[soft(-90..90)] + tropism: Item, + /// How much `'` and `#` count up U and V, unless a command gives its own amount like `'(2)`. + #[name("UV Increment")] + #[default(1., 1.)] + #[widget(ParsedWidgetOverride::Custom = "vec2_uv")] + uv_increment: Item, + /// Seed to determine unique variations on the random turns of `~` and the step, angle, and width jitters. + #[hard(0..)] + seed: Item, +) -> Item { + let settings = crate::turtle::TurtleSettings { + step: *step.element(), + step_scale: *step_scale.element(), + step_jitter: *step_jitter.element(), + angle: *angle.element(), + angle_scale: *angle_scale.element(), + angle_jitter: *angle_jitter.element(), + width: *width.element(), + width_scale: *width_scale.element(), + width_jitter: *width_jitter.element(), + tropism: *tropism.element(), + uv_increment: *uv_increment.element(), + seed: *seed.element() as u64, + }; + + crate::turtle::turtle_path(commands.element(), &settings) +} + #[cfg(test)] mod tests { use super::*; - use core_types::list::ATTR_SMOOTH; + use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_KIND, ATTR_SMOOTH, ATTR_STEP, ATTR_UV, ATTR_WIDTH}; use kurbo::ParamCurve; use vector_types::vector::misc::point_to_dvec2; use vector_types::vector::shared_paths_from_item_attributes; @@ -706,4 +789,236 @@ mod tests { assert!(anchors.iter().all(|anchor| (anchor.length() - 25.).abs() < 1e-9)); } } + + fn turtle(commands: &str) -> Item { + turtle_varied(commands, 0., 0) + } + + fn turtle_varied(commands: &str, step_jitter: f64, seed: i64) -> Item { + let text = |text: &str| item(text.to_string()); + turtle_path( + (), + text(commands), + item(10.), + item(0.5), + item(step_jitter), + item(90.), + item(0.5), + item(0.), + item(1.), + item(0.5), + item(0.), + item(10.), + item(DVec2::ONE), + item(seed), + ) + } + + fn positions(drawing: &Item) -> Vec { + drawing.element().positions().collect() + } + + /// Each path's pool references and whether it closes. + fn turtle_runs(drawing: &Item) -> Vec<(Vec, bool)> { + let paths = shared_paths_from_item_attributes(drawing); + paths.iter_element_values().map(|path| (path.references().collect(), path.is_closed())).collect() + } + + fn point_attributes(drawing: &Item, key: &str) -> Vec { + drawing.element().0.iter_attribute_values::(key).map(|values| values.copied().collect()).unwrap_or_default() + } + + #[test] + fn turtle_square_closes_on_its_start() { + let square = turtle("F+F+F+F"); + + assert_eq!(turtle_runs(&square), [(vec![0, 1, 2, 3, 0], true)]); + assert_eq!( + square.element().positions().collect::>(), + [DVec2::ZERO, DVec2::new(0., -10.), DVec2::new(-10., -10.), DVec2::new(-10., 0.)] + ); + + // Drawing on after closing leaves the square closed and starts a new path from its first point + assert_eq!(turtle_runs(&turtle("F+F+F+F+F")), [(vec![0, 1, 2, 3, 0], true), (vec![0, 4], false)]); + } + + #[test] + fn turtle_branches_weld_to_one_trunk() { + let tree = turtle("F[+F]F"); + + // The trunk stays one run through the junction, where the branch begins + assert_eq!(turtle_runs(&tree), [(vec![0, 1, 3], false), (vec![1, 2], false)]); + assert_eq!(point_attributes::(&tree, ATTR_DEPTH), [0, 0, 1, 0]); + assert_eq!(point_attributes::(&tree, ATTR_DISTANCE), [0., 10., 20., 20.]); + assert_eq!(point_attributes::(&tree, ATTR_HEADING), [-90., -90., 180., -90.]); + + // Branches leaving before anything is drawn still share their starting point + assert_eq!(turtle_runs(&turtle("[+F][-F]F")), [(vec![0, 1], false), (vec![0, 2], false), (vec![0, 3], false)]); + } + + #[test] + fn turtle_moves_break_paths_and_parameters_override_amounts() { + let drawing = turtle("FfF(25)+(45)F"); + + assert_eq!(turtle_runs(&drawing), [(vec![0, 1], false), (vec![2, 3, 4], false)]); + let positions: Vec = drawing.element().positions().collect(); + assert_eq!(positions[3], DVec2::new(0., -45.)); + assert!((positions[4] - DVec2::new(-10. * 0.5_f64.sqrt(), -45. - 10. * 0.5_f64.sqrt())).length() < 1e-9); + + // `g` moves just like `f` + let moved = turtle("FgF"); + assert_eq!(turtle_runs(&moved), [(vec![0, 1], false), (vec![2, 3], false)]); + assert_eq!(moved.element().positions().nth(2), Some(DVec2::new(0., -20.))); + } + + #[test] + fn turtle_width_scales_and_is_restored_after_a_branch() { + let drawing = turtle("F[!(3)F]F"); + assert_eq!(point_attributes::(&drawing, ATTR_WIDTH), [1., 1., 3., 1.]); + + // The width halves and doubles back, and dividing by zero leaves it alone + assert_eq!(point_attributes::(&turtle("F!F?F?(0)F"), ATTR_WIDTH), [1., 1., 0.5, 1., 1.]); + + // `G` draws like `F`, and other letters mean nothing to the turtle + assert_eq!(turtle_runs(&turtle("FGAF")), [(vec![0, 1, 2, 3], false)]); + assert_eq!(point_attributes::(&turtle(""), ATTR_WIDTH), Vec::::new()); + assert!(turtle("").element().0.iter_attribute_values::(ATTR_WIDTH).is_some(), "an empty drawing still has the attribute"); + + // A draw's second number stamps only the point it draws to + assert_eq!(point_attributes::(&turtle("F(10, 3)F"), ATTR_WIDTH), [1., 3., 1.]); + } + + #[test] + fn turtle_half_steps_and_scaled_steps() { + let halves = turtle("HhH"); + assert_eq!(turtle_runs(&halves), [(vec![0, 1], false), (vec![2, 3], false)]); + assert_eq!(positions(&halves), [DVec2::ZERO, DVec2::new(0., -5.), DVec2::new(0., -10.), DVec2::new(0., -15.)]); + + // The step halves and doubles back, and dividing by zero leaves it alone + let ys: Vec = positions(&turtle("F\"F_F_(0)F")).iter().map(|position| position.y).collect(); + assert_eq!(ys, [0., -10., -15., -25., -35.]); + + // The angle halves to 45°, then doubles back to 90° once the branch ends + let angled = positions(&turtle("[;+F]+F")); + assert!((angled[1] - DVec2::new(-10. * 0.5_f64.sqrt(), -10. * 0.5_f64.sqrt())).length() < 1e-9); + assert_eq!(angled[2], DVec2::new(-10., 0.)); + } + + #[test] + fn turtle_bends_toward_the_ground_without_passing_it() { + // Heading left, the turtle bends 10° down + let bent = positions(&turtle("+T(10)F")); + assert!((bent[1] - 10. * DVec2::from_angle(170_f64.to_radians())).length() < 1e-9); + + // A vertical heading doesn't bend, and a strong pull stops at straight down + assert_eq!(positions(&turtle("T(10)F"))[1], DVec2::new(0., -10.)); + assert_eq!(positions(&turtle("+T(1000)F"))[1], DVec2::new(0., 10.)); + } + + #[test] + fn turtle_closes_polygons_through_recorded_anchors() { + let square = turtle("{.f.+f.+f.}"); + assert_eq!(turtle_runs(&square), [(vec![0, 1, 2, 3, 0], true)]); + assert_eq!(positions(&square), [DVec2::ZERO, DVec2::new(0., -10.), DVec2::new(-10., -10.), DVec2::new(-10., 0.)]); + + // A last anchor back on the first isn't repeated, and too few anchors make no shape + assert_eq!(turtle_runs(&turtle("{.f.+f.+f.+f.}")), [(vec![0, 1, 2, 3, 0], true)]); + assert_eq!(positions(&turtle("{.f.}")), []); + + // A shape the commands leave open still closes, as if its `}` came last + assert_eq!(turtle_runs(&turtle("{.f.+f.+f.")), [(vec![0, 1, 2, 3, 0], true)]); + } + + #[test] + fn turtle_counts_up_uv() { + let drawing = turtle("F'F#F'(2)F"); + let expected = [DVec2::ZERO, DVec2::ZERO, DVec2::new(1., 0.), DVec2::new(1., 1.), DVec2::new(3., 1.)]; + assert_eq!(point_attributes::(&drawing, ATTR_UV), expected); + } + + #[test] + fn turtle_places_points_of_a_kind_on_no_path() { + let drawing = turtle("F[+F.(2)]\"F."); + + // The placed points 3 and 5 join no path, but carry the turtle's state and their kind + assert_eq!(turtle_runs(&drawing), [(vec![0, 1, 4], false), (vec![1, 2], false)]); + assert_eq!(positions(&drawing)[3], DVec2::new(-10., -10.)); + assert_eq!(positions(&drawing)[5], DVec2::new(0., -15.)); + assert_eq!(point_attributes::(&drawing, ATTR_KIND), [0, 0, 0, 2, 0, 1]); + assert_eq!(point_attributes::(&drawing, ATTR_DEPTH), [0, 0, 1, 1, 0, 0]); + assert_eq!(point_attributes::(&drawing, ATTR_HEADING)[3], 180.); + assert_eq!(point_attributes::(&drawing, ATTR_STEP), [10., 10., 10., 10., 5., 5.]); + + // Inside a shape, `.` adds an anchor, but a branch saved there can return after the shape closes to place a point + let shape = turtle("{.f.[+f.+f.}]."); + assert_eq!(turtle_runs(&shape), [(vec![0, 1, 2, 3, 0], true)]); + assert_eq!(positions(&shape)[4], DVec2::new(0., -10.)); + assert_eq!(point_attributes::(&shape, ATTR_KIND), [0, 0, 0, 0, 1]); + + // Several spots saved inside a shape come back last first, one per `]` + let saved_twice = turtle("{.f.[+f.[+f.}].]."); + assert_eq!(turtle_runs(&saved_twice), [(vec![0, 1, 2, 3, 0], true)]); + assert_eq!(positions(&saved_twice)[4..], [DVec2::new(-10., -10.), DVec2::new(0., -10.)]); + assert_eq!(point_attributes::(&saved_twice, ATTR_KIND), [0, 0, 0, 0, 1, 1]); + assert_eq!(point_attributes::(&saved_twice, ATTR_DEPTH), [0, 0, 1, 2, 1, 0]); + } + + #[test] + fn turtle_randomness_follows_the_seed() { + let wander = |seed: i64| positions(&turtle_varied("~(30)F~(30)F", 0.2, seed)); + assert_eq!(wander(3), wander(3)); + assert_ne!(wander(3), wander(4)); + + // The first step stays within 20% of its length and 30° of straight up + let first = wander(3)[1]; + assert!((8. ..=12.).contains(&first.length())); + assert!(first.angle_to(DVec2::NEG_Y).abs() <= 30_f64.to_radians() + 1e-9); + assert!((0..8).any(|seed| (wander(seed)[1].length() - 10.).abs() > 1.), "some seed should stray past 10%"); + } + + #[test] + fn turtle_jitters_turns_and_widths() { + let jittered = |seed: u64| { + let settings = crate::turtle::TurtleSettings { + angle_jitter: 0.5, + width_jitter: 0.5, + seed, + ..Default::default() + }; + crate::turtle::turtle_path("F+F", &settings) + }; + let turn = |seed: u64| { + let points = positions(&jittered(seed)); + (points[1] - points[0]).angle_to(points[2] - points[1]).to_degrees().abs() + }; + + // A 90° turn stays within half of itself either way, and so does the width each line draws to + assert!((0..8).all(|seed| (45. - 1e-9..=135. + 1e-9).contains(&turn(seed)))); + assert!((0..8).any(|seed| (turn(seed) - 90.).abs() > 10.), "some seed should turn well off 90°"); + let widths: Vec = (0..8).flat_map(|seed| point_attributes::(&jittered(seed), ATTR_WIDTH)[1..].to_vec()).collect(); + assert!(widths.iter().all(|width| (0.5..=1.5).contains(width))); + assert!(widths.iter().any(|width| (width - 1.).abs() > 0.1), "some seed should vary the width"); + } + + #[test] + fn turtle_jitters_grow_gradually_and_leave_random_turns_alone() { + let drawn = |step_jitter: f64, angle_jitter: f64, width_jitter: f64| { + let settings = crate::turtle::TurtleSettings { + step_jitter, + angle_jitter, + width_jitter, + seed: 3, + ..Default::default() + }; + positions(&crate::turtle::turtle_path("~F+F~F", &settings)) + }; + let unjittered = drawn(0., 0., 0.); + + // Width moves no points, so turning it up keeps the `~` turns as they were + assert_eq!(drawn(0., 0., 0.5), unjittered); + + // Barely turning up the step and angle jitters barely moves the points + let nudged = drawn(1e-6, 1e-6, 0.); + assert!(nudged.iter().zip(&unjittered).all(|(nudged, unjittered)| nudged.distance(*unjittered) < 1e-3)); + } } diff --git a/node-graph/nodes/vector/src/grid_topology.rs b/node-graph/nodes/vector/src/grid_topology.rs index 9f7ceba2148..049d2e2ce13 100644 --- a/node-graph/nodes/vector/src/grid_topology.rs +++ b/node-graph/nodes/vector/src/grid_topology.rs @@ -179,6 +179,7 @@ impl Lattice { GridTopology::PointsOnly => return self.points_only(), GridTopology::Serpentine => self.serpentine(), GridTopology::HilbertCurve => self.hilbert_curve(), + GridTopology::MooreCurve => self.moore_curve(), GridTopology::Spiral => self.spiral(), GridTopology::Loop => match self.loop_route() { Some(route) => vec![GridPath::closed(route)], @@ -413,13 +414,17 @@ impl Lattice { pieces.into_iter().filter(|piece| piece.len() > 1).map(GridPath::open).collect() } - /// The generalized Hilbert curve through the points the rows reach, so the Symmetric shapes leave out the same points Rows Only does. - fn hilbert_curve(&self) -> Vec { - let full_rows = if self.grid_type == GridType::IsometricSymmetricMinusOne { + /// How many rows reach across every column, leaving out the extra points of the Symmetric shapes just as Rows Only does. + fn full_rows(&self) -> i64 { + if self.grid_type == GridType::IsometricSymmetricMinusOne { (self.rows - 1).max(0) } else { self.rows - }; + } + } + + /// The points along a route through the full rows, given as the column and row of each step. + fn along_full_rows(&self, route: Vec<(i64, i64)>) -> Vec { let height = |x: i64, y: i64| { if !self.isometric() || x % 2 == 0 { 2 * y @@ -430,8 +435,20 @@ impl Lattice { } }; - let points = gilbert_curve(self.columns, full_rows).into_iter().filter_map(|(x, y)| self.at((x, height(x, y)))).collect(); - vec![GridPath::open(points)] + route.into_iter().filter_map(|(x, y)| self.at((x, height(x, y)))).collect() + } + + /// The generalized Hilbert curve through the points the full rows reach. + fn hilbert_curve(&self) -> Vec { + vec![GridPath::open(self.along_full_rows(gilbert_curve(self.columns, self.full_rows())))] + } + + /// The generalized Moore curve through the same points as the Hilbert curve, falling back to that open curve where a single row or column leaves no room for a loop. + fn moore_curve(&self) -> Vec { + match generalized_moore_curve(self.columns, self.full_rows()) { + Some(route) => vec![GridPath::closed(self.along_full_rows(route))], + None => self.hilbert_curve(), + } } /// The corners around each cell between two neighboring columns, row by row: top left, top right, bottom right, then bottom left, where the grid may lack any of them. @@ -747,8 +764,8 @@ impl Lattice { comb(&self.column_points) } else { let mut route = self.column_points[0].clone(); - for x in 1..columns - 2 { - let below_top = &self.column_points[x][1..]; + for (x, column) in self.column_points.iter().enumerate().take(columns - 2).skip(1) { + let below_top = &column[1..]; if x % 2 == 1 { route.extend(below_top.iter().rev()); } else { @@ -829,55 +846,84 @@ fn comb(lines: &[Vec]) -> Vec { /// The generalized Hilbert curve (the Gilbert curve) through every cell of a rectangle, matching the Hilbert curve on power-of-two squares. /// It takes one diagonal step when the long side is odd and the short side even, where no route along the edges can link its two corners. fn gilbert_curve(width: i64, height: i64) -> Vec<(i64, i64)> { - fn generate(order: &mut Vec<(i64, i64)>, (x, y): (i64, i64), (ax, ay): (i64, i64), (bx, by): (i64, i64)) { - let (width, height) = ((ax + ay).abs(), (bx + by).abs()); - let (step_ax, step_ay, step_bx, step_by) = (ax.signum(), ay.signum(), bx.signum(), by.signum()); - - // A single row or column is walked straight through - if height == 1 || width == 1 { - let ((step_x, step_y), count) = if height == 1 { ((step_ax, step_ay), width) } else { ((step_bx, step_by), height) }; - order.extend((0..count).map(|i| (x + step_x * i, y + step_y * i))); - return; - } - - let (mut ax_half, mut ay_half, mut bx_half, mut by_half) = (ax.div_euclid(2), ay.div_euclid(2), bx.div_euclid(2), by.div_euclid(2)); - let (width_half, height_half) = ((ax_half + ay_half).abs(), (bx_half + by_half).abs()); - - if 2 * width > 3 * height { - // Long rectangles split in two along their length - if width_half % 2 == 1 && width > 2 { - (ax_half, ay_half) = (ax_half + step_ax, ay_half + step_ay); - } - generate(order, (x, y), (ax_half, ay_half), (bx, by)); - generate(order, (x + ax_half, y + ay_half), (ax - ax_half, ay - ay_half), (bx, by)); - } else { - // Others split into the Hilbert curve's up, across, and down thirds - if height_half % 2 == 1 && height > 2 { - (bx_half, by_half) = (bx_half + step_bx, by_half + step_by); - } - generate(order, (x, y), (bx_half, by_half), (ax_half, ay_half)); - generate(order, (x + bx_half, y + by_half), (ax, ay), (bx - bx_half, by - by_half)); - generate( - order, - (x + (ax - step_ax) + (bx_half - step_bx), y + (ay - step_ay) + (by_half - step_by)), - (-bx_half, -by_half), - (-(ax - ax_half), -(ay - ay_half)), - ); - } - } - let mut order = Vec::new(); if width > 0 && height > 0 { if width >= height { - generate(&mut order, (0, 0), (width, 0), (0, height)); + gilbert_section(&mut order, (0, 0), (width, 0), (0, height)); } else { - generate(&mut order, (0, 0), (0, height), (width, 0)); + gilbert_section(&mut order, (0, 0), (0, height), (width, 0)); } } order } +/// Appends the generalized Hilbert curve through the rectangle spanned by two axes from its corner at `(x, y)`, heading for the corner that the first axis leads to. +fn gilbert_section(order: &mut Vec<(i64, i64)>, (x, y): (i64, i64), (ax, ay): (i64, i64), (bx, by): (i64, i64)) { + let (width, height) = ((ax + ay).abs(), (bx + by).abs()); + let (step_ax, step_ay, step_bx, step_by) = (ax.signum(), ay.signum(), bx.signum(), by.signum()); + + // A single row or column is walked straight through + if height == 1 || width == 1 { + let ((step_x, step_y), count) = if height == 1 { ((step_ax, step_ay), width) } else { ((step_bx, step_by), height) }; + order.extend((0..count).map(|i| (x + step_x * i, y + step_y * i))); + return; + } + + let (mut ax_half, mut ay_half, mut bx_half, mut by_half) = (ax.div_euclid(2), ay.div_euclid(2), bx.div_euclid(2), by.div_euclid(2)); + let (width_half, height_half) = ((ax_half + ay_half).abs(), (bx_half + by_half).abs()); + + if 2 * width > 3 * height { + // Long rectangles split in two along their length + if width_half % 2 == 1 && width > 2 { + (ax_half, ay_half) = (ax_half + step_ax, ay_half + step_ay); + } + gilbert_section(order, (x, y), (ax_half, ay_half), (bx, by)); + gilbert_section(order, (x + ax_half, y + ay_half), (ax - ax_half, ay - ay_half), (bx, by)); + } else { + // Others split into the Hilbert curve's up, across, and down thirds + if height_half % 2 == 1 && height > 2 { + (bx_half, by_half) = (bx_half + step_bx, by_half + step_by); + } + gilbert_section(order, (x, y), (bx_half, by_half), (ax_half, ay_half)); + gilbert_section(order, (x + bx_half, y + by_half), (ax, ay), (bx - bx_half, by - by_half)); + gilbert_section( + order, + (x + (ax - step_ax) + (bx_half - step_bx), y + (ay - step_ay) + (by_half - step_by)), + (-bx_half, -by_half), + (-(ax - ax_half), -(ay - ay_half)), + ); + } +} + +/// The generalized Moore curve through every cell of a rectangle (two Gilbert curves, one through each half, joined at their corners beside the divide), or none if a side is too short to loop. +/// It matches the Moore curve on power-of-two squares and takes one diagonal step when both sides are odd, where no loop along the edges can pass through every cell. +fn generalized_moore_curve(width: i64, height: i64) -> Option> { + // Splitting the longer side keeps the halves closest to square + let transposed = height > width; + let (long, short) = if transposed { (height, width) } else { (width, height) }; + if short < 2 { + return None; + } + + // An odd short side needs each half to be an odd number of cells wide for its corners to link along the edges + let mut divide = long / 2; + if short % 2 == 1 && divide % 2 == 0 { + divide += 1; + } + + // Both halves are laid out in positive directions and mirrored into place, since halving negative sizes rounds the other way and can miss the corner to join + let half_route = |half_width: i64| { + let mut order = Vec::new(); + gilbert_section(&mut order, (0, 0), (0, short), (half_width, 0)); + order + }; + let first = half_route(divide).into_iter().map(|(x, y)| (divide - 1 - x, y)); + let second = half_route(long - divide).into_iter().map(|(x, y)| (divide + x, short - 1 - y)); + + Some(first.chain(second).map(|(x, y)| if transposed { (y, x) } else { (x, y) }).collect()) +} + /// Joins edges into the fewest trails that draw each edge once, each continuing as straight as possible through the points it passes. /// A connected group of edges becomes one closed trail if every point has an even number of edges, or else one open trail per pair of points with an odd number. /// Runs in O(edges) for the bounded number of edges at each point. @@ -1188,7 +1234,7 @@ mod tests { GridType::IsometricSymmetricPlusOne, GridType::IsometricSymmetricMinusOne, ]; - const TOPOLOGIES: [GridTopology; 14] = [ + const TOPOLOGIES: [GridTopology; 15] = [ GridTopology::Lines, GridTopology::Edges, GridTopology::FewestPaths, @@ -1198,6 +1244,7 @@ mod tests { GridTopology::PointsOnly, GridTopology::Serpentine, GridTopology::HilbertCurve, + GridTopology::MooreCurve, GridTopology::Spiral, GridTopology::Loop, GridTopology::Rings, @@ -1487,6 +1534,58 @@ mod tests { }); } + #[test] + fn moore_curve_steps_to_a_neighbor_except_once_diagonally_on_odd_by_odd_rectangles() { + for width in 2..=64_i64 { + for height in 2..=64_i64 { + let route = generalized_moore_curve(width, height).unwrap_or_default(); + + let mut visited = vec![false; (width * height) as usize]; + for &(x, y) in &route { + assert!((0..width).contains(&x) && (0..height).contains(&y), "{width}x{height}: ({x}, {y}) is outside"); + assert!(!std::mem::replace(&mut visited[(y * width + x) as usize], true), "{width}x{height}: ({x}, {y}) is visited twice"); + } + assert!(visited.iter().all(|&visited| visited), "{width}x{height}: a cell is missed"); + + let mut diagonals = 0; + for (&(ax, ay), &(bx, by)) in route.iter().zip(route.iter().cycle().skip(1)) { + match ((ax - bx).abs(), (ay - by).abs()) { + (0, 1) | (1, 0) => {} + (1, 1) => diagonals += 1, + step => panic!("{width}x{height}: the step from ({ax}, {ay}) spans {step:?}"), + } + } + assert_eq!(diagonals, usize::from(width % 2 == 1 && height % 2 == 1), "{width}x{height}"); + } + } + } + + #[test] + fn moore_curve_closes_through_the_hilbert_curve_points() { + each_lattice(GridTopology::MooreCurve, |lattice, case| { + let layout = lattice.layout(GridTopology::MooreCurve); + let path = &layout.paths[0]; + assert_eq!(path.closed, lattice.full_rows() >= 2, "{case}"); + + let mut distinct = path.points.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!(distinct.len(), path.points.len(), "{case}: a point is visited more than once"); + + let mut hilbert_points = lattice.layout(GridTopology::HilbertCurve).paths[0].points.clone(); + hilbert_points.sort_unstable(); + assert_eq!(distinct, hilbert_points, "{case}"); + + // Only grids with an odd number of both columns and rows need a step off the edges to close the loop + let leaps = path_steps(path).filter(|&(a, b)| !lattice.are_neighbors(a, b)).count(); + if lattice.grid_type == GridType::Rectangular { + assert_eq!(leaps, usize::from(lattice.columns % 2 == 1 && lattice.rows % 2 == 1), "{case}"); + } else { + assert!(leaps <= 1, "{case}: {leaps} steps follow no edge"); + } + }); + } + #[test] fn loop_closes_through_every_point() { each_lattice(GridTopology::Loop, |lattice, case| { diff --git a/node-graph/nodes/vector/src/lib.rs b/node-graph/nodes/vector/src/lib.rs index 3da8313a7f4..34bd10bec13 100644 --- a/node-graph/nodes/vector/src/lib.rs +++ b/node-graph/nodes/vector/src/lib.rs @@ -1,6 +1,7 @@ pub mod generator_nodes; mod grid_topology; pub mod merge_qr_squares; +mod turtle; pub mod vector_modification_nodes; mod vector_nodes; mod voronoi; diff --git a/node-graph/nodes/vector/src/turtle.rs b/node-graph/nodes/vector/src/turtle.rs new file mode 100644 index 00000000000..c165726f83d --- /dev/null +++ b/node-graph/nodes/vector/src/turtle.rs @@ -0,0 +1,419 @@ +use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_ID, ATTR_KIND, ATTR_STEP, ATTR_UV, ATTR_WIDTH, Item, List}; +use core_types::misc::parse_f64; +use glam::DVec2; +use graphic_types::Vector; +use rand::rngs::StdRng; +use rand::{RngExt, SeedableRng}; +use vector_types::vector::{CurveType, Path, PointId, SegmentId, SetVectorPaths, push_paths}; + +/// How close, as a fraction of the step just drawn, a draw must land on its path's first point to close the path there. +const CLOSURE_TOLERANCE: f64 = 1e-6; + +/// How far `~` may turn either way, unless a command gives its own limit like `~(30)`. +const RANDOM_TURN_LIMIT: f64 = 180.; + +/// The kind assigned to every drawn point, matching what points from elsewhere without a kind read as. +const DRAWN_KIND: i64 = 0; + +/// The kind of a point that `.` places outside a shape without a number of its own. +const PLACED_KIND: i64 = 1; + +/// The node's inputs, which the commands fall back to when they don't give their own numbers. +pub(crate) struct TurtleSettings { + pub step: f64, + pub step_scale: f64, + /// The most a step's length varies at random, as a fraction of it. + pub step_jitter: f64, + pub angle: f64, + pub angle_scale: f64, + /// The most a turn's angle varies at random, as a fraction of it. + pub angle_jitter: f64, + pub width: f64, + pub width_scale: f64, + /// The most the width a line draws to varies at random, as a fraction of it. + pub width_jitter: f64, + pub tropism: f64, + pub uv_increment: DVec2, + pub seed: u64, +} + +#[cfg(test)] +impl Default for TurtleSettings { + /// The node's default inputs. + fn default() -> Self { + Self { + step: 10., + step_scale: 0.5, + step_jitter: 0., + angle: 90., + angle_scale: 0.5, + angle_jitter: 0., + width: 1., + width_scale: 0.5, + width_jitter: 0., + tropism: 10., + uv_increment: DVec2::ONE, + seed: 0, + } + } +} + +/// The turtle's place, direction, and pen, which `[` saves and `]` restores. +#[derive(Clone, Copy)] +struct Turtle { + position: DVec2, + /// Degrees, with `0.` along +X and positive angles turning clockwise on screen. + heading: f64, + distance: f64, + depth: i64, + /// The length of a step, which `"` and `_` scale. + step: f64, + /// The angle of a turn, which `;` and `@` scale. + angle: f64, + /// The width of the line, which `!` and `?` scale. + width: f64, + /// The U and V numbers, which `'` and `#` count up. + uv: DVec2, + /// The drawing's slot for the point the turtle stands on, which a branch shares with its parent so both weld there. + anchor_slot: usize, + /// The run being drawn, as an index into the drawing's runs. + run: Option, +} + +impl Turtle { + fn turn(&mut self, degrees: f64) { + self.heading = (self.heading + degrees).rem_euclid(360.); + } + + /// Turns a sideways heading `tropism` degrees toward straight down, and less the nearer it is to vertical, without turning past it. + /// A negative tropism bends toward straight up instead. + fn bend_down(&mut self, tropism: f64) { + let target = if tropism >= 0. { 90. } else { 270. }; + let remaining = (target - self.heading + 180.).rem_euclid(360.) - 180.; + + // The sideways part of the heading, which is exactly zero when vertical + let sideways = direction(self.heading).x; + self.turn((tropism * sideways).clamp(-remaining.abs(), remaining.abs())); + } + + /// Moves forward regardless of the pen, counting the distance traveled. + fn advance(&mut self, length: f64) { + self.position += length * direction(self.heading); + self.distance += length.abs(); + } +} + +/// The unit vector a heading in degrees points along, exact for multiples of 90° so square lattices stay on whole numbers. +fn direction(heading: f64) -> DVec2 { + let quarter_turns = heading / 90.; + if quarter_turns.fract() == 0. { + return match (quarter_turns as i64).rem_euclid(4) { + 0 => DVec2::X, + 1 => DVec2::Y, + 2 => DVec2::NEG_X, + _ => DVec2::NEG_Y, + }; + } + + DVec2::from_angle(heading.to_radians()) +} + +/// Scales an amount by a random factor within `jitter` of 1, only drawing from the generator when there's variation to give. +fn vary(amount: f64, jitter: f64, rng: &mut StdRng) -> f64 { + if jitter == 0. { + return amount; + } + + amount * (1. + jitter * rng.random_range(-1. ..=1.)) +} + +/// A place the turtle has stood, which gains its point the first time something is drawn from it. +#[derive(Clone, Copy)] +enum AnchorSlot { + Drawn(u32), + /// The turtle as it arrived, whose state stamps the point once one is drawn. + Undrawn(Turtle), +} + +/// The points and path runs a turtle lays down, with each point's attributes alongside. +#[derive(Default)] +struct Drawing { + positions: Vec, + depths: Vec, + distances: Vec, + headings: Vec, + widths: Vec, + uvs: Vec, + steps: Vec, + kinds: Vec, + /// Pool indices of each run, in the order the runs began. + runs: Vec>, + anchor_slots: Vec, +} + +impl Drawing { + fn new_anchor_slot(&mut self, slot: AnchorSlot) -> usize { + self.anchor_slots.push(slot); + self.anchor_slots.len() - 1 + } + + /// Adds a point where the turtle stands, stamped with its state and a kind, and gives its pool index. + fn push_point(&mut self, turtle: &Turtle, kind: i64) -> u32 { + self.positions.push(turtle.position); + self.depths.push(turtle.depth); + self.distances.push(turtle.distance); + // Reported from -180° to 180°, so the starting heading up the screen reads as -90° + self.headings.push(180. - (180. - turtle.heading).rem_euclid(360.)); + self.widths.push(turtle.width); + self.uvs.push(turtle.uv); + self.steps.push(turtle.step); + self.kinds.push(kind); + + (self.positions.len() - 1) as u32 + } + + /// The point of the place the turtle stands, drawing it there if this is the first time it's needed. + fn anchor_point(&mut self, turtle: &Turtle) -> u32 { + let arrival = match self.anchor_slots.get(turtle.anchor_slot) { + Some(AnchorSlot::Drawn(anchor)) => return *anchor, + Some(AnchorSlot::Undrawn(arrival)) => *arrival, + None => { + log::error!("The turtle stands at a place the drawing has no slot for"); + *turtle + } + }; + + let anchor = self.push_point(&arrival, DRAWN_KIND); + if let Some(slot) = self.anchor_slots.get_mut(turtle.anchor_slot) { + *slot = AnchorSlot::Drawn(anchor); + } + anchor + } + + /// Draws a segment forward from the turtle, continuing its run or beginning one from the point it stands on. + /// The `width` stamps only the point drawn to, leaving the turtle's own width as it was. + fn draw(&mut self, turtle: &mut Turtle, length: f64, width: f64) { + let start = self.anchor_point(turtle); + let run = match turtle.run { + Some(run) => run, + None => { + self.runs.push(vec![start]); + self.runs.len() - 1 + } + }; + + turtle.advance(length); + + // Landing back on the run's first point closes the run there rather than adding a duplicate point + let first = self.runs[run][0]; + let closes = self.runs[run].len() >= 3 && turtle.position.distance(self.positions[first as usize]) <= CLOSURE_TOLERANCE * length.abs(); + let end = if closes { + turtle.position = self.positions[first as usize]; + first + } else { + self.push_point(&Turtle { width, ..*turtle }, DRAWN_KIND) + }; + + self.runs[run].push(end); + turtle.anchor_slot = self.new_anchor_slot(AnchorSlot::Drawn(end)); + + // A closed run is finished, so drawing on begins a new one from the point it closed on + turtle.run = if closes { None } else { Some(run) }; + } + + /// Moves the turtle forward without drawing, so its next draw begins a new run. + fn travel(&mut self, turtle: &mut Turtle, length: f64) { + turtle.advance(length); + turtle.run = None; + turtle.anchor_slot = self.new_anchor_slot(AnchorSlot::Undrawn(*turtle)); + } + + /// Adds a closed path through the places the turtle recorded with `.`, leaving out a last one that returns to the first. + fn add_polygon(&mut self, mut anchors: Vec) { + if let [first, .., before_last, last] = anchors.as_slice() + && last.position.distance(first.position) <= CLOSURE_TOLERANCE * last.position.distance(before_last.position) + { + anchors.pop(); + } + if anchors.len() < 3 { + return; + } + + let mut references: Vec = anchors.iter().map(|anchor| self.push_point(anchor, DRAWN_KIND)).collect(); + references.push(references[0]); + self.runs.push(references); + } + + /// Builds the vector, numbering the points and then the segments in the order they were drawn. + fn into_item(self) -> Item { + let point_count = self.positions.len(); + let mut vector = Vector(List::new_from_elements(self.positions)); + + if point_count > 0 { + let mut point_id = PointId::ZERO; + vector.0.set_attribute_values(ATTR_ID, (0..point_count).map(|_| point_id.next_id()).collect::>()); + } + vector.0.set_attribute_values(ATTR_DEPTH, self.depths); + vector.0.set_attribute_values(ATTR_DISTANCE, self.distances); + vector.0.set_attribute_values(ATTR_HEADING, self.headings); + vector.0.set_attribute_values(ATTR_WIDTH, self.widths); + vector.0.set_attribute_values(ATTR_UV, self.uvs); + vector.0.set_attribute_values(ATTR_STEP, self.steps); + vector.0.set_attribute_values(ATTR_KIND, self.kinds); + + let mut segment_id = SegmentId::ZERO; + let runs = self.runs.into_iter().filter(|references| references.len() > 1).map(|references| { + let ids = (1..references.len()).map(|_| segment_id.next_id()).collect(); + (CurveType::Linear, references, ids) + }); + let mut paths = List::::new(); + push_paths(&mut paths, runs); + + Item::new_from_element(vector).with_paths(paths) + } +} + +/// Splits a parenthesized parameter list off the front of the commands, giving its insides and the commands after it. +/// An unclosed list runs to the end of the commands. +fn split_parameters(commands: &str) -> (&str, &str) { + let mut nesting = 0; + for (index, character) in commands.char_indices() { + match character { + '(' => nesting += 1, + ')' => { + nesting -= 1; + if nesting == 0 { + return (&commands[1..index], &commands[index + 1..]); + } + } + _ => {} + } + } + + (&commands[1..], "") +} + +/// Follows turtle commands from the origin, facing up the screen, and gives the paths it draws. +pub(crate) fn turtle_path(commands: &str, settings: &TurtleSettings) -> Item { + let mut drawing = Drawing::default(); + let mut turtle = Turtle { + position: DVec2::ZERO, + heading: 270., + distance: 0., + depth: 0, + step: settings.step, + angle: settings.angle, + width: settings.width, + uv: DVec2::ZERO, + anchor_slot: 0, + run: None, + }; + turtle.anchor_slot = drawing.new_anchor_slot(AnchorSlot::Undrawn(turtle)); + let mut saved = Vec::new(); + + // Each source of randomness gets its own generator, seeded far from the others, so a jitter turned up from 0 changes the drawing gradually and leaves the rest alone + let generator = |source: u64| StdRng::seed_from_u64(settings.seed ^ source.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + let mut random_turn_rng = generator(0); + let mut step_jitter_rng = generator(1); + let mut angle_jitter_rng = generator(2); + let mut width_jitter_rng = generator(3); + + // The anchors recorded by `.` for each shape that `{` began and `}` hasn't yet closed, innermost last + let mut polygons: Vec> = Vec::new(); + + let mut remaining = commands; + while let Some(symbol) = remaining.chars().next() { + remaining = &remaining[symbol.len_utf8()..]; + + // A parenthesized list after a symbol belongs to it + let parameters = if remaining.starts_with('(') { + let (parameters, after) = split_parameters(remaining); + remaining = after; + parameters + } else { + "" + }; + let number = |index: usize| parameters.split(',').nth(index).and_then(|parameter| parse_f64(parameter.trim())); + + match symbol { + 'F' | 'G' => { + let length = vary(number(0).unwrap_or(turtle.step), settings.step_jitter, &mut step_jitter_rng); + let width = vary(number(1).unwrap_or(turtle.width), settings.width_jitter, &mut width_jitter_rng); + drawing.draw(&mut turtle, length, width); + } + 'f' | 'g' => { + let length = vary(number(0).unwrap_or(turtle.step), settings.step_jitter, &mut step_jitter_rng); + drawing.travel(&mut turtle, length); + } + 'H' => { + let length = vary(number(0).unwrap_or(turtle.step) / 2., settings.step_jitter, &mut step_jitter_rng); + let width = vary(number(1).unwrap_or(turtle.width), settings.width_jitter, &mut width_jitter_rng); + drawing.draw(&mut turtle, length, width); + } + 'h' => { + let length = vary(number(0).unwrap_or(turtle.step) / 2., settings.step_jitter, &mut step_jitter_rng); + drawing.travel(&mut turtle, length); + } + '+' => turtle.turn(-vary(number(0).unwrap_or(turtle.angle), settings.angle_jitter, &mut angle_jitter_rng)), + '-' => turtle.turn(vary(number(0).unwrap_or(turtle.angle), settings.angle_jitter, &mut angle_jitter_rng)), + '|' => turtle.turn(180.), + '~' => turtle.turn(number(0).unwrap_or(RANDOM_TURN_LIMIT) * random_turn_rng.random_range(-1. ..=1.)), + 'T' => turtle.bend_down(number(0).unwrap_or(settings.tropism)), + '"' => turtle.step *= number(0).unwrap_or(settings.step_scale), + '_' => { + let divisor = number(0).unwrap_or(settings.step_scale); + if divisor != 0. { + turtle.step /= divisor; + } + } + ';' => turtle.angle *= number(0).unwrap_or(settings.angle_scale), + '@' => { + let divisor = number(0).unwrap_or(settings.angle_scale); + if divisor != 0. { + turtle.angle /= divisor; + } + } + '!' => turtle.width *= number(0).unwrap_or(settings.width_scale), + '?' => { + let divisor = number(0).unwrap_or(settings.width_scale); + if divisor != 0. { + turtle.width /= divisor; + } + } + '\'' => turtle.uv.x += number(0).unwrap_or(settings.uv_increment.x), + '#' => turtle.uv.y += number(0).unwrap_or(settings.uv_increment.y), + '[' => { + saved.push(turtle); + turtle.depth += 1; + turtle.run = None; + } + ']' => { + if let Some(restored) = saved.pop() { + turtle = restored; + } + } + '{' => polygons.push(Vec::new()), + '.' => match polygons.last_mut() { + Some(anchors) => anchors.push(turtle), + // Outside a shape, the point joins no path, so it marks a position without drawing anything + None => { + let kind = number(0).map_or(PLACED_KIND, |kind| kind.round() as i64); + drawing.push_point(&turtle, kind); + } + }, + '}' => { + if let Some(anchors) = polygons.pop() { + drawing.add_polygon(anchors); + } + } + _ => {} + } + } + + // Shapes still open when the commands end close as if their `}` came last, innermost first + while let Some(anchors) = polygons.pop() { + drawing.add_polygon(anchors); + } + + drawing.into_item() +} diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index b311c7ff290..6a8de075eb6 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -1,16 +1,22 @@ -use core_types::list::{ATTR_GEOMETRY_CACHE, Item, List, NodeIdPath}; +use core_types::list::{ATTR_GEOMETRY_CACHE, Item, NodeIdPath}; use core_types::transform::BakeTransform; -use core_types::uuid::NodeId; use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx}; use glam::{DAffine2, DVec2}; use graphic_types::Vector; use vector_types::kurbo::BezPath; use vector_types::vector::{GeometryCache, VectorModification, edit_item_geometry, ensure_paths_attribute, shared_paths_from_item_attributes}; -/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. -#[node_macro::node(category(""), memoize)] -fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { - let mut vector = vector; +/// Holds the edits made with the Pen and Path tools, applying them to the incoming shape. +#[node_macro::node(category("Vector: Geometry"), icon("NodePath"), memoize, version(2))] +fn path( + _ctx: impl Ctx, + /// The original shape that edits made with the Pen and Path tools are applied to. + content: Item, + /// The edits made with the Pen and Path tools, stored as changes to points and segments. + modification: Item>, + #[node_path] node_path: Item, +) -> Item { + let mut vector = content; let modification = modification.into_element(); // Moving points leaves the paths as they are, so they stay shared with the incoming geometry instead of being copied @@ -39,16 +45,10 @@ fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item(ATTR_EDITOR_CLICK_TARGET); - // Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`), - // matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer. - let node_path = node_path.into_element().0; - let subgraph_path: List = { - let len = node_path.len(); - node_path.into_iter().take(len.saturating_sub(1)).collect() - }; - let existing = vector.attribute_cloned_or_default::(ATTR_EDITOR_LAYER_PATH).0; - let layer_path = if existing.is_empty() { subgraph_path } else { existing }; - vector.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path)); + // Trace a vector no layer has claimed back to this node for the editor's tools + if vector.attribute_cloned_or_default::(ATTR_EDITOR_LAYER_PATH).0.is_empty() { + vector.set_attribute(ATTR_EDITOR_LAYER_PATH, node_path.into_element()); + } vector } @@ -59,6 +59,7 @@ fn bake_transform(_ctx: impl Ctx, #[implement let mut content = content; if let Some(transform) = content.remove_attribute::(ATTR_TRANSFORM) { content.element_mut().bake_transform(&transform); + graphic_types::graphic::rebase_stamped_transforms(content.attributes_mut(), transform); } content @@ -67,7 +68,7 @@ fn bake_transform(_ctx: impl Ctx, #[implement #[cfg(test)] mod tests { use super::*; - use core_types::list::{ATTR_ID, ATTR_PATHS}; + use core_types::list::{ATTR_ID, ATTR_PATHS, List}; use vector_types::vector::{CurveType, PointId, SegmentId, VectorModificationType, paths_from_item_attributes, push_path}; // A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards @@ -81,7 +82,7 @@ mod tests { bezpath.close_path(); let drawn = Vector::item_from_bezpath(&bezpath); - let modified = path_modify((), drawn.clone(), Item::default(), Item::default()); + let modified = path((), drawn.clone(), Item::default(), Item::default()); assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn)); } @@ -106,7 +107,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: hub, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); let first_path = |item: &Item| paths_from_item_attributes(item).unwrap().element(0).unwrap().0.iter_element_values().copied().collect::>(); assert_eq!(first_path(&drawn), [0, 1, 2, 3, 0]); @@ -125,7 +126,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: corner, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(modified.element().0.element(1), Some(&DVec2::new(11., 0.))); assert!(std::ptr::eq(paths_from_item_attributes(&drawn).unwrap(), paths_from_item_attributes(&modified).unwrap())); @@ -149,7 +150,7 @@ mod tests { }); for modification in [VectorModification::default(), adds_a_point] { - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(paths_from_item_attributes(&modified).map(List::len), Some(0)); assert_eq!( diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 52076a8264f..5efbd400f4f 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -6,6 +6,7 @@ use core::hash::{Hash, Hasher}; use core_types::blending::BlendMode; use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::list::{ATTR_APPEARANCE, ATTR_ID, ATTR_PATHS, Item, ItemAttributeValues, List, ListDyn, NodeIdPath}; +use core_types::math::spread::spread_factors; use core_types::transform::{Footprint, Transform}; use core_types::uuid::NodeId; use core_types::{ @@ -15,12 +16,12 @@ use core_types::{ use core_types::{Interrupt, NodeError}; use glam::{DAffine2, DMat2, DVec2}; use graphic_types::Vector; -use graphic_types::graphic::{bake_paint_transforms, is_paint_present}; +use graphic_types::graphic::{bake_transform_into_attributes, is_paint_present}; use graphic_types::raster_types::{CPU, GPU, Raster}; -use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, stamp_coverage}; +use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, stamp_coverage, stamped_transform}; use kurbo::simplify::{SimplifyOptions, simplify_bezpath}; use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape}; -use rand::{Rng, SeedableRng}; +use rand::{RngExt, SeedableRng}; use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet}; use vector_types::GradientForm; @@ -78,7 +79,7 @@ fn next_working_segment_id(working: &WorkingVector) -> SegmentId { } /// Implemented for `List` types that contain vector items reachable via mutable access. -/// Used by the whole-collection Assign Colors node so it can apply to either `List` or `List`. +/// Used by the whole-collection Vary Fill Colors and Vary Stroke Colors nodes so they can apply to either `List` or `List`. trait VectorListIterMut { fn for_each_vector_list_mut(&mut self, f: impl FnMut(&mut List)); @@ -275,49 +276,87 @@ impl ExpandVectorItems for Graphic { } #[derive(Debug, thiserror::Error)] -pub enum AssignColorsError { +pub enum VaryColorsError { #[error("The gradient has no colors to assign")] EmptyGradient, } -/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient. -#[node_macro::node(category("Vector: Style"), icon("NodeAssignColors"), path(graphene_core::vector))] -fn assign_colors( +/// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient. +#[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2))] +fn vary_fill_colors( _: impl Ctx, - /// The content with vector paths to apply the fill and/or stroke style to. + /// The content with vector paths to apply the fill style to. #[implementations(List, List)] #[widget(ParsedWidgetOverride::Hidden)] content: T, - /// Whether to style the fill. - #[default(true)] - fill: Item, - /// Whether to style the stroke. - stroke: Item, /// The range of colors to select from. #[default(Color::BLACK, Color::WHITE)] - #[widget(ParsedWidgetOverride::Custom = "assign_colors_gradient")] + #[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_gradient")] gradient: Item, /// Whether to reverse the gradient. reverse: Item, /// Whether to randomize the color selection for each element from throughout the gradient. randomize: Item, /// Seed to determine unique variations on the randomized color selection. - #[widget(ParsedWidgetOverride::Custom = "assign_colors_seed")] + #[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_seed")] #[hard(0..)] seed: Item, /// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once. - #[widget(ParsedWidgetOverride::Custom = "assign_colors_repeat_every")] + #[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_repeat_every")] #[hard(0..)] repeat_every: Item, -) -> Result +) -> Result where T: VectorListIterMut + Send, { - let (fill, stroke, reverse, randomize) = (fill.into_element(), stroke.into_element(), reverse.into_element(), randomize.into_element()); - let (seed, repeat_every) = (seed.into_element(), repeat_every.into_element()); + vary_cover_colors(content, Cover::Fill, gradient, reverse, randomize, seed, repeat_every) +} - if (fill || stroke) && gradient.element().is_empty() { - return Err(AssignColorsError::EmptyGradient); +/// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient. +#[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector))] +fn vary_stroke_colors( + _: impl Ctx, + /// The content with vector paths to apply the stroke style to. + #[implementations(List, List)] + #[widget(ParsedWidgetOverride::Hidden)] + content: T, + /// The range of colors to select from. + #[default(Color::BLACK, Color::WHITE)] + #[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_gradient")] + gradient: Item, + /// Whether to reverse the gradient. + reverse: Item, + /// Whether to randomize the color selection for each element from throughout the gradient. + randomize: Item, + /// Seed to determine unique variations on the randomized color selection. + #[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_seed")] + #[hard(0..)] + seed: Item, + /// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once. + #[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_repeat_every")] + #[hard(0..)] + repeat_every: Item, +) -> Result +where + T: VectorListIterMut + Send, +{ + vary_cover_colors(content, Cover::Stroke, gradient, reverse, randomize, seed, repeat_every) +} + +/// Paints the fill or stroke of each vector element with its own color from along the gradient, for the Vary Fill Colors and Vary Stroke Colors nodes. +fn vary_cover_colors( + content: T, + cover: Cover, + gradient: Item, + reverse: Item, + randomize: Item, + seed: Item, + repeat_every: Item, +) -> Result { + let (reverse, randomize, seed, repeat_every) = (reverse.into_element(), randomize.into_element(), seed.into_element(), repeat_every.into_element()); + + if gradient.element().is_empty() { + return Err(VaryColorsError::EmptyGradient); } let mut content = content; @@ -331,42 +370,36 @@ where let gradient = if reverse { element.reversed(settings.cyclic) } else { element }; let evaluator = gradient.evaluator(settings); - let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64); + let mut factors = spread_factors(length, randomize, seed as u64, repeat_every as u64); - let mut i: usize = 0; content.for_each_vector_list_mut(|vector_list| { for index in 0..vector_list.len() { - let factor = match randomize { - true => rng.random::(), - false => match repeat_every { - 0 => i as f64 / (length - 1).max(1) as f64, - 1 => 0., - _ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64, - }, - }; + let factor = factors.next().unwrap_or_default(); let color = evaluator.evaluate(factor); let color_paint = Graphic::ColorList(List::new_from_element(color)); - if fill { - vector_list.with_attribute_mut_or_default::(ATTR_APPEARANCE, index, |appearance| { - if !appearance.set_paint_of(Cover::Fill, color_paint.clone()) { - appearance.replace_or_insert(Coverage::new_fill(), color_paint.clone(), CoverPlacement::Below); + match cover { + Cover::Fill => { + let transform = stamped_transform(vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, index)); + vector_list.with_attribute_mut_or_default::(ATTR_APPEARANCE, index, |appearance| { + if !appearance.set_paint_of(Cover::Fill, color_paint.clone()) { + appearance.replace_or_insert(Coverage::new_fill(), color_paint.clone(), transform, CoverPlacement::Below); + } + }) + } + // The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke + Cover::Stroke => { + if vector_list + .attribute::(ATTR_APPEARANCE, index) + .is_some_and(|appearance| appearance.has_cover(Cover::Stroke)) + { + vector_list.with_attribute_mut_or_default::(ATTR_APPEARANCE, index, |appearance| { + appearance.set_paint_of(Cover::Stroke, color_paint.clone()); + }); } - }); - } - // The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke - if stroke - && vector_list - .attribute::(ATTR_APPEARANCE, index) - .is_some_and(|appearance| appearance.has_cover(Cover::Stroke)) - { - vector_list.with_attribute_mut_or_default::(ATTR_APPEARANCE, index, |appearance| { - appearance.set_paint_of(Cover::Stroke, color_paint.clone()); - }); + } } - - i += 1; } }); @@ -522,13 +555,7 @@ where // The wire envelope is dropped for the same reason as in `fill` above let paint = paint.into_element(); - // The coverage records the stroke's authoring space, so the item transform is composed in. Its translation - // cancels out in every consumer, so it is cleared to let an otherwise-identity capture elide. - let mut coverage_stroke = stroke; - coverage_stroke.transform *= content.attribute_cloned_or_default::(ATTR_TRANSFORM); - coverage_stroke.transform.translation = DVec2::ZERO; - - stamp_coverage(&mut content, Coverage::new_stroke(&coverage_stroke), paint, CoverPlacement::Above); + stamp_coverage(&mut content, Coverage::new_stroke(&stroke), paint, CoverPlacement::Above); content } @@ -543,103 +570,6 @@ fn dash_pattern( Item::new_from_element(DashPattern::from(lengths)) } -#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Copy to Points"), path(core_types::vector))] -fn copy_to_points( - _: impl Ctx, - points: List, - /// Artwork to be copied and placed at each point. - #[expose] - #[implementations(List, List, List, List>, List, List)] - content: List, - /// Minimum range of randomized sizes given to each placed copy. - #[default(1)] - #[range] - #[soft(0..2)] - #[unit("x")] - random_scale_min: Item, - /// Maximum range of randomized sizes given to each placed copy. - #[default(1)] - #[range] - #[soft(0..2)] - #[unit("x")] - random_scale_max: Item, - /// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes). - #[range] - #[soft(-50..50)] - random_scale_bias: Item, - /// Seed to determine unique variations on all the randomized copy sizes. - #[hard(0..)] - random_scale_seed: Item, - /// Range of randomized angles given to each placed copy, in degrees ranging from furthest clockwise to counterclockwise. - #[unit("°")] - #[range] - #[soft(0..360)] - random_rotation: Item, - /// Seed to determine unique variations on all the randomized copy angles. - #[hard(0..)] - random_rotation_seed: Item, -) -> List { - let (random_scale_min, random_scale_max, random_scale_bias) = (random_scale_min.into_element(), random_scale_max.into_element(), random_scale_bias.into_element()); - let (random_scale_seed, random_rotation, random_rotation_seed) = (random_scale_seed.into_element(), random_rotation.into_element(), random_rotation_seed.into_element()); - - let mut result_list = List::new(); - - let random_scale_difference = random_scale_max - random_scale_min; - - for row in points.into_iter() { - let mut scale_rng = rand::rngs::StdRng::seed_from_u64(random_scale_seed as u64); - let mut rotation_rng = rand::rngs::StdRng::seed_from_u64(random_rotation_seed as u64); - - let do_scale = random_scale_difference.abs() > 1e-6; - let do_rotation = random_rotation.abs() > 1e-6; - - let points_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); - let row_paths = shared_paths_from_item_attributes(&row); - for point in row.element().anchor_positions(&row_paths) { - let translation = points_transform.transform_point2(point); - - let rotation = if do_rotation { - let degrees = (rotation_rng.random::() - 0.5) * random_rotation; - degrees / 360. * TAU - } else { - 0. - }; - - let scale = if do_scale { - if random_scale_bias.abs() < 1e-6 { - // Linear - random_scale_min + scale_rng.random::() * random_scale_difference - } else { - // Weighted (see ) - let random = scale_rng.random::(); - let scale_factor = if random_scale_bias > 0. { - // Rearranged as `b + log2(r + (1 - r) 2^-b)` so a large bias can't overflow `2^b`, with the log floored at `-b` where `2^-b` underflows - 1. + (random + (1. - random) * (-random_scale_bias).exp2()).log2().max(-random_scale_bias) / random_scale_bias - } else { - let horizontal_scale_factor = 1. - 2_f64.powf(random_scale_bias); - (1. - random * horizontal_scale_factor).log2() / random_scale_bias - }; - random_scale_min + scale_factor * random_scale_difference - } - } else { - random_scale_min - }; - - let transform = DAffine2::from_scale_angle_translation(DVec2::splat(scale), rotation, translation); - - for row_index in 0..content.len() { - let Some(mut row) = content.clone_item(row_index) else { continue }; - let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); - row.set_attribute(ATTR_TRANSFORM, transform * row_transform); - - result_list.push(row); - } - } - } - - result_list -} - #[node_macro::node(category("Vector: Path"), icon("NodeRoundCorners"), path(core_types::vector))] fn round_corners( _: impl Ctx, @@ -1224,6 +1154,7 @@ fn box_warp(_: impl Ctx, #[implementations(Graphic, Ve // Reset the transform since we've applied it directly to the points *row.element_mut() = result; row.set_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); + graphic_types::graphic::rebase_stamped_transforms(row.attributes_mut(), transform); } row })) @@ -1593,6 +1524,49 @@ fn points_to_vector( Item::new_from_element(vector).with_paths(List::::new()) } +/// Lists the positions of the anchor points in the vector content, as placed by its transform. Wiring this into the **Translation** of a **Transform** node places a copy of its content at each point. +/// +/// Each point keeps its attributes, so **Read Attribute** can read them alongside the positions. +#[node_macro::node(category("Vector: Point"), icon("NodeVectorToPoints"), name("Vector to Points"), path(core_types::vector))] +fn vector_to_points( + _: impl Ctx, + /// The vector content with anchor points to list the positions of. + content: Item, +) -> List { + let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); + let paths = shared_paths_from_item_attributes(&content); + let vector = content.element(); + + vector.anchor_indices(&paths).into_iter().filter_map(|index| placed_point(vector, index, transform)).collect() +} + +/// Lists the positions of the open ends in the vector content, where a path stops without meeting another, like the tips of a tree's branches. +/// +/// Each point keeps its attributes, so **Read Attribute** can read them alongside the positions. +#[node_macro::node(category("Vector: Point"), icon("NodeOpenEnds"), path(core_types::vector))] +fn open_ends( + _: impl Ctx, + /// The vector content with paths to find the open ends of. + content: Item, +) -> List { + let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); + let paths = shared_paths_from_item_attributes(&content); + let vector = content.element(); + + // An open end is the anchor of exactly one segment, unlike a point along a path or a junction + let connectivity = vector.connectivity(&paths); + (0..vector.point_count()) + .filter(|&index| connectivity.spokes(index as u32) == 1) + .filter_map(|index| placed_point(vector, index, transform)) + .collect() +} + +/// The pool point at `index` with its attributes, placed by the transform. +fn placed_point(vector: &Vector, index: usize, transform: DAffine2) -> Option> { + let (position, attributes) = vector.0.clone_item(index)?.into_parts(); + Some(Item::from_parts(transform.transform_point2(position), attributes)) +} + /// Creates a polyline from a series of vector points, replacing any existing segments that may already exist. #[node_macro::node(category("Vector: Path"), icon("NodePointsToPolyline"), name("Points to Polyline"), path(core_types::vector))] fn points_to_polyline(_: impl Ctx, #[implementations(Graphic, Vector)] points: Item, #[default(true)] closed: Item) -> Item { @@ -1928,7 +1902,7 @@ fn solidify_stroke_list(content: List) -> List { let (vector, attributes) = row.into_parts(); let appearance = attributes.get::(ATTR_APPEARANCE).cloned().unwrap_or_default(); - let Some(stroke) = appearance.first_coverage_of(Cover::Stroke).map(Coverage::stroke_params).filter(|stroke| stroke.weight != 0.) else { + let Some(stroke) = appearance.first_stroke_params().filter(|stroke| stroke.weight != 0.) else { return vec![Item::from_parts(vector, attributes)]; }; // List order is paint order: a stroke coverage before the first fill coverage paints below it @@ -2112,7 +2086,8 @@ pub fn combine_paths(_: impl Ctx, content: List) -> Item { let node_id = layer_path.iter_element_values().next_back().map(|node_id| node_id.0).unwrap_or_default(); let mut hasher = DefaultHasher::new(); - (index, node_id).hash(&mut hasher); + // Hash as u32 to avoid platform differences + (index as u32, node_id).hash(&mut hasher); let collision_hash_seed = hasher.finish(); let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index); @@ -2128,7 +2103,7 @@ pub fn combine_paths(_: impl Ctx, content: List) -> Item { attributes.insert_cloned_from(&source_attributes, ATTR_APPEARANCE); // Adopt the last input item's layer (if any) so the editor can also bucket clicks under a contributing child layer attributes.insert_cloned_from(&source_attributes, ATTR_EDITOR_LAYER_PATH); - bake_paint_transforms(&mut attributes, source_transform); + bake_transform_into_attributes(&mut attributes, source_transform); } attributes.set_paths(output_paths); @@ -3079,13 +3054,21 @@ fn morph( let (source_index, target_index) = (a.first_index_of(cover), b.first_index_of(cover)); // An unmatched stroke steps out at the midpoint, matching the stroke geometry, while an unmatched fill persists and fades - let coverage = match (source_index.and_then(|index| a.cover_at(index)), target_index.and_then(|index| b.cover_at(index))) { - (Some(source), Some(target)) if cover == Cover::Stroke => Coverage::new_stroke(&source.stroke_params().lerp(&target.stroke_params(), time)), - (Some(source), Some(target)) => (if time < 0.5 { source } else { target }).clone(), + let (source_transform, target_transform) = (source_index.map(|index| a.transform_at(index)), target_index.map(|index| b.transform_at(index))); + let (coverage, transform) = match (source_index.and_then(|index| a.cover_at(index)), target_index.and_then(|index| b.cover_at(index))) { + (Some(_), Some(_)) if cover == Cover::Stroke => { + let (Some(source), Some(target)) = (source_index.and_then(|index| a.stroke_params_at(index)), target_index.and_then(|index| b.stroke_params_at(index))) else { + continue; + }; + let stroke = source.lerp(&target, time); + (Coverage::new_stroke(&stroke), stroke.transform) + } + (Some(source), Some(_)) if time < 0.5 => (source.clone(), source_transform.unwrap_or_default()), + (Some(_), Some(target)) => (target.clone(), target_transform.unwrap_or_default()), (Some(_), None) if cover == Cover::Stroke && time >= 0.5 => continue, (None, Some(_)) if cover == Cover::Stroke && time < 0.5 => continue, - (Some(source), None) => source.clone(), - (None, Some(target)) => target.clone(), + (Some(source), None) => (source.clone(), source_transform.unwrap_or_default()), + (None, Some(target)) => (target.clone(), target_transform.unwrap_or_default()), (None, None) => continue, }; @@ -3097,7 +3080,7 @@ fn morph( .map(Item::into_element) .unwrap_or_default(); - result.replace_or_insert(coverage, paint, CoverPlacement::Above); + result.replace_or_insert(coverage, paint, transform, CoverPlacement::Above); } Some(result) @@ -4309,40 +4292,52 @@ mod test { } } #[test] - fn copy_to_points() { - let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY); - let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY); + fn vector_to_points() { + let square = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY); + let transform = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0., DVec2::new(5., 7.)); - let expected_points = { - let (vector, paths) = Vector::from_bezpath(&points); - vector.anchor_positions(&paths) - }; + let points = super::vector_to_points((), create_vector_item(square, transform)); - let copy_to_points = super::copy_to_points( - Footprint::default(), - vector_node_from_bezpath(points), - vector_node_from_bezpath(element), - Item::new_from_element(1.), - Item::new_from_element(1.), - Item::new_from_element(0.), - Item::new_from_element(0), - Item::new_from_element(0.), - Item::new_from_element(0), + let positions: Vec = points.iter_element_values().copied().collect(); + assert_eq!(positions, [DVec2::new(-15., -13.), DVec2::new(25., -13.), DVec2::new(25., 27.), DVec2::new(-15., 27.)]); + } + + #[test] + fn vector_to_points_and_open_ends_keep_point_attributes() { + use core_types::list::{ATTR_DEPTH, ATTR_HEADING, ATTR_KIND}; + + // A trunk with a branch to the left, placed 100 px to the right + let tree = crate::turtle::turtle_path("F[+F]F", &Default::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(100., 0.))); + + let points = super::vector_to_points((), tree.clone()); + assert_eq!(points.iter_element_values().count(), 4); + assert_eq!( + points.iter_attribute_values::(ATTR_DEPTH).map(|depths| depths.copied().collect::>()), + Some(vec![0, 0, 1, 0]) ); - let combined = List::new_from_item(super::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(copy_to_points)))); - let combined_paths = row_paths(&combined, 0); - let combined_copy_to_points = combined.element(0).unwrap(); - - assert_eq!(combined_copy_to_points.stroke_manipulator_groups(combined_paths).count(), expected_points.len()); - - for (index, (manipulator_groups, _)) in combined_copy_to_points.stroke_manipulator_groups(combined_paths).enumerate() { - let offset = expected_points[index]; - let manipulator_groups_anchors = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::>(); - assert_eq!( - &manipulator_groups_anchors, - &[offset + DVec2::NEG_ONE, offset + DVec2::new(1., -1.), offset + DVec2::ONE, offset + DVec2::new(-1., 1.),] - ); - } + + // The root and both tips, but not the junction where the branch leaves the trunk + let ends = super::open_ends((), tree); + let positions: Vec = ends.iter_element_values().copied().collect(); + assert_eq!(positions, [DVec2::new(100., 0.), DVec2::new(90., -10.), DVec2::new(100., -20.)]); + assert_eq!( + ends.iter_attribute_values::(ATTR_HEADING).map(|headings| headings.copied().collect::>()), + Some(vec![-90., 180., -90.]) + ); + + // A closed path has no open ends + let square = crate::turtle::turtle_path("F+F+F+F", &Default::default()); + assert_eq!(super::open_ends((), square).len(), 0); + + // A point placed by `.` outside a shape is listed with the anchors, but isn't an open end + let marked = crate::turtle::turtle_path("F.(3)", &Default::default()); + assert_eq!( + super::vector_to_points((), marked.clone()) + .iter_attribute_values::(ATTR_KIND) + .map(|kinds| kinds.copied().collect::>()), + Some(vec![0, 0, 3]) + ); + assert_eq!(super::open_ends((), marked).len(), 2); } fn convex_hull_of(bezpath: BezPath, transform: DAffine2, curvature: f64) -> Item { @@ -4747,8 +4742,13 @@ mod test { // The two endpoints list their covers in opposite paint orders, which pairing by position would cross let appearance = |fill: Color, stroke: Color, stroke_placement| { let mut appearance = Appearance::default(); - appearance.replace_or_insert(Coverage::new_fill(), Graphic::from(List::new_from_element(fill)), CoverPlacement::Above); - appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(4.)), Graphic::from(List::new_from_element(stroke)), stroke_placement); + appearance.replace_or_insert(Coverage::new_fill(), Graphic::from(List::new_from_element(fill)), DAffine2::IDENTITY, CoverPlacement::Above); + appearance.replace_or_insert( + Coverage::new_stroke(&Stroke::new(4.)), + Graphic::from(List::new_from_element(stroke)), + DAffine2::IDENTITY, + stroke_placement, + ); appearance }; @@ -4920,15 +4920,13 @@ mod test { // A rank-0 vector reaches the same per-list styling path as a vector list, rather than being skipped #[test] - fn assign_colors_reaches_rank_0_vector_graphics() { + fn vary_fill_colors_reaches_rank_0_vector_graphics() { let leaf = Graphic::Vector(Box::new(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)))); let content = List::new_from_element(leaf); - let styled = super::assign_colors( + let styled = super::vary_fill_colors( Footprint::default(), content, - Item::new_from_element(true), - Item::new_from_element(false), Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])), Item::new_from_element(false), Item::new_from_element(false), @@ -5278,25 +5276,38 @@ mod test { } #[test] - fn assign_colors_from_an_empty_gradient() { + fn vary_colors_from_an_empty_gradient() { let content = || List::new_from_item(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY))); - let assign = |fill: bool| { - super::assign_colors( - (), - content(), - item(fill), - item(false), - item(Gradient::from(Vec::::new())), - item(false), - item(false), - item(0), - item(0), - ) - }; + let empty = || item(Gradient::from(Vec::::new())); - assert!(matches!(assign(true), Err(AssignColorsError::EmptyGradient))); - // With neither the fill nor the stroke styled, the gradient goes unused - assert!(assign(false).is_ok()); + let fills = super::vary_fill_colors((), content(), empty(), item(false), item(false), item(0), item(0)); + let strokes = super::vary_stroke_colors((), content(), empty(), item(false), item(false), item(0), item(0)); + assert!(matches!(fills, Err(VaryColorsError::EmptyGradient))); + assert!(matches!(strokes, Err(VaryColorsError::EmptyGradient))); + } + + #[test] + fn vary_stroke_colors_recolors_only_existing_strokes() { + let rect = || vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)); + let mut stroked = Appearance::default(); + stroked.replace_or_insert( + Coverage::new_stroke(&Stroke::new(4.)), + Graphic::from(List::new_from_element(Color::BLACK)), + DAffine2::IDENTITY, + CoverPlacement::Above, + ); + let content: List = [rect().with_attribute(ATTR_APPEARANCE, stroked), rect()].into_iter().collect(); + + let styled = super::vary_stroke_colors((), content, item(Gradient::from(vec![Color::WHITE])), item(false), item(false), item(0), item(0)).unwrap(); + + let stroke_paint = styled + .attribute::(ATTR_APPEARANCE, 0) + .and_then(|appearance| appearance.first_paint_of(Cover::Stroke).cloned()); + assert_eq!(stroke_paint, Some(Graphic::ColorList(List::new_from_element(Color::WHITE)))); + assert!( + !styled.attribute::(ATTR_APPEARANCE, 1).is_some_and(|appearance| appearance.has_cover(Cover::Stroke)), + "an element without a stroke should not gain one" + ); } #[test] @@ -5309,17 +5320,4 @@ mod test { assert_eq!(solidified.element(0), Some(filled.element())); assert_eq!(solidified.attribute::(ATTR_APPEARANCE, 0), filled.attribute::(ATTR_APPEARANCE)); } - - #[test] - fn copy_to_points_with_a_large_scale_bias() { - let points = vector_node_from_bezpath(Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY)); - let content = vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)); - - let copies = super::copy_to_points((), points, content, item(1.), item(2.), item(2000.), item(0), item(0.), item(0)); - for index in 0..copies.len() { - let transform: DAffine2 = copies.attribute_cloned_or_default(ATTR_TRANSFORM, index); - let scale = transform.matrix2.x_axis.length(); - assert!((1. ..=2.).contains(&scale), "copy {index} has scale {scale}"); - } - } } diff --git a/node-graph/nodes/vector/src/voronoi.rs b/node-graph/nodes/vector/src/voronoi.rs index 54a15b3274f..334e7bf5f53 100644 --- a/node-graph/nodes/vector/src/voronoi.rs +++ b/node-graph/nodes/vector/src/voronoi.rs @@ -128,7 +128,7 @@ fn voronoi_cells_per_site(sites: &[DVec2]) -> Result<(Vec>>, V } // One Voronoi vertex per Delaunay triangle. - let circumcenters: Vec = triangles.chunks_exact(3).map(|t| circumcenter(sites[t[0]], sites[t[1]], sites[t[2]])).collect(); + let circumcenters: Vec = triangles.as_chunks::<3>().0.iter().map(|&[a, b, c]| circumcenter(sites[a], sites[b], sites[c])).collect(); // The convex hull polygon, which clips the diagram to a finite region. let hull: Vec = hull_indices.iter().map(|&i| sites[i]).collect(); diff --git a/node-graph/nodes/vectorize/Cargo.toml b/node-graph/nodes/vectorize/Cargo.toml index f906a16bafb..79e45bdd6d1 100644 --- a/node-graph/nodes/vectorize/Cargo.toml +++ b/node-graph/nodes/vectorize/Cargo.toml @@ -19,6 +19,7 @@ workspace = true core-types = { workspace = true } vector-types = { workspace = true } raster-types = { workspace = true } +raster-kernels = { workspace = true } graphic-types = { workspace = true } graphene-hash = { workspace = true } node-macro = { workspace = true } diff --git a/node-graph/nodes/vectorize/src/lib.rs b/node-graph/nodes/vectorize/src/lib.rs index 406021a060a..61915c3492b 100644 --- a/node-graph/nodes/vectorize/src/lib.rs +++ b/node-graph/nodes/vectorize/src/lib.rs @@ -5,10 +5,11 @@ pub use convert::{ATTR_OLLEV_REPEAT, RepeatStructure}; pub use slices::TraceSlot; use core_types::list::{Item, List}; -use core_types::runtime::{Clock, Runtime}; +use core_types::runtime::Runtime; use core_types::{ATTR_TRANSFORM, CacheHash, Ctx, Poll, RuntimeHandle, SourceId}; use glam::{DAffine2, DVec2}; use graphic_types::Graphic; +use raster_kernels::evaluate_raster_effects; use raster_types::{CPU, Raster}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::time::Duration; @@ -37,7 +38,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.; /// Traces an image into a stack of filled and stroked shapes, drawn bottom to top as an artist would layer them. /// /// The trace runs in slices, one per evaluation, showing the shapes traced so far until it is done. -#[node_macro::node(category("Raster"), memoize)] +#[node_macro::node(category("Raster"), icon("NodeVectorize"), memoize)] fn vectorize( _: impl Ctx, /// The image to trace. @@ -97,21 +98,17 @@ fn vectorize( } let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize); let runtime = runtime.element(); - let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE, runtime.clock()); + let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE); if let Poll::Partial(_) = state { // Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice - trace.ask_next(runtime.spawn(*source.element(), Box::pin(async {}))); + runtime.spawn(*source.element(), Box::pin(async {})); } state } /// Runs one slice of the trace held in `slot`, starting a new trace if `slot` holds none for these inputs. -#[allow(clippy::too_many_arguments)] -fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option, slot: &TraceSlot, slice: Duration, clock: &dyn Clock) -> Poll> { - let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = image.element(); - let (width, height) = (raster.width as usize, raster.height as usize); - if width == 0 || height == 0 { +fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option, slot: &TraceSlot, slice: Duration) -> Poll> { + if image.element().width == 0 || image.element().height == 0 { slot.clear(); return Poll::Final(List::new()); } @@ -121,7 +118,14 @@ fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: o (detail.to_bits(), tolerance.to_bits(), max_pixels).hash(&mut hasher); [stages.translucency, stages.strokes, stages.primitives, stages.effects, stages.instancing, stages.path_gradients].hash(&mut hasher); + // The image's effects are carried out once for the whole trace, rather than on each slice let start = || { + let image = evaluate_raster_effects(image.clone()); + let raster = image.element(); + let (width, height) = (raster.width as usize, raster.height as usize); + let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); + let pixels_to_document = image_transform * DAffine2::from_scale(DVec2::new(1. / width as f64, 1. / height as f64)); + let source = ollev::Image { pixels: ollev::Pixels::RgbaF32 { data: bytemuck::cast_slice(&raster.data), @@ -139,11 +143,10 @@ fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: o stages, ..Default::default() }; - ollev::Tracing::new(&source, &options) + ollev::Tracing::new(&source, &options).map(|tracing| (tracing, pixels_to_document)) }; - let pixels_to_document = image_transform * DAffine2::from_scale(DVec2::new(1. / width as f64, 1. / height as f64)); - slot.poll(hasher.finish(), slice, clock, start, |model| convert::model_to_graphic(model, pixels_to_document)) + slot.poll(hasher.finish(), slice, start, convert::model_to_graphic) } #[cfg(test)] @@ -154,7 +157,6 @@ mod test { use raster_types::Image; use std::sync::{Arc, Mutex}; use std::task::{Context, Waker}; - use std::time::Instant; /// An image of `width` by `height` pixels colored by `color` at each pixel's column and row. fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item> { @@ -164,14 +166,14 @@ mod test { /// One slice of `image` traced at default settings by the node holding `slot`. fn slice(image: &Item>, slot: &TraceSlot) -> Poll> { - trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE, &Instant::now()) + trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE) } /// The shapes traced from `image` at `detail` and `tolerance` by a node of its own, slice by slice. fn trace(image: &Item>, detail: f64, tolerance: f64) -> List { let slot = TraceSlot::default(); loop { - match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE, &Instant::now()) { + match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE) { Poll::Partial(_) => {} Poll::Final(traced) => return traced, state => panic!("the trace ended in {state:?}"), @@ -311,7 +313,7 @@ mod test { #[test] fn the_first_evaluation_shows_shapes() { let slot = TraceSlot::default(); - match trace_slice(&busy(256), 1., 1., ollev::Stages::ALL, None, &slot, Duration::from_millis(200), &Instant::now()) { + match trace_slice(&busy(256), 1., 1., ollev::Stages::ALL, None, &slot, Duration::from_millis(200)) { Poll::Partial(shown) => assert!(!shown.is_empty(), "the first partial result shows no shapes"), state => panic!("the first slice ended in {state:?}"), } @@ -341,8 +343,8 @@ mod test { /// A runtime whose tasks are collected, with `SOURCE` live. fn collecting_runtime() -> (Arc, AsyncRuntime) { let spawner = Arc::new(CollectSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(Instant::now())); - runtime.retain_sources(&[SOURCE]); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.update_sources(&[SOURCE]); (spawner, runtime) } @@ -391,16 +393,15 @@ mod test { assert!(generation > 0, "the trace took a single slice"); } - /// New inputs drop the former trace's request for its next slice, which then asks for no evaluation. + /// New inputs leave the former trace's request for its next slice, which bumps the generation along with the new trace's own. #[test] - fn new_inputs_drop_the_former_request_for_a_slice() { + fn new_inputs_ask_for_their_own_slice() { let (spawner, runtime) = collecting_runtime(); let slot = TraceSlot::default(); assert!(matches!(evaluate(&slot, &busy(96), &runtime), Poll::Partial(_))); assert!(matches!(evaluate(&slot, &busy(128), &runtime), Poll::Partial(_))); assert_eq!(spawner.drain(), 2); - assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)], "the dropped trace's request bumped the generation"); - assert!(runtime.take_bumped()); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]); } } diff --git a/node-graph/nodes/vectorize/src/slices.rs b/node-graph/nodes/vectorize/src/slices.rs index d3718ecc81a..158037be5d2 100644 --- a/node-graph/nodes/vectorize/src/slices.rs +++ b/node-graph/nodes/vectorize/src/slices.rs @@ -1,6 +1,7 @@ use core_types::Poll; use core_types::list::List; -use core_types::runtime::{AbortHandle, Clock}; +use core_types::runtime::Instant; +use glam::DAffine2; use graphic_types::Graphic; use ollev::model::Model; use std::ops::ControlFlow; @@ -24,55 +25,46 @@ struct Trace { tracing: Option, /// Why the trace failed, kept so the same inputs are not traced again. failed: Option, + /// Places the traced image's pixels in the document. + pixels_to_document: DAffine2, shown: List, /// The revision of the scene in `shown`. revision: Option, - /// The task requesting the next slice, aborted on drop so a replaced trace triggers no evaluation. - next: Option, -} - -impl Drop for Trace { - fn drop(&mut self) { - if let Some(next) = &self.next { - next.abort(); - } - } } impl TraceSlot { - /// Advances the trace of `inputs` by `slice`, replacing any trace of other inputs with one from `start`. + /// Advances the trace of `inputs` by `slice`, replacing any trace of other inputs with one from `start`, which also gives where the traced pixels lie. /// Returns the latest showable scene, partial until the trace is done. pub fn poll( &self, inputs: u64, slice: Duration, - clock: &dyn Clock, - start: impl FnOnce() -> Result, - convert: impl Fn(&Model) -> List, + start: impl FnOnce() -> Result<(ollev::Tracing, DAffine2), ollev::TraceError>, + convert: impl Fn(&Model, DAffine2) -> List, ) -> Poll> { // Taken out of the slot so a panicking slice leaves it empty let mut held = self.lock(); let mut trace = match held.take().filter(|trace| trace.inputs == inputs) { Some(trace) => trace, None => match start() { - Ok(tracing) => Trace { + Ok((tracing, pixels_to_document)) => Trace { inputs, tracing: Some(tracing), failed: None, + pixels_to_document, shown: List::new(), revision: None, - next: None, }, Err(error) => return Poll::fallback(List::new(), error), }, }; if let Some(tracing) = &mut trace.tracing { - let deadline = clock.now() + slice; - let step = tracing.step(|_| if clock.now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }); + let deadline = Instant::now() + slice; + let step = tracing.step(|_| if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }); match step { Ok(ollev::Step::Done(model)) => { - trace.shown = convert(&model); + trace.shown = convert(&model, trace.pixels_to_document); trace.tracing = None; } Err(error) => { @@ -84,7 +76,7 @@ impl TraceSlot { && Some(progress.revision()) != trace.revision && let Some(model) = progress.model() { - trace.shown = convert(&model); + trace.shown = convert(&model, trace.pixels_to_document); trace.revision = Some(progress.revision()); } } @@ -101,15 +93,7 @@ impl TraceSlot { state } - /// Keeps the task requesting the next slice, so dropping the trace aborts it. - pub fn ask_next(&self, next: AbortHandle) { - match self.lock().as_mut() { - Some(trace) => trace.next = Some(next), - None => next.abort(), - } - } - - /// Drops the slot's trace and its request for the next slice. + /// Drops the slot's trace. pub fn clear(&self) { self.lock().take(); } diff --git a/node-graph/preprocessor/Cargo.toml b/node-graph/preprocessor/Cargo.toml index e6670be6351..bae4d979467 100644 --- a/node-graph/preprocessor/Cargo.toml +++ b/node-graph/preprocessor/Cargo.toml @@ -30,3 +30,4 @@ dyn-any = { workspace = true } futures = { workspace = true } glam = { workspace = true } node-macro = { workspace = true } +document-loader = { workspace = true } diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index 2d7aeb5d7fb..80e94d3f873 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -1,6 +1,8 @@ #[macro_use] extern crate log; +mod value_types; + use graph_craft::Type; use graph_craft::application_io::resource::ResourceId; use graph_craft::document::value::*; @@ -23,6 +25,14 @@ fn producer_node_id(ident: &ProtoNodeIdentifier, key: impl Hash) -> NodeId { NodeId(hasher.finish()) } +fn substitute_network_id(identifier: &ProtoNodeIdentifier, compile_metadata: Option) -> NetworkId { + let mut hasher = DefaultHasher::new(); + "preprocessor substitute".hash(&mut hasher); + identifier.hash(&mut hasher); + compile_metadata.hash(&mut hasher); + NetworkId(hasher.finish()) +} + #[derive(Debug, Clone)] struct Substitution { node: DocumentNode, @@ -38,10 +48,21 @@ pub struct Preprocessor { impl Preprocessor { pub fn preprocess(&self, network: &mut NodeNetwork, resolve_resource: &dyn Fn(ResourceId) -> Option) -> Result<(), PreprocessorError> { - network.inline_definitions().map_err(PreprocessorError::Definition)?; + network.validate_definitions().map_err(PreprocessorError::Definition)?; self.insert_inject_scopes(network); + self.replace_inputs_with_producer_nodes(network, resolve_resource)?; - self.expand_network(network); + for definition in network.definitions.values_mut() { + self.replace_inputs_with_producer_nodes(definition, resolve_resource)?; + } + + let mut substitutes = HashMap::new(); + self.expand_network(network, &mut substitutes); + for definition in network.definitions.values_mut() { + self.expand_network(definition, &mut substitutes); + } + network.definitions.extend(substitutes); + Ok(()) } } @@ -84,8 +105,8 @@ impl Preprocessor { let id = producer_node_id(&platform_application_io::editor_api::IDENTIFIER, resource_id); let resource_node = DocumentNode { inputs: vec![ - NodeInput::scope(platform_application_io::application_io::IDENTIFIER), NodeInput::value(TaggedValue::ResourceHash(hash), false), + NodeInput::scope(platform_application_io::application_io::IDENTIFIER), ], implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::resource::IDENTIFIER), ..Default::default() @@ -118,35 +139,46 @@ impl Preprocessor { Ok(()) } - fn expand_network(&self, network: &mut NodeNetwork) { + /// Replaces each proto node that has a substitution with the table entry `substitutes` holds for its identifier and compile metadata. + fn expand_network(&self, network: &mut NodeNetwork, substitutes: &mut HashMap) { for node in network.nodes.values_mut() { - match &mut node.implementation { - DocumentNodeImplementation::Network(node_network) => self.expand_network(node_network), - DocumentNodeImplementation::ProtoNode(proto_node_identifier) => { - let compile_metadata = node.compile_metadata.take().or_else(|| self.compile_metadata.get(proto_node_identifier).copied()); - - if let Some(Substitution { node: new_node, wrapped_node_id }) = self.substitutions.get(proto_node_identifier) { - // Reconcile the document node's inputs with what the current node definition expects, - // since the saved document may have fewer or more inputs than the current version - while node.inputs.len() < new_node.inputs.len() { - node.inputs.push(new_node.inputs[node.inputs.len()].clone()); - } - node.inputs.truncate(new_node.inputs.len()); - - node.implementation = new_node.implementation.clone(); - - // Move the compile metadata to the wrapped node because networks are not allowed to have compile metadata - if let DocumentNodeImplementation::Network(network) = &mut node.implementation - && let Some(wrapped_node) = network.nodes.get_mut(wrapped_node_id) - { - wrapped_node.compile_metadata = compile_metadata; - } - } else { - node.compile_metadata = compile_metadata; - } + let identifier = match &mut node.implementation { + DocumentNodeImplementation::Network(node_network) => { + self.expand_network(node_network, substitutes); + continue; } - DocumentNodeImplementation::Extract | DocumentNodeImplementation::Definition(_) => (), + DocumentNodeImplementation::ProtoNode(proto_node_identifier) => proto_node_identifier.clone(), + DocumentNodeImplementation::Definition(_) => continue, + }; + let compile_metadata = node.compile_metadata.take().or_else(|| self.compile_metadata.get(&identifier).copied()); + + let Some(Substitution { node: new_node, wrapped_node_id }) = self.substitutions.get(&identifier) else { + node.compile_metadata = compile_metadata; + continue; + }; + + // Reconcile the document node's inputs with what the current node definition expects, + // since the saved document may have fewer or more inputs than the current version + while node.inputs.len() < new_node.inputs.len() { + node.inputs.push(new_node.inputs[node.inputs.len()].clone()); } + node.inputs.truncate(new_node.inputs.len()); + + let DocumentNodeImplementation::Network(substitute) = &new_node.implementation else { + node.implementation = new_node.implementation.clone(); + continue; + }; + + // Networks are not allowed to have compile metadata, so each set of compile metadata gets its own entry holding it on the wrapped node + let id = substitute_network_id(&identifier, compile_metadata); + substitutes.entry(id).or_insert_with(|| { + let mut substitute = substitute.clone(); + if let Some(wrapped_node) = substitute.nodes.get_mut(wrapped_node_id) { + wrapped_node.compile_metadata = compile_metadata; + } + substitute + }); + node.implementation = DocumentNodeImplementation::Definition(id); } } @@ -283,7 +315,6 @@ impl Preprocessor { call_argument: input_type.clone(), implementation: DocumentNodeImplementation::ProtoNode(id.clone()), visible: true, - skip_deduplication: false, ..Default::default() }; @@ -339,7 +370,6 @@ impl Preprocessor { generated: true, }), visible: true, - skip_deduplication: false, ..Default::default() }; @@ -394,6 +424,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp } RegistryValueSource::Scope(data) => return NodeInput::scope(*data), RegistryValueSource::SourceId => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId), + RegistryValueSource::NodePath => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath), }; // A ranked `Item` type prefers a bare `T` value (promoted at resolution), since bare values drive the Inspector widgets @@ -537,9 +568,10 @@ mod destructure_tests { // The multi-output node is substituted with a transient generated network: the struct as the hidden primary export, // followed by one export per field, each pulled out of the struct by that field's extractor node let node = network.nodes.get(&NodeId(0)).unwrap(); - let DocumentNodeImplementation::Network(generated) = &node.implementation else { + let DocumentNodeImplementation::Definition(generated) = &node.implementation else { panic!("The multi-output node should be substituted with a generated network") }; + let generated = &network.definitions[generated]; assert!(generated.generated, "The substituted network must be marked as generated so it stays out of node paths"); assert_eq!(generated.exports.len(), destructure.number_of_outputs()); @@ -592,9 +624,10 @@ mod destructure_tests { // With a `#[primary]` field there is no hidden primary output, so there's one export per field let node = network.nodes.get(&NodeId(0)).unwrap(); - let DocumentNodeImplementation::Network(generated) = &node.implementation else { + let DocumentNodeImplementation::Definition(generated) = &node.implementation else { panic!("The multi-output node should be substituted with a generated network") }; + let generated = &network.definitions[generated]; assert_eq!(generated.exports.len(), destructure.number_of_outputs()); for (field, export) in destructure.fields.iter().zip(&generated.exports) { let NodeInput::Node { node_id: extractor_id, .. } = export else { @@ -780,13 +813,15 @@ mod tests { ..Default::default() }; - Preprocessor::new().expand_network(&mut network); + let mut substitutes = HashMap::new(); + Preprocessor::new().expand_network(&mut network, &mut substitutes); let node = &network.nodes[&NodeId(0)]; assert_eq!(node.compile_metadata, None, "The network node replacing the substituted node should not keep its compile metadata"); - let DocumentNodeImplementation::Network(substitution) = &node.implementation else { + let DocumentNodeImplementation::Definition(substitution) = &node.implementation else { panic!("Boolean Operation is memoized, so it should be substituted with a network"); }; + let substitution = &substitutes[substitution]; let wrapped_node = substitution .nodes @@ -825,7 +860,7 @@ mod tests { assert_eq!(info.constant_inputs.count_ones(), 1, "{identifier:?} should only require its name to be constant"); } - for identifier in [graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::monitor::IDENTIFIER, ops::passthrough::IDENTIFIER] { + for identifier in [graphene_core::memo::memoize::IDENTIFIER, ops::passthrough::IDENTIFIER] { assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input"); } } diff --git a/node-graph/preprocessor/src/value_types.rs b/node-graph/preprocessor/src/value_types.rs new file mode 100644 index 00000000000..06766690aa3 --- /dev/null +++ b/node-graph/preprocessor/src/value_types.rs @@ -0,0 +1,157 @@ +//! The compiler's answer to what type a wire carries, for document migrations. + +use crate::Preprocessor; +use graph_craft::application_io::PlatformEditorApi; +use graph_craft::application_io::resource::ResourceId; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; +use graph_craft::graphene_compiler::Compiler; +use graph_craft::proto::TypingContext; +use graph_craft::{Type, item}; +use graphene_std::RuntimeHandle; +use graphene_std::platform_application_io::ResourceHash; +use interpreted_executor::node_registry::NODE_REGISTRY; +use std::collections::HashSet; +use std::sync::Arc; + +impl Preprocessor { + /// The value type slot `slot` of `node` carries in `inlined`, a network with no definitions left, by compiling only what feeds that slot. + /// `None` where that doesn't compile, or where instances of the node in several networks disagree. Costs one compile per instance. + pub fn input_type(&self, inlined: &NodeNetwork, node: NodeId, slot: usize, resource_hash: &dyn Fn(ResourceId) -> Option) -> Option { + let instances: Vec> = inlined.recursive_nodes().filter(|(id, _, _)| **id == node).map(|(_, _, path)| path).collect(); + + let mut agreed = None; + for path in instances { + let input = inlined.nested_network(&path)?.nodes.get(&node)?.inputs.get(slot)?.clone(); + let value_type = self.type_of_input(inlined, path, input, resource_hash)?; + + if agreed.as_ref().is_some_and(|agreed| *agreed != value_type) { + return None; + } + agreed = Some(value_type); + } + agreed + } + + /// Follows `input` out of networks and through hidden nodes to the output that gives it its type, then compiles that output alone. + pub fn type_of_input(&self, root: &NodeNetwork, mut path: Vec, mut input: NodeInput, resource_hash: &dyn Fn(ResourceId) -> Option) -> Option { + let (source, output_index) = loop { + match input { + NodeInput::Node { node_id, output_index } => { + let source = root.nested_network(&path)?.nodes.get(&node_id)?; + if source.visible { + break (node_id, output_index); + } + input = source.inputs.first()?.clone(); + } + NodeInput::Import { import_index, .. } => { + let caller = path.pop()?; + input = root.nested_network(&path)?.nodes.get(&caller)?.inputs.get(import_index)?.clone(); + } + _ => return None, + } + }; + + let mut pruned = root.clone(); + let output_path: Vec = path.iter().copied().chain([source]).collect(); + if !redirect_export_chain(&mut pruned, &output_path, output_index) { + return None; + } + pruned.exports.truncate(1); + pruned.remove_dead_nodes(0); + + // The compiler asserts every wire resolves, which a stored document doesn't promise + if !wires_resolve(&pruned) { + return None; + } + + // The scopes the runtime injects, given only as types since nothing is evaluated + let scope_stand_in = |value_type: Type| DocumentNode { + implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), + inputs: vec![NodeInput::value(TaggedValue::TypeDefault(value_type), false)], + ..Default::default() + }; + let content = DocumentNode { + implementation: DocumentNodeImplementation::Network(pruned), + ..Default::default() + }; + let mut scoped = NodeNetwork { + exports: vec![NodeInput::node(NodeId(0), 0)], + nodes: [ + (NodeId(0), content), + (NodeId(1), scope_stand_in(item!(Arc))), + (NodeId(2), scope_stand_in(item!(RuntimeHandle))), + ] + .into_iter() + .collect(), + scope_injections: [ + ("editor-api".to_string(), (NodeId(1), item!(Arc))), + ("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))), + ] + .into_iter() + .collect(), + definitions: Default::default(), + generated: true, + }; + + self.preprocess(&mut scoped, resource_hash).ok()?; + + // The compiler asserts every scope input resolves, so content reading any other scope stays unresolved + if !scope_inputs_resolve(&scoped, &HashSet::new()) { + return None; + } + + let proto_network = Compiler {}.compile_single(scoped).ok()?.network; + let mut typing_context = TypingContext::new(&NODE_REGISTRY); + typing_context.update(&proto_network).ok()?; + typing_context.type_of(proto_network.output).map(|types| types.return_value.clone()) + } +} + +/// Point the primary export at each level of `network` down through the nodes of `path`, unhiding each so the innermost node's output evaluates. +fn redirect_export_chain(network: &mut NodeNetwork, path: &[NodeId], output_index: usize) -> bool { + let Some((node_id, deeper_path)) = path.split_first() else { return true }; + + let export = NodeInput::node(*node_id, if deeper_path.is_empty() { output_index } else { 0 }); + match network.exports.first_mut() { + Some(first) => *first = export, + None => network.exports.push(export), + } + + let Some(node) = network.nodes.get_mut(node_id) else { return false }; + node.visible = true; + + if deeper_path.is_empty() { + return true; + } + match &mut node.implementation { + DocumentNodeImplementation::Network(nested) => redirect_export_chain(nested, deeper_path, output_index), + _ => false, + } +} + +fn wires_resolve(network: &NodeNetwork) -> bool { + let resolves = |input: &NodeInput| !matches!(input, NodeInput::Node { node_id, .. } if !network.nodes.contains_key(node_id)); + + network.exports.iter().all(resolves) + && network.nodes.values().all(|node| { + let nested_resolve = match &node.implementation { + DocumentNodeImplementation::Network(nested) => wires_resolve(nested), + _ => true, + }; + node.inputs.iter().all(resolves) && nested_resolve + }) +} + +fn scope_inputs_resolve(network: &NodeNetwork, enclosing_scopes: &HashSet) -> bool { + let scopes: HashSet = enclosing_scopes.iter().cloned().chain(network.scope_injections.keys().cloned()).collect(); + + network.nodes.values().all(|node| { + let inputs_resolve = node.inputs.iter().all(|input| !matches!(input, NodeInput::Scope(key) if !scopes.contains(key.as_ref()))); + let nested_resolve = match &node.implementation { + DocumentNodeImplementation::Network(nested) => scope_inputs_resolve(nested, &scopes), + _ => true, + }; + inputs_resolve && nested_resolve + }) +} diff --git a/node-graph/rfcs/async-execution-model.md b/node-graph/rfcs/async-execution-model.md index 63462e0a015..dcb21f34927 100644 --- a/node-graph/rfcs/async-execution-model.md +++ b/node-graph/rfcs/async-execution-model.md @@ -215,13 +215,13 @@ pub trait Spawn { /// Node-facing scope input. pub trait Runtime { - fn spawn(&self, source: SourceId, task: Task) -> AbortHandle; + fn spawn(&self, source: SourceId, task: Task); } ``` -`Task` is a boxed `'static` future that is `Send` on native targets only. The editor owns an `AsyncRuntime`, which updates the live sources (`retain_sources`) and takes snapshots of the generations (`snapshot`). Nodes get a cloneable `RuntimeHandle` to the same state through the `runtime` scope input, which is always present. Graphs without async nodes never read it. +`Task` is a boxed `'static` future that is `Send` on native targets only. The editor owns an `AsyncRuntime`, which updates the live sources (`update_sources`) and takes snapshots of the generations (`snapshot`). Nodes get a cloneable `RuntimeHandle` to the same state through the `runtime` scope input, which is always present. Graphs without async nodes never read it. -The host provides the `Spawn` implementation (a tokio runtime on desktop and `spawn_local` on the web) and a `Clock` (`Instant` on desktop, `performance.now()` on the web), which nodes can read through `RuntimeHandle::clock`. The editor wraps the spawner so that a finished task calls the runtime's wake callback (a channel send on desktop, a queued runtime run on the web). `Runtime::spawn` returns an abort handle; an aborted task bumps nothing. +The host provides the `Spawn` implementation: a tokio runtime on desktop and `spawn_local` on the web. The editor wraps it so that a finished task sets a dirty flag and calls the runtime's wake callback (a channel send on desktop, an idle callback on the web). Executor construction, update, and execution are plain functions, and `execute` returns `Poll`. The only await left in the editor runtime is the GPU readback for exports and the eyedropper, which can't block on the web. On desktop, the runtime runs on its own thread under `block_on`, and the readback polls the device until the copy is done. @@ -230,11 +230,12 @@ We don't use wakers to notify the graph. A waker resumes a suspended computation ## Scheduling - Generations are read once per evaluation. A task that finishes during an evaluation takes effect in the next one. -- The bump flag is checked once per runtime run, so N finished tasks cause one re-render of the last viewport request. -- The host marks frames with `begin_frame` (each animation frame on the web, the runtime thread's loop on desktop). A re-evaluation caused by finished tasks only starts while the frame is within `Scheduling::frame_budget` (16 ms by default), otherwise it waits for the next frame. Without this, a chain of immediately finishing tasks on the web would run entirely within one microtask checkpoint and the browser would never paint. Graph updates and explicit execution requests are never deferred. -- On recompile, `retain_sources` removes sources that no longer exist (aborting their tasks) and adds new ones at generation zero. Nodes that were removed drop their slots, which aborts their tasks. +- The dirty flag is checked once per runtime run, so N finished tasks cause one re-render of the last viewport request. +- Only `update` reads requests and applies network updates, and hosts call it at most once per frame (each animation frame on the web, each redraw on desktop). `run` only evaluates, when a request or a finished task has set the dirty flag, so a graph can settle between updates however often the editor sends them. A newer request replaces an older one of its kind. +- On the web, a wake asks for a run through `requestIdleCallback`, and within that idle period runs again at once while another run fits. Otherwise, and in browsers without that API, the next animation frame picks up the finished task. Waking any sooner would hold up frames: a microtask blocks painting, and a normal task goes ahead of the frame. On desktop, the graph has its own thread, so a wake runs it at once. +- On recompile, `update_sources` removes sources that no longer exist and adds new ones at generation zero. Nodes that were removed drop their slots, which aborts their tasks. -The editor maps the top-level `Poll` to an `ExecutionResult`: `Pending`, `Value`, `Fallback(value, errors)`, `Error(errors)`, or `Panic`. A `Pending` result keeps the last frame and its errors on screen. An export treats `Partial` like `Pending`: it is parked and re-run on every wake after a bump until the result is final, and the runtime doesn't process other requests until then. +The editor maps the top-level `Poll` to an `ExecutionResult`: `Pending`, `Value`, `Fallback(value, errors)`, `Error(errors)`, or `Panic`. A `Pending` result keeps the last frame and its errors on screen. An export treats `Partial` like `Pending`: it is parked and re-run on every dirty wake until the result is final. `update` stops reading at an export, so it runs on its own network update and anything sent later waits. ## Overhead diff --git a/node-graph/rfcs/document-format-migrations.md b/node-graph/rfcs/document-format-migrations.md index beff26fe8a8..12583e8fc29 100644 --- a/node-graph/rfcs/document-format-migrations.md +++ b/node-graph/rfcs/document-format-migrations.md @@ -2,7 +2,7 @@ A migration system for `.gdd` documents built around one rule: **history is always in the current shape**. A migration is a deterministic function over registry states. The runner applies it by replaying stored history and rewriting every delta into what it would have been had the author worked against the new shape, inserting deltas where the migration restructures the graph. Undo, time travel, replay, and deltas arriving from peers on an older build therefore never meet an outdated node shape, and the runtime never needs to execute one. -Migrations come in two tiers sharing that rule. **Format migrations** step serialized payloads across a `format_version` bump. **Node migrations** step one proto-node declaration from `identifier@version` to its successor on the typed `Registry`. Migrations are written as plain functions whose parameter types state what they read and write, live in independent crates that register themselves, and are ordered automatically. +Migrations come in two tiers sharing that rule. **Format migrations** step serialized payloads across a `format_version` bump. **Node migrations** step one declaration, a proto node or a built-in network definition, from `identifier@version` to its successor on the typed `Registry`. Migrations are written as plain functions whose parameter types state what they read and write, live in independent crates that register themselves, and are ordered automatically. # Motivation @@ -74,10 +74,13 @@ The function runs once per **anchor**: a node of the source declaration. The run | `&mut Inputs` | the anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate` | | `&mut Upstream` | new and existing nodes upstream of the anchor | `add_node`, `add_node_keyed`, `remove_node` | | `&mut Downstream` | the slots and exports reading the anchor's outputs, plus new downstream nodes | `consumers`, `add_node`, `add_node_keyed`, `connect` | +| `&mut Attributes` | attributes of the anchor and of the nodes the run adds | `set`, `remove` | | `&mut Resources` | document resources | `add_embedded` | `Inputs` operations apply in order to the target layout being built. `node.inputs()` is always the source layout. Reads through a mutable view (such as `Downstream::consumers`) also see the source state, so nodes added by the migration never appear among the anchor's consumers. +The runner places added nodes from the anchor's own position. Nodes leading up to the anchor's chain input form a row, or join the chain when the anchor is chained or a layer. Other nodes feeding the anchor or that row sit below the first one reading them, and the rest sit on the anchor. A chained anchor has no coordinates of its own, so only its chain is placed, and an anchor with no stored position gets nothing placed. A migration overrides these positions, or clears a stored name that no longer fits the anchor, through `Attributes`. + A migration addresses declarations with `decl!`, values with a frozen mirror of the value variants it uses, and connections with plain connector types: ```rust @@ -326,6 +329,33 @@ Cycles are rejected in CI, as are two migrations from the same declaration. Migr A node migration is pending when its source declaration is referenced anywhere in the document, *including history*. A node removed long ago still has its old shape stored in its `AddNode` and in the removal snapshot, and undo can bring it back. Pending format migrations come from `manifest.format_version`. +## Network definitions + +Built-in subgraphs such as Merge and Artboard aren't proto nodes. Each instance is a node whose `Implementation::Network` points at its own copy of a network from the editor's catalog. They migrate through the same tier, with the differences below. + +**Declarations.** `Declaration` carries a kind, `Proto` or `Network`. A network declaration is written `decl!(network "Merge"@1)`, and steps name it the same way: + +```rust +rename!(network "Artboard"@1 => @2); // Version step +rename!(network "Merge"@1 => "graphic_nodes::merge"@2); // Replacement by a proto node +``` + +A proto declaration's encoding leaves the kind out, so IDs derived from declarations written before network definitions existed stay the same. + +**Stored reference.** The network's `ui::reference` attribute names its definition as a `NetworkReference { identifier, version }`. Version 1 stays the bare identifier string it was before versions existed, so existing documents keep their bytes. Later versions store an object with both fields. One attribute rather than one per field keeps identifier and version under one LWW timestamp, so concurrent writes can't pair one peer's identifier with another's version, and pending detection matches the exact version. + +`DocumentNodeDefinition` declares the `version`. The editor writes the catalog's current version whenever it stores a reference, the way runtime conversion takes a proto node's version from `NODE_METADATA`. Opening a document migrates every instance to its definition's current version, so the editor never holds an older one in memory. + +**Anchors.** A node is an anchor of a network declaration when it implements a network whose reference names that declaration. `references` finds the declaration in `AddNetwork`, in `RemoveNetwork` snapshots, and in writes to `ui::reference`. + +**Switching.** The runner switches a network anchor to a network declaration by rewriting the reference. It switches one to a proto declaration by setting the implementation and removing the network the anchor implemented, with every node in it and every network nested in it. A proto anchor can't become a network declaration, and migrations only add proto nodes. + +Removing the network drops whatever it holds, including nodes the user added. This is a deliberate exception to totality, since the alternatives are worse. Reporting an edited subgraph as `unrepresentable` opens the document read-only, and keeping the edited copy usually doesn't compile anyway, since the nodes inside it typically folded into the new proto node. Built-in subgraphs are rarely edited, so the loss is rare. + +**Whole states.** An instance consists of two entities that history adds in separate deltas, and the editor's diff adds the network first. In between, the network names the definition without an anchor to migrate it, so `M` would leave the old reference in rewritten history, and every later open would find the migration pending again. Migrations from a network declaration therefore run on whole states only, like those reading `&Graph`. + +**Checks.** An editor test requires a registered migration leading to every network definition above version 1. The API dump doesn't cover network definitions yet. + ## Runner pipeline 1. **Format tier.** While `format_version` is below the current version, apply the step whose `migrates_from` matches (a gap is a hard error) to the registry, history records, and session, then bump the version. @@ -374,6 +404,16 @@ A naive rewrite evaluates `M` on a full state per delta. Instead, the runner: A migration whose edits are only `Inputs` operations with constant values, and every rename, is an index map over input slots. The runner applies such migrations per delta without replaying states, remapping `ChangeNodeInput`, `SetNodeInputs`, `ChangeNodeInputAttribute`, `AddNode` payloads, and removal snapshots directly. The commutation test proves this fast path equal to the state path. +## The compiler and whole states + +Some migrations need to know what only the compiler or executor can tell, such as the type flowing through a wire or a measurement of evaluated geometry. Storing types to answer this offline isn't an option, since `TypeId`s aren't stable across builds and `type_name` output isn't stable at all. So a migration asks for the compiler with an `Option<&dyn Compiler>` parameter, which the caller opening the document offers through a `MigrationHost`, and these are the costs, paid only by what uses them: + +- **Whole states.** A delta in the middle of an interaction can leave a state no one ever saw, with nodes wired to what's not added yet, which reading the graph or compiling can only fail on. So a migration whose footprint reads the network runs at the boundaries undo can land on, the end of an interaction, a change of author, a branch point, or a cursor, and everything since the previous one becomes one chain. A history without interaction ends, such as an imported document's, is one evaluation. Bootstrapping marks its end, so the first edit after it is its own undo step. +- **Order.** The compiler can't describe what the binary no longer implements, so these migrations run as late as their dependencies allow, within the one ordered pass opening runs. Within one, an anchor only runs once no other anchor is upstream of it. The declarations it needs are loaded only then, from the caller's byte store and otherwise the container. +- **Failure.** There may be no compiler, and it may have no answer, so the migration must choose a fallback. A state that doesn't compile usually didn't before either, so there's nothing for a fallback to harm. Without a host the fallback is permanent, so the editor and CLI always offer one. A migration that itself fails falls back to truncating, as below. +- **Determinism.** The result depends on the build, so unlike the rest of this document, two peers can compute different `Rev`s. Such a rewrite only suits a document with one peer until settling is built. +- **Targets.** `Target` lets an anchor switch to any declaration its migration pins, which needs no version step, so documents holding a node that is only a target aren't rewritten for it. + ## Errors and the truncate fallback A migration reports two kinds of failure: @@ -489,6 +529,8 @@ document/migrations/ **Truncate always.** Simple and always possible, but it discards undo history on every node upgrade and needs every peer to agree on the truncation point. +**Reference attribute vs. declaration resource for network definitions.** A content-addressed resource behind `Implementation::Network`, like `ProtoNode`, would let one resolver path cover both kinds. It changes the shape of `Implementation`, which needs a format step, and turns detaching an instance into a resource swap. A single attribute holding identifier and version gives the same atomicity and exact matching. + **Frozen mirrors vs. runtime types.** Input values are stored as self-describing `graph-storage::Value`s, so a migration decodes them into its own frozen mirror. Old runtime types therefore never need to stay in the runtime crates. # Unresolved questions @@ -499,8 +541,10 @@ document/migrations/ - **Input attributes of inserted nodes.** `NewNode` takes bare `NodeInput`s, so inserted nodes start with empty per-input attributes. Taking `InputSlot`s would let a migration carry them over. - **Removal safety.** `Upstream::remove_node` is only correct when nothing else reads the removed node, which the region system can't check. - **`unrepresentable` in CI.** Whether reaching it in the commutation test fails CI outright. -- **Layout.** Whether migrations may write node positions and chain placement, or leave inserted nodes to a host-side layout pass. +- **Layout.** Migrations position the nodes they add and can move the anchor, but can't move other existing nodes, so an inserted node can overlap what sits upstream. Positions stored relative to each node's consumers would move the upstream without writing it. - **Multiple pending migrations.** Whether consecutive pending node migrations run as separate rewrite passes or are fused into one replay. +- **Migrations reading a subgraph.** A migration that inspects an instance's inner nodes depends on their versions, which change independently of the definition's. The planned answer is a cascading bump: the API dump lists a definition's inner `identifier@version`s, so bumping an inner node also requires bumping every definition containing it, and pins order that node's migrations around the definition's. Nothing reads a subgraph yet, so neither a read view for it nor the cascading bump exists. +- **Detaching.** Whether a migration may clear an edited instance's reference, keeping it as a custom subgraph, instead of collapsing it. # Future possibilities diff --git a/proc-macros/src/editor_commands.rs b/proc-macros/src/editor_commands.rs index ac7fa4d4959..8c5d83623ea 100644 --- a/proc-macros/src/editor_commands.rs +++ b/proc-macros/src/editor_commands.rs @@ -1,6 +1,6 @@ use convert_case::{Case, Casing}; use proc_macro2::TokenStream; -use quote::{quote, quote_spanned}; +use quote::{ToTokens, quote, quote_spanned}; use syn::spanned::Spanned; use syn::{Error, FnArg, Ident, Item, ItemFn, ItemMod, ItemUse, Pat, Visibility}; @@ -51,7 +51,7 @@ pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result Message` translations")); } - if !signature.generics.params.is_empty() || signature.asyncness.is_some() || signature.unsafety.is_some() { + if !signature.generics.params.is_empty() || signature.asyncness.is_some() || matches!(signature.safety, syn::Safety::Unsafe(_)) { return Err(Error::new(signature.span(), "command functions must be plain non-generic, non-async, safe functions")); } @@ -62,6 +62,13 @@ pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result` or `Vec>` where `MyStruct: Tsify`. + // To get rid of this, `unwrapping_tsify` contains some expressions to get back the tsify free param types + let mut unwrapping_tsify = Vec::new(); + // A list of the types without any Ts wrappers. + let mut tsify_free_param_types = Vec::new(); + for parameter in &signature.inputs { let FnArg::Typed(pat_type) = parameter else { unreachable!("receiver is rejected above") }; let Pat::Ident(pat_ident) = &*pat_type.pat else { @@ -69,6 +76,47 @@ pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result`, returning the inner `T`. + fn try_get_nested_type<'a>(ty: &'a syn::Type, ident: &str) -> Option<&'a syn::Type> { + let syn::Type::Path(type_path) = ty else { return None }; + let last_segment = type_path.path.segments.last()?; + if last_segment.ident != ident { + return None; + } + let syn::PathArguments::AngleBracketed(argument) = &last_segment.arguments else { return None }; + argument.args.iter().find_map(|g| if let syn::GenericArgument::Type(t) = g { Some(t) } else { None }) + } + + let debug_info = quote! {concat!("convert ", stringify!(#pat_ident), " to type ", stringify!(#pat_type) )}; + if let Some(nested_type) = try_get_nested_type(&pat_type.ty, "Ts") { + // This is a tsify::Ts + unwrapping_tsify.push(quote_spanned! { + pat_ident.span() => let #pat_ident = match #pat_ident.to_rust() { + Ok(#pat_ident) => #pat_ident, + Err(e) => { + log::error!("Cannot {}: {:?}", #debug_info, e); + return; + } + }; + }); + tsify_free_param_types.push(nested_type.to_token_stream()); + } else if let Some(nested_type) = try_get_nested_type(&pat_type.ty, "Vec").and_then(|inner| try_get_nested_type(inner, "Ts")) { + // This is a Vec> + unwrapping_tsify.push(quote_spanned! { + pat_ident.span() => let #pat_ident = match #pat_ident.into_iter().map(|item|item.to_rust()).collect::,_>>() { + Ok(#pat_ident) => #pat_ident, + Err(e) => { + log::error!("Cannot {}: {:?}", #debug_info, e); + return; + } + }; + }); + tsify_free_param_types.push(quote! { Vec<#nested_type> }); + } else { + // This a type without a Ts wrapper + tsify_free_param_types.push(pat_type.ty.to_token_stream()); + } } let return_type = &signature.output; @@ -77,19 +125,22 @@ pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result #(#docs)* - #variant { #(#param_names: #param_types,)* }, + #variant { #(#param_names: #tsify_free_param_types,)* }, }); stubs.extend(quote_spanned! {span=> #(#docs)* #[cfg(not(feature = "native"))] #[wasm_bindgen(js_name = #js_name)] pub fn #fn_name(&self, #(#param_names: #param_types,)*) { - self.dispatch((move || #return_type #body)()) + #(#unwrapping_tsify)* + fn #fn_name(#(#param_names: #tsify_free_param_types,)*) #return_type #body + self.dispatch(#fn_name(#(#param_names,)*)) } #(#docs)* #[cfg(feature = "native")] #[wasm_bindgen(js_name = #js_name)] pub fn #fn_name(&self, #(#param_names: #param_types,)*) { + #(#unwrapping_tsify)* self.send(EditorCommand::#variant { #(#param_names,)* }) } }); diff --git a/proc-macros/src/message_handler_data_attr.rs b/proc-macros/src/message_handler_data_attr.rs index cbf45f79ecd..1ede053d319 100644 --- a/proc-macros/src/message_handler_data_attr.rs +++ b/proc-macros/src/message_handler_data_attr.rs @@ -20,7 +20,7 @@ pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream // Extract the message type from the trait path let trait_path = match &impl_block.trait_ { - Some((_, path, _)) => path, + Some((path, _)) => path, None => return Err(syn::Error::new(Span::call_site(), "Expected trait implementation")), }; diff --git a/proc-macros/src/widget_builder.rs b/proc-macros/src/widget_builder.rs index a1ec05b0eae..f7bee1e69ea 100644 --- a/proc-macros/src/widget_builder.rs +++ b/proc-macros/src/widget_builder.rs @@ -158,6 +158,7 @@ pub fn derive_widget_builder_impl(input_item: TokenStream2) -> syn::Result Self { #construction } diff --git a/tools/cargo-run/internal/download/Cargo.toml b/tools/cargo-run/internal/download/Cargo.toml index 75a2826d4a5..e2503a36e5d 100644 --- a/tools/cargo-run/internal/download/Cargo.toml +++ b/tools/cargo-run/internal/download/Cargo.toml @@ -16,6 +16,6 @@ workspace = true [dependencies] cargo-run = { path = "../.." } ureq = { version = "3", default-features = false, features = ["rustls"] } -sha2 = { version = "0.10" } +sha2 = { version = "0.11" } flate2 = { version = "1", default-features = false, features = ["rust_backend"] } tar = { version = "0.4", default-features = false } diff --git a/tools/cargo-run/src/requirements.rs b/tools/cargo-run/src/requirements.rs index 10265874fd0..015ef3bef08 100644 --- a/tools/cargo-run/src/requirements.rs +++ b/tools/cargo-run/src/requirements.rs @@ -55,8 +55,8 @@ fn requirements(task: &Task) -> Vec { args: &["--version"], name: "Wasm Bindgen", // NOTICE: keep in sync with the `wasm-bindgen` crate in `Cargo.toml` and the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, and `.nix/pkgs/graphite.nix` - version: Some("=0.2.127"), - install: "cargo install -f wasm-bindgen-cli@0.2.127".into(), + version: Some("=0.2.129"), + install: "cargo install -f wasm-bindgen-cli@0.2.129".into(), skip: Some(&|task| matches!(task.target, Target::Cli)), ..Default::default() }, diff --git a/tools/crate-hierarchy-viz/Cargo.toml b/tools/crate-hierarchy-viz/Cargo.toml index 3f46047652b..49c3bdb9dff 100644 --- a/tools/crate-hierarchy-viz/Cargo.toml +++ b/tools/crate-hierarchy-viz/Cargo.toml @@ -16,6 +16,6 @@ workspace = true [dependencies] serde = { workspace = true } -toml = "0.8" +toml = "1.1" anyhow = { workspace = true } glob = "0.3" diff --git a/tools/node-docs/Cargo.toml b/tools/node-docs/Cargo.toml index 5ec7ed41f55..760c74381e7 100644 --- a/tools/node-docs/Cargo.toml +++ b/tools/node-docs/Cargo.toml @@ -17,9 +17,7 @@ workspace = true [dependencies] # Local dependencies graphene-std = { workspace = true } -interpreted-executor = { workspace = true } graph-craft = { workspace = true, features = ["loading"] } -preprocessor = { workspace = true } # Workspace dependencies indoc = { workspace = true } diff --git a/tools/node-docs/src/page_catalog.rs b/tools/node-docs/src/page_catalog.rs index c3bc00a33f9..c652a5e0f11 100644 --- a/tools/node-docs/src/page_catalog.rs +++ b/tools/node-docs/src/page_catalog.rs @@ -28,6 +28,7 @@ fn write_frontmatter(page: &mut std::fs::File) { [extra] order = 3 css = [\"/page/user-manual/node-catalog.css\"] + development_notice = true +++ " ); diff --git a/tools/node-docs/src/page_category.rs b/tools/node-docs/src/page_category.rs index e16a50723db..d593e5a9973 100644 --- a/tools/node-docs/src/page_category.rs +++ b/tools/node-docs/src/page_category.rs @@ -29,6 +29,7 @@ fn write_frontmatter(page: &mut std::fs::File, category: &str, order: usize) { [extra] order = {order} css = [\"/page/user-manual/node-category.css\"] + development_notice = true +++ " ); diff --git a/tools/node-docs/src/page_node.rs b/tools/node-docs/src/page_node.rs index 3b1ebb224d2..cedcd9187ce 100644 --- a/tools/node-docs/src/page_node.rs +++ b/tools/node-docs/src/page_node.rs @@ -57,6 +57,7 @@ fn write_frontmatter(page: &mut std::fs::File, metadata: &NodeMetadata, order: u [extra] order = {order} css = [\"/page/user-manual/node.css\"] + development_notice = true +++ " ); diff --git a/tools/node-docs/src/utility.rs b/tools/node-docs/src/utility.rs index 2146409293b..311d009dc3b 100644 --- a/tools/node-docs/src/utility.rs +++ b/tools/node-docs/src/utility.rs @@ -6,7 +6,7 @@ pub const OMIT_HIDDEN: bool = true; pub fn category_description(category: &str) -> &str { match category { "Value" => "Nodes in this category supply data values of common types such as numbers, colors, gradients, booleans, and strings.", - "Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, wrapping nodes into a custom subgraph, and caching results.", + "Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, repeating steps on a result, wrapping nodes into a custom subgraph, and caching results.", "Transform" => "Nodes in this category move, rotate, scale, and skew graphical content, read and combine the transformation matrices that place it, and arrange items by packing them into rows or columns.", "Graphic" => "Nodes in this category compose graphical content of any kind, such as merging layers, making artboards and groups, blending and clipping, repeating and mirroring copies, and flattening nested groups.", "Vector: Style" => "Nodes in this category apply fill and stroke styles to alter the appearance of vector graphics.", diff --git a/tools/regression/Cargo.toml b/tools/regression/Cargo.toml index d7bb5c66c66..928350a94f6 100644 --- a/tools/regression/Cargo.toml +++ b/tools/regression/Cargo.toml @@ -17,9 +17,12 @@ workspace = true [dependencies] # Local dependencies graphene-cli = { path = "../../node-graph/graphene-cli" } +document-loader = { workspace = true } document-format = { workspace = true, features = ["zip", "xz", "migrations"] } # Workspace dependencies +graph-craft = { workspace = true } +graphene-std = { workspace = true } clap = { workspace = true, features = ["derive"] } fern = { workspace = true } image = { workspace = true } diff --git a/tools/regression/src/coverage.rs b/tools/regression/src/coverage.rs new file mode 100644 index 00000000000..77e2236f40d --- /dev/null +++ b/tools/regression/src/coverage.rs @@ -0,0 +1,44 @@ +//! Which of the nodes this build registers appear somewhere in the corpus's documents. + +use crate::corpus::Corpus; +use graph_craft::document::DocumentNodeImplementation; +use graphene_cli::open_document; +use graphene_std::registry::{NODE_METADATA, category_sort_key, is_hidden_category}; +use std::collections::HashSet; +use std::error::Error; + +/// Print how many of the registered nodes the corpus uses, and with `list_uncovered`, the ones it doesn't. +/// Nodes in hidden categories never appear in the node catalog, so they only count with `include_hidden`. +pub(crate) async fn coverage(corpus: &Corpus, list_uncovered: bool, include_hidden: bool) -> Result<(), Box> { + let mut used = HashSet::new(); + for entry in &corpus.manifest.documents { + let document = open_document(&corpus.document(&entry.name), false).await.map_err(|error| format!("{}: {error}", entry.name))?; + let identifiers = document.network.recursive_nodes().filter_map(|(_, node, _)| match &node.implementation { + DocumentNodeImplementation::ProtoNode(identifier) => Some(identifier.as_str().to_string()), + _ => None, + }); + used.extend(identifiers); + } + + let metadata = NODE_METADATA.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let counted: Vec<_> = metadata.iter().filter(|(_, metadata)| include_hidden || !is_hidden_category(metadata.category)).collect(); + let mut uncovered: Vec<_> = counted.iter().filter(|(identifier, _)| !used.contains(identifier.as_str())).collect(); + + let total = counted.len(); + let covered = total - uncovered.len(); + let percentage = if total == 0 { 0. } else { covered as f64 / total as f64 * 100. }; + println!("The corpus uses {covered} of {total} nodes ({percentage:.1}%)"); + + if list_uncovered { + uncovered.sort_by(|(_, a), (_, b)| category_sort_key(a.category).cmp(&category_sort_key(b.category)).then(a.display_name.cmp(b.display_name))); + let mut category = None; + for (identifier, metadata) in uncovered { + if category != Some(metadata.category) { + category = Some(metadata.category); + println!("\n{}", if metadata.category.is_empty() { "Uncategorized" } else { metadata.category }); + } + println!(" {} ({})", metadata.display_name, identifier.as_str()); + } + } + Ok(()) +} diff --git a/tools/regression/src/main.rs b/tools/regression/src/main.rs index f40d51106f1..458e516f651 100644 --- a/tools/regression/src/main.rs +++ b/tools/regression/src/main.rs @@ -1,5 +1,6 @@ mod compare; mod corpus; +mod coverage; mod ingest; mod render; mod upgrade; @@ -64,6 +65,15 @@ enum Command { #[clap(long, default_value = "target/regression")] output: PathBuf, }, + /// Report how many of the registered nodes the corpus's documents use. + Coverage { + /// Also list the nodes no document uses. + #[clap(long)] + uncovered: bool, + /// Also count the nodes in hidden categories, which the node catalog doesn't list. + #[clap(long)] + include_hidden: bool, + }, } #[tokio::main] @@ -130,6 +140,10 @@ async fn run(app: App) -> Result> { } Ok(passed) } + Command::Coverage { uncovered, include_hidden } => { + coverage::coverage(&Corpus::open(&corpus_root()?)?, uncovered, include_hidden).await?; + Ok(true) + } } } diff --git a/tools/regression/src/upgrade.rs b/tools/regression/src/upgrade.rs index 9a5b3ab1798..486e6c1342f 100644 --- a/tools/regression/src/upgrade.rs +++ b/tools/regression/src/upgrade.rs @@ -29,7 +29,7 @@ pub(crate) fn expand(paths: &[PathBuf]) -> Result, Box> /// An archive's bytes aren't stable across a reopen, so the file is only rewritten when it changed. The embedded legacy `.graphite` is dropped, since it doesn't migrate and the editor would open it in place of the migrated state. pub(crate) async fn upgrade(path: &Path) -> Result> { let archive = std::fs::read(path)?; - let gdd = graphene_cli::open_gdd(&archive).await?; + let gdd = document_loader::open_gdd(&archive).await?; if !gdd.migrated() { return Ok(false); } diff --git a/tools/web-editor-driver/Cargo.toml b/tools/web-editor-driver/Cargo.toml index 16093419b49..c27e4558f77 100644 --- a/tools/web-editor-driver/Cargo.toml +++ b/tools/web-editor-driver/Cargo.toml @@ -28,7 +28,7 @@ clap = { workspace = true, features = ["derive"] } # Other dependencies image = { version = "0.25", default-features = false, features = ["png"] } interprocess = "2.4.2" -getrandom = "0.3" +getrandom = "0.4" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Threading"] } diff --git a/tools/web-editor-driver/src/client.rs b/tools/web-editor-driver/src/client.rs index 8a80c666aa0..2b9863aff20 100644 --- a/tools/web-editor-driver/src/client.rs +++ b/tools/web-editor-driver/src/client.rs @@ -1,7 +1,7 @@ //! Starting, reaching, and stopping the session host, which owns the browser so separate invocations can act on the same editor one after another. use control_protocol::{ClientMessage, Command, CommandResult, HostMessage, PROTOCOL_VERSION}; -use interprocess::local_socket::{RecvHalf, SendHalf, Stream, prelude::*}; +use interprocess::local_socket::{Stream, prelude::*}; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::path::PathBuf; @@ -36,8 +36,7 @@ enum OpenFailure { } pub struct Connection { - receiver: BufReader, - sender: SendHalf, + stream: BufReader, next_id: u64, } @@ -45,10 +44,8 @@ impl Connection { fn open(record: &SessionRecord) -> Result { let name = socket::name(&record.session_id).map_err(|_| OpenFailure::Unreachable)?; let stream = Stream::connect(name).map_err(|_| OpenFailure::Unreachable)?; - let (receiver, sender) = stream.split(); let mut connection = Self { - receiver: BufReader::new(receiver), - sender, + stream: BufReader::new(stream), next_id: 1, }; @@ -94,11 +91,11 @@ impl Connection { } fn send(&mut self, message: &ClientMessage) -> Result<(), String> { - socket::write_message(&mut self.sender, message) + socket::write_message(&mut self.stream.get_ref(), message) } fn receive(&mut self) -> Result, String> { - socket::read_message(&mut self.receiver) + socket::read_message(&mut self.stream) } } diff --git a/tools/web-editor-driver/src/host.rs b/tools/web-editor-driver/src/host.rs index 58b498ac959..4ebb98e3052 100644 --- a/tools/web-editor-driver/src/host.rs +++ b/tools/web-editor-driver/src/host.rs @@ -69,8 +69,8 @@ pub fn run(options: SessionOptions) -> Result<(), String> { } fn serve(stream: Stream, state: &HostState) { - let (receiver, mut sender) = stream.split(); - let mut receiver = BufReader::new(receiver); + let mut receiver = BufReader::new(&stream); + let mut sender = &stream; let refusal = match socket::read_message(&mut receiver) { Ok(Some(ClientMessage::Attach { version, .. })) if version != PROTOCOL_VERSION => Some(format!( diff --git a/website/content/donate.md b/website/content/donate.md index a64c8de0949..7478ced6e53 100644 --- a/website/content/donate.md +++ b/website/content/donate.md @@ -2,15 +2,15 @@ title = "Donate" [extra] -css = ["/page/donate.css", "/component/feature-box.css"] -js = ["/js/page/donate.js"] +css = ["/page/donate.css", "/component/feature-box.css", "/component/credits-names.css"] +js = ["/js/page/donate.js", "/js/component/credits-particles.js"] +++

Thank you for your donation! Your receipt is on its way by email, and your support goes straight into building Graphite.
-
Welcome, and thank you for becoming a member! Your receipt is on its way by email. We're fulfilling membership rewards by hand for now, so please forward that receipt to contact@graphite.art with your Discord username, the name you'd like in the credits, and/or any other details pertinent to your membership level.
+
Welcome, and thank you for becoming a member! Your receipt is on its way by email. Set up your rewards on the membership page.
+
+
- +
@@ -72,9 +74,8 @@ js = ["/js/page/donate.js"]
- Manage your ongoing membership
- +
@@ -82,7 +83,9 @@ js = ["/js/page/donate.js"]
  • Support Graphite's development
  • -
  • Shiny GitHub profile achievement
  • +
  • Members-only Discord channel and gold nametag
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $5 monthly @@ -91,9 +94,10 @@ js = ["/js/page/donate.js"]
    -
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Your name in our update video and site credits
  • +
  • Members-only Discord channel and gold nametag
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $10 monthly @@ -102,10 +106,11 @@ js = ["/js/page/donate.js"]
    -
  • Your name in our update video and site credits
  • +
  • Your name higher in our update video and site credits
  • +
  • Personalized color choice for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $15 monthly @@ -114,10 +119,11 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • +
  • Your name higher in our update video and site credits
  • +
  • Personalized colored gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $25 monthly @@ -126,10 +132,11 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • +
  • Your name higher in our update video and site credits
  • +
  • Personalized animated gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $50 monthly @@ -138,10 +145,12 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • +
  • Your name higher in our update video and site credits
  • +
  • Custom avatar picture with your site credits name
  • +
  • Personalized animated gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $75 monthly @@ -150,11 +159,13 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • -
  • Custom hyperlink on your site credits name
  • +
  • Your name higher in our update video and site credits
  • +
  • Custom hyperlink on your site credits name
  • +
  • Custom avatar picture with your site credits name
  • +
  • Personalized animated gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $100 monthly @@ -163,12 +174,14 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • -
  • Custom avatar picture with your site credits name
  • -
  • Custom hyperlink on your site credits name
  • +
  • Your name higher in our update video and site credits
  • +
  • Animated particle effects around your site credits name
  • +
  • Custom hyperlink on your site credits name
  • +
  • Custom avatar picture with your site credits name
  • +
  • Personalized animated gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $250 monthly @@ -177,13 +190,15 @@ js = ["/js/page/donate.js"]
    -
  • Your name higher in our update video and site credits
  • -
  • A spoken personal thank-you during update video credits
  • -
  • Custom avatar picture with your site credits name
  • -
  • Custom hyperlink on your site credits name
  • +
  • Your name higher in our update video and site credits
  • +
  • A spoken personal thank-you in our update video credits
  • +
  • Animated particle effects around your site credits name
  • +
  • Custom hyperlink on your site credits name
  • +
  • Custom avatar picture with your site credits name
  • +
  • Personalized animated gradient for your site credits name
  • Members-only Discord channel and gold nametag
  • -
  • Regular dev sneak-peeks and project files from recent YouTube uploads
  • -
  • Shiny GitHub profile achievement
  • +
  • Regular dev sneak peeks and project files from recent YouTube uploads
  • +
  • Shiny GitHub profile achievement
Donate $500 monthly @@ -193,10 +208,10 @@ js = ["/js/page/donate.js"]
  • Select a common amount from above or customize it below
  • -
  • We're currently not set up to fulfill membership rewards for one-time donors, but your selfless generosity is appreciated
  • +
  • One-time gifts don't include membership rewards, but they help us keep building Graphite. Thank you!
-
+
@@ -210,5 +225,42 @@ js = ["/js/page/donate.js"]

GitHub subsidizes our processing fees so your full amount reaches us.

+Manage your ongoing membership and rewards +
+
+
+ +
+
+ +## Acknowledgments + +We're grateful to these programs and organizations for the grants and services that help make Graphite possible. + +
+ European Commission, NGI Zero Commons Fund, and NLnet Foundation + Google Summer of Code + CI powered by Blacksmith +
+ +
+
+ + diff --git a/website/content/membership.md b/website/content/membership.md new file mode 100644 index 00000000000..914f5ec9d8a --- /dev/null +++ b/website/content/membership.md @@ -0,0 +1,245 @@ ++++ +title = "Manage membership" +path = "donate/membership" + +[extra] +css = ["/page/membership.css", "/component/feature-box.css", "/component/credits-names.css"] +js = ["/js/page/membership.js", "/js/component/credits-particles.js"] ++++ + +
+ +
+
+ +# Manage membership + +Thank you for helping make Graphite possible! Signed-in members can manage how they support the project and access their reward perks on this page. + + + + + +
+
+
+
+ + + + + + + +
+

How are you paying for your membership?

+
+ + +
+ + + + + + +

Not a member yet? Pick a tier.

+
+ +
+
+ +
diff --git a/website/content/volunteer/guide/graphene/_index.md b/website/content/volunteer/guide/graphene/_index.md index 8d8ca4ea637..e663139db61 100644 --- a/website/content/volunteer/guide/graphene/_index.md +++ b/website/content/volunteer/guide/graphene/_index.md @@ -89,7 +89,6 @@ Since Graphene is fundamentally a programming language, throughout this document - - diff --git a/website/content/volunteer/guide/graphene/document-migrations.md b/website/content/volunteer/guide/graphene/document-migrations.md index 3c63c573a86..3a31b2592c7 100644 --- a/website/content/volunteer/guide/graphene/document-migrations.md +++ b/website/content/volunteer/guide/graphene/document-migrations.md @@ -83,12 +83,17 @@ You ask for what you need through the function's parameters, in any order. The f |---|---|---| | `&Node` | The anchor before migration | `id()`, `inputs()`, and the stored node's other accessors | | `&Graph` | The anchor's network before migration | `node(id)`, `declaration(id)`, `consumers(output)` | -| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate`, `len` | +| `Option<&dyn Compiler>` | What only the compiler can tell about the state before migration, see [Asking the compiler](#asking-the-compiler) | `input_type(node, slot)` | +| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `push_reflection`, `remove`, `truncate`, `len` | | `&mut Upstream` | Nodes feeding the anchor | `add_node`, `add_node_keyed`, `remove_node` | | `&mut Downstream` | Whatever reads the anchor's outputs | `consumers`, `add_node`, `add_node_keyed`, `connect` | +| `&mut Target` | Which declaration the anchor becomes, see [Choosing a target](#choosing-a-target) | `set` | +| `&mut Attributes` | Attributes of the anchor and of the nodes you add, see [Placing and naming nodes](#placing-and-naming-nodes) | `set`, `remove` | Reads always see the old document. `node.inputs()` returns the old layout however many edits you've made, and nodes you add never show up in `consumers`. `Inputs` edits apply in order to the layout being built. After `inputs.insert(1, ...)`, later `Inputs` calls see the old slot 1 as slot 2. `node.inputs()[1]` is still the old slot 1. +An input the compiler fills in, like a node's own path, is added with `inputs.push_reflection(...)`, which takes a frozen mirror of the `DocumentNodeMetadata` variant it reflects. + ### Values A migration has to keep working after the code around it changes, so it can't use live types like `TaggedValue`. Declare an enum with only the variants you read or write, named the same as in `TaggedValue`: @@ -184,9 +189,72 @@ rename!("graphene_core::ops::AddNode"@1 => "math_nodes::AddNode"@2); When the replacement also changes the inputs, scaffold a function with `cargo run migration new @ `. The new node has to be at `version + 1`. +### Choosing a target + +When a node splits into several, one target can't fit every anchor. `Target::set` switches this anchor to another declaration instead, named with `decl!` in the function body so the runner can order the migration against it. It can have any version, so a node that is only a target doesn't need a version bump, and documents that hold it but not the old node aren't rewritten. Only the target in the attribute has to be at `version + 1`. + +```rust +/// Fill and stroke became separate nodes. +#[migration("vector_nodes::style"@1 => "vector_nodes::vary_fill"@2)] +pub fn vary_from_style(node: &Node, target: &mut Target) { + if literal_of::(&node.inputs()[STROKE].input).is_some_and(|stroke| stroke == Tagged::Bool(true)) { + target.set(decl!("vector_nodes::vary_stroke"@1)); + } +} +``` + +A wire written to a removed node brings that node back, so avoid switching a wire on and off depending on state. Keep the slot reading the same thing, and add nodes downstream of the anchor instead. + +### Placing and naming nodes + +Nodes you add are placed beside the anchor for you, from the anchor's own stored position. Those leading up to the anchor's primary input form a row to its left, or join its layer's chain. Others feeding the anchor or that row sit below the first one reading them, and the rest start on the anchor. A chained anchor has no coordinates of its own, so only its chain is placed, and an anchor with no stored position gets nothing placed. `Attributes::set` writes an attribute of the anchor or of a node this run adds, named by the ID `add_node` returned, and `remove` deletes one. A display name stored as the old node's default would misname the new one, so clear it: + +```rust +if node.attributes().get_typed::(DISPLAY_NAME).as_deref() == Some("Copy to Points") { + attributes.remove(node.id(), DISPLAY_NAME); +} +``` + +Writing to any other node fails, since another anchor's run may be editing it. + +### Network definitions + +Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: + +```rust +rename!(network "Artboard"@1 => @2); +``` + +To replace a subgraph with a proto node, make the node the target. As with any replacement, the node has to be at `version + 1`: + +```rust +rename!(network "Merge"@1 => "graphic_nodes::merge"@2); +``` + +The runner removes the instance's network with every node in it, including nodes the user added, and keeps the instance's inputs. If the proto node's inputs are laid out differently, write a function with `#[migration(network "Merge"@1 => "graphic_nodes::merge"@2)]` and change them through `&mut Inputs`. A proto node can't become a network definition. + +An instance only exists once both its node and its network are in the document, so these migrations run on whole states, like the ones reading `&Graph`. + +### Asking the compiler + +Which node a migration inserts can depend on the type flowing through a wire, such as a flatten node restoring what a group erased. Such a migration goes in the `migration-compiled` crate, which links the node crates, and takes `Option<&dyn Compiler>`. It compares with `element_is`, which only compares `type_name`s within the running build, so no type name is ever stored, and removing a type breaks the build rather than changing the result: + +```rust +#[migration("vector_nodes::copy"@1 => "vector_nodes::flatten_graphic"@2)] +pub fn flatten_by_type(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) { + if compiler.and_then(|compiler| compiler.input_type(node, CONTENT)).is_some_and(|value_type| value_type.element_is::()) { + target.set(decl!("vector_nodes::flatten_vector"@1)); + } +} +``` + +There may be no compiler, and it may not have an answer, for a state that doesn't compile or for what only exists at runtime, so always have a fallback. A migration reading `&Graph` or asking the compiler runs on whole states only: the end of each interaction, which is what undo can land on, with everything since the previous one rewritten as one step. A document imported without history is therefore one evaluation. Migrations asking the compiler run as late as their dependencies allow, with upstream anchors first, so what they ask about is usually in its current shape. A document holding none of their nodes never builds the compiler or loads a declaration for it. + +Their result depends on the build, so peers on different builds can disagree, which is why other migrations should avoid the compiler wherever they can. + ### What the function may depend on -A migration runs many times on one document, once per relevant step of its history, and every collaborator has to get the same result. So it can only depend on its parameters. Randomness, clocks, global state, and calls into live node code are all off limits. +A migration runs many times on one document, once per relevant step of its history, and every collaborator has to get the same result. So it can only depend on its parameters. Randomness, clocks, global state, and calls into live node code outside of the compiler are all off limits. It also has to handle every state the old version allowed, including wired inputs and exposed literals. Return `MigrationError::invariant` if the old state breaks its own node's rules. Return `MigrationError::unrepresentable` if the new version can't express something the old one could, which usually means the new version should change. Both are bugs. If one fires on an old step of a document's history, the document opens with its history cut off at that point. If it fires on the current state, the document doesn't open. @@ -253,7 +321,7 @@ Finish with `cargo run migration check` and `cargo test -p migration-formats`. T ## Regression corpus -The [corpus](https://github.com/tagtraumen/graphite-corpus) is a separate repository of real documents and the images they should render. CI checks every pull request against it. A correct migration keeps a document looking the same, so `check` should still pass with your change: +The [corpus](https://github.com/GraphiteEditor/document-corpus) is a separate repository of real documents and the images they should render. CI checks every pull request against it. A correct migration keeps a document looking the same, so `check` should still pass with your change: ```sh cargo run regression --corpus check @@ -265,4 +333,4 @@ Leave corpus documents as they were added. They're there to prove that old files ## Current limits -A document whose history contains merges can't have that history rewritten, so migrating it restarts history from the migrated state and undo can't reach further back. Nodes generated by `#[derive(Destructure)]` can't be scaffolded, because they have no function of their own to carry a version. +A document whose history contains merges can't have that history rewritten, so migrating it restarts history from the migrated state and undo can't reach further back. Nodes generated by `#[derive(Destructure)]` can't be scaffolded, because they have no function of their own to carry a version. `cargo run migration check` doesn't see network definitions yet, so an editor test catches a bumped `version` without a migration instead, and `cargo run migration new` can't scaffold one. diff --git a/website/sass/component/credits-names.scss b/website/sass/component/credits-names.scss new file mode 100644 index 00000000000..1ff2e025dd2 --- /dev/null +++ b/website/sass/component/credits-names.scss @@ -0,0 +1,258 @@ +// ==================== +// MEMBER CREDITS NAMES +// ==================== + +// Names flow along each row at their own widths, so one only breaks across lines when it's wider than the whole row +.credits-names { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.25em 1.5em; + padding: 0; + list-style: none; + line-height: 1.25; + + li { + display: flex; + align-items: center; + gap: 0.4em; + margin-top: 0; + overflow-wrap: anywhere; + // Keeps the particles drawn behind the name in front of the page + position: relative; + isolation: isolate; + } + + img { + flex: 0 0 auto; + width: 1.5em; + height: 1.5em; + object-fit: cover; + } +} + +// The membership page's preview takes its member's tier too, sizing its name like the site credits +:is(.credits-tier, .credits-preview) { + // Names spread apart in the tiers with particle effects, which need the room + &:is(.diamond, .carbide) .credits-names { + gap: 2em 2.5em; + } + + &.diamond .credits-names { + font-size: 2rem; + } + + &.carbide .credits-names { + font-size: 1.75rem; + } + + &.graphene .credits-names { + font-size: 1.5rem; + } + + &.graphite .credits-names { + font-size: 1.375rem; + } + + &.charcoal .credits-names { + font-size: 1.25rem; + } + + &.carbon .credits-names { + font-size: 1.125rem; + } + + &.proton .credits-names { + font-size: 0.875rem; + } +} + +// Links take the same color as the other names, set apart only by their underline +.credits-name { + color: var(--name-color, inherit); +} + +// Underlined explicitly, so the membership page's preview matches without a real address +a.credits-name { + text-decoration: underline; +} + +// ================ +// NAME COLOR FADES +// ================ + +// The colors paint a background that shows only through the see-through letters +.name-fade > .credits-name { + color: transparent; + background-image: linear-gradient(90deg, var(--name-color), var(--name-fade-colors)); + background-clip: text; + text-decoration-color: var(--name-color); +} + +// Stretched so wide that the name covers an almost even sliver, which slides through each color in turn +.name-fade.fade > .credits-name { + background-size: calc(5000% * (var(--name-color-count, 2) - 1)) 100%; + animation: credits-name-fade calc(1.5s * (var(--name-color-count, 2) - 1)) ease-in-out infinite alternate; +} + +// Returns to the first color at its end, so each tile of the repeating gradient meets the next seamlessly +.name-fade.flow > .credits-name { + background-image: linear-gradient(90deg, var(--name-color), var(--name-fade-colors), var(--name-color)); + background-size: calc(100% * var(--name-color-count, 2)) 100%; + animation: credits-name-flow calc(2s * var(--name-color-count, 2)) linear infinite; +} + +// A band of the other colors sweeps across, then waits off to the side before the next pass +.name-fade.shimmer > .credits-name { + background-image: linear-gradient(100deg, var(--name-color) 40%, var(--name-fade-colors), var(--name-color) 60%); + background-size: 300% 100%; + background-repeat: no-repeat; + animation: credits-name-shimmer 3s ease-in-out infinite; +} + +// Flow turned upright, so the colors climb through the letters like rising heat +.name-fade.rise > .credits-name { + background-image: linear-gradient(0deg, var(--name-color), var(--name-fade-colors), var(--name-color)); + background-size: 100% calc(100% * var(--name-color-count, 2)); + animation: credits-name-rise calc(2s * var(--name-color-count, 2)) linear infinite; +} + +// Crisp-edged bands half again as wide as the name slide past, so each new color sweeps across and then holds before the next +.name-fade.wipe > .credits-name { + background-image: linear-gradient(270deg, var(--name-color-bands)); + background-size: calc(320% * var(--name-color-count, 2)) 100%; + animation: credits-name-wipe calc(2.8s * var(--name-color-count, 2)) linear infinite; +} + +// Thin diagonal bands on a square tile, which tiles seamlessly because the colors repeat twice across it +.name-fade.stripes > .credits-name { + background-image: linear-gradient(45deg, var(--name-color-bands)); + background-size: calc(0.5em * var(--name-color-count, 2)) calc(0.5em * var(--name-color-count, 2)); + animation: credits-name-stripes calc(1.5s * var(--name-color-count, 2)) linear infinite; +} + +// Rings of the colors spread outward from the middle, by pushing out where the repeating rings begin +@property --credits-name-ripple { + syntax: ""; + inherits: false; + initial-value: 0px; +} + +.name-fade.ripple > .credits-name { + background-image: repeating-radial-gradient( + circle, + var(--name-color) var(--credits-name-ripple), + var(--name-fade-colors), + var(--name-color) calc(var(--credits-name-ripple) + 1.8em * var(--name-color-count, 2)) + ); + animation: credits-name-ripple calc(1.5s * var(--name-color-count, 2)) linear infinite; +} + +// The name keeps its first color, backlit by a soft glow of the others that brightens and dims +.name-fade.glow > .credits-name { + position: relative; + color: var(--name-color); + background-image: none; + + &::before { + content: ""; + position: absolute; + inset: -0.1em -0.3em; + z-index: -1; + border-radius: 0.6em; + background-image: linear-gradient(90deg, var(--name-fade-colors), var(--name-fade-colors)); + filter: blur(0.35em); + animation: credits-name-glow 2.4s ease-in-out infinite alternate; + } +} + +@keyframes credits-name-fade { + to { + background-position-x: 100%; + } +} + +// Moves by exactly one tile, which as a percentage depends on how many times wider than the name the tile is +@keyframes credits-name-flow { + to { + background-position-x: calc(-100% * var(--name-color-count, 2) / (var(--name-color-count, 2) - 1)); + } +} + +@keyframes credits-name-shimmer { + from { + background-position-x: 100%; + } + + 60%, + to { + background-position-x: 0%; + } +} + +// Each moves by exactly one tile, like the flow +@keyframes credits-name-rise { + to { + background-position-y: calc(100% * var(--name-color-count, 2) / (var(--name-color-count, 2) - 1)); + } +} + +@keyframes credits-name-wipe { + to { + background-position-x: calc(-100% * 3.2 * var(--name-color-count, 2) / (3.2 * var(--name-color-count, 2) - 1)); + } +} + +@keyframes credits-name-stripes { + to { + background-position-x: calc(0.5em * var(--name-color-count, 2)); + } +} + +@keyframes credits-name-ripple { + to { + --credits-name-ripple: calc(1.8em * var(--name-color-count, 2)); + } +} + +@keyframes credits-name-glow { + from { + opacity: 0.2; + scale: 0.95; + } + + to { + opacity: 0.65; + scale: 1.05; + } +} + +@media (prefers-reduced-motion: reduce) { + .name-fade > .credits-name, + .name-fade > .credits-name::before { + animation: none; + } + + .name-fade.glow > .credits-name::before { + opacity: 0.45; + } +} + +// ========= +// PARTICLES +// ========= + +// Drawn by the credits particles script, reaching past the name on every side +.credits-particles { + position: absolute; + top: -1em; + left: -1em; + width: calc(100% + 2em); + height: calc(100% + 2em); + z-index: -1; + pointer-events: none; + + &.front { + z-index: 1; + } +} diff --git a/website/sass/page/donate.scss b/website/sass/page/donate.scss index ccf3145b305..bfe35f6d83d 100644 --- a/website/sass/page/donate.scss +++ b/website/sass/page/donate.scss @@ -42,7 +42,7 @@ align-self: stretch; margin-top: calc(40 * var(--variable-px)); - // Hides these while the stats API request is still in flight or has failed + // Hides these when the Worker had no fresh tally to fill them with &:has(.value:empty) { visibility: hidden; } @@ -101,11 +101,23 @@ // DONATION PICKER // =============== +// Holds the picker with the link to manage a membership beneath it +.donation-picker-column { + flex: 1 1 420px; + display: flex; + flex-direction: column; + + .manage { + align-self: flex-end; + margin-top: calc(20 * var(--variable-px)); + font-size: calc(1rem * 7 / 9); + } +} + .donation-picker { // Shrinks the checkout button, which is the only thing in here sized off this variable --font-size-link: calc(1rem * 10 / 9); - flex: 1 1 420px; box-sizing: border-box; position: relative; display: flex; @@ -117,6 +129,13 @@ background-blend-mode: overlay; background-position: center; + // Shown by the Worker to a signed-in member, styled like the membership page's notices + .member-notice { + padding: 12px 20px; + margin-bottom: 10px; + background-color: var(--color-seaside); + } + // Every visibility rule below is driven by these, so they're taken out of the layout without losing keyboard focusability input:is([type="radio"], [type="checkbox"]) { position: absolute; @@ -308,18 +327,11 @@ flex-direction: column; gap: 10px; - // Carried by the toggle rather than the wrapper, so the separation above it never changes .payment-method { margin-top: calc(20 * var(--variable-px)); } } - .manage { - align-self: flex-end; - margin-top: calc(20 * var(--variable-px)); - font-size: calc(1rem * 7 / 9); - } - .action { grid-area: 3 / 1; display: none; @@ -438,23 +450,73 @@ .tier-panel[data-frequency="one-time"] { display: contents; } - - // There is no ongoing membership to manage from a one-time gift - .manage { - display: none; - } } -.donation-picker:has([value="direct"]:checked) .github-only { - color: Rgb(from var(--color-navy) r g b / 0.33); +// There is no ongoing membership to manage from a one-time gift +.donation-picker-column:has([value="one-time"]:checked) .manage { + display: none; } -.donation-picker:has([value="github"]:checked) .manage { - color: Rgb(from var(--color-crimson) r g b / 0.33); - pointer-events: none; +.donation-picker:has([value="direct"]:checked) .github-only { + display: none; } .donation-picker:has([value="direct"]:checked) :is(.action, .method-note)[data-method="direct"], .donation-picker:has([value="github"]:checked) :is(.action, .method-note)[data-method="github"] { display: block; } + +// ============== +// MEMBER CREDITS +// ============== + +.member-credits { + .credits-tiers { + align-self: stretch; + display: flex; + flex-direction: column; + gap: calc(80 * var(--variable-px)); + margin-top: calc(40 * var(--variable-px)); + } + + h3 { + display: flex; + align-items: center; + gap: 0.75em; + text-transform: uppercase; + color: var(--color-ale); + + // Rules off the rest of the row, so each tier reads as its own section + &::after { + content: ""; + flex: 1 1 0; + height: var(--border-thickness); + background-color: currentColor; + } + } +} + +// =============== +// ACKNOWLEDGMENTS +// =============== + +.acknowledgments { + .acknowledgment-logos { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: calc(40 * var(--variable-px)) calc(60 * var(--variable-px)); + margin-top: calc(40 * var(--variable-px)); + + a { + min-width: 0; + max-width: 100%; + } + } + + img { + display: block; + max-width: 100%; + height: auto; + } +} diff --git a/website/sass/page/membership.scss b/website/sass/page/membership.scss new file mode 100644 index 00000000000..36d8a9535b6 --- /dev/null +++ b/website/sass/page/membership.scss @@ -0,0 +1,894 @@ +// ========================= +// INTRODUCTION BESIDE PANEL +// ========================= + +.diptych.membership-hero { + align-items: flex-start; + + > .block { + flex: 1 1 420px; + + h1 { + text-wrap: balance; + } + + // Spaced like the paragraphs beside it, since it's a wrapper the Worker can remove whole + .billing-note { + margin-top: 20px; + } + } +} + +// ============ +// MEMBER PANEL +// ============ + +// Shares the donation picker's look, down to the size of its buttons +.membership-panel { + --font-size-link: calc(1rem * 10 / 9); + + flex: 1 1 420px; + box-sizing: border-box; + padding: calc(var(--feature-box-padding) / 2 * var(--variable-px)); + background-color: var(--color-cloud); + background-image: url("https://static.graphite.art/textures/noise.png"); + background-blend-mode: overlay; + background-position: center; + + p { + text-align: left; + text-justify: auto; + } + + h2 { + font-size: calc(1rem * 8 / 9); + font-weight: 800; + text-transform: uppercase; + } + + // Hyphenated like paragraphs, since these are divs the Worker can remove whole + .aside, + .notice { + hyphens: auto; + } + + .aside { + font-size: calc(1rem * 7 / 9); + } + + .button { + display: block; + background-color: var(--color-fog); + text-align: center; + } + + button.button { + width: 100%; + font-family: inherit; + cursor: pointer; + } + + // Collapsed unless the Worker revealed one of its notices + .notices:not(:has(.notice:not([hidden]))) { + display: none; + } + + .notice { + padding: 12px 20px; + background-color: var(--color-peach); + + &.confirmation { + background-color: var(--color-seaside); + } + } + + // A passing confirmation folds away once it's had time to be read, closing the gap above it too + .notices:has(.notice.passing:not([hidden])) { + display: grid; + grid-template-rows: 1fr; + animation: passing-notices-leave 0.4s ease-in 5s forwards; + + .notice { + min-height: 0; + overflow: hidden; + animation: passing-notice-leave 0.4s ease-in 5s forwards; + } + + @keyframes passing-notices-leave { + to { + grid-template-rows: 0fr; + margin-top: calc(-1 * var(--section-gap)); + display: none; + } + } + + @keyframes passing-notice-leave { + to { + padding-block: 0; + opacity: 0; + } + } + } + + .email-change-confirmation { + display: flex; + flex-direction: column; + gap: 10px; + overflow-wrap: anywhere; + + &[hidden] { + display: none; + } + } + + .signed-out { + .notices { + margin-bottom: 20px; + } + + .button { + margin-top: 10px; + } + + .sign-in { + margin-top: 20px; + + .aside { + margin-top: 20px; + } + } + + // Only the sign-in for how the member pays shows, once they've chosen it + &:not(:has(input[value="direct"]:checked)) .sign-in.direct, + &:not(:has(input[value="github"]:checked)) .sign-in.github { + display: none; + } + } + + // Drawn like the donation picker's own choice between the two + .payment-method { + display: flex; + gap: 10px; + margin-top: 10px; + + label { + flex: 1 1 0; + padding: 0.4em 0; + text-align: center; + font-weight: 800; + background-color: var(--color-fog); + cursor: pointer; + + &:hover { + background-color: var(--color-lemon); + } + + &:has(input:checked) { + background-color: var(--color-navy); + color: var(--color-parchment); + } + + &:has(input:focus-visible) { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + } + + // Out of the layout but still reachable by keyboard + input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + margin: 0; + } + } + + .signed-in { + --section-gap: 20px; + + display: flex; + flex-direction: column; + gap: var(--section-gap); + + &[hidden] { + display: none; + } + } + + .account { + display: flex; + align-items: center; + gap: 12px; + + .account-name { + flex: 1 1 auto; + overflow-wrap: anywhere; + + // The username always gets a line of its own + strong { + display: block; + } + } + } + + .change-email { + display: flex; + flex-direction: column; + gap: 10px; + + &[hidden] { + display: none; + } + } + + // A minor action beside what it acts on, like signing out or unlinking an account + .text-button { + flex: 0 0 auto; + padding: 0; + border: none; + background: none; + font: inherit; + font-size: calc(1rem * 7 / 9); + font-weight: 800; + text-transform: uppercase; + color: var(--color-crimson); + cursor: pointer; + } + + .membership { + display: flex; + flex-direction: column; + gap: calc(40 * var(--variable-px)); + margin-top: calc(20 * var(--variable-px)); + } + + .tier { + display: flex; + flex-direction: column; + + .tier-name { + font-family: "Bona Nova", Palatino, serif; + font-feature-settings: "lnum"; + font-weight: 700; + line-height: 1.25; + font-size: calc(1rem * 8 / 3); + } + + .tier-terms { + font-size: calc(1rem * 7 / 9); + font-weight: 800; + text-transform: uppercase; + color: var(--color-walnut); + } + } + + .billing, + .discord, + .credits { + display: flex; + flex-direction: column; + gap: 10px; + + h2 { + margin-bottom: 10px; + } + } + + .billing .notice { + margin: 0; + } + + // Each direct membership's renewal date, over the buttons that send its member to Stripe + .stripe-memberships { + display: flex; + flex-direction: column; + gap: 20px; + } + + .stripe-membership { + display: flex; + flex-direction: column; + gap: 10px; + } + + // Changing and ending the membership pair up in halves, with the overview on its own row + .stripe-membership-tasks { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + + .button[value="overview"] { + grid-column: 1 / -1; + } + } + + // The diptych layout makes decorative pictures blocks, which would otherwise outrank their hidden attribute + .credits img[hidden] { + display: none; + } + + // Speaking the name reveals only the spoken name, and showing it reveals everything else + .credits:not(:has([name="speak_in_video_credits"]:checked)) .spoken-name-field, + .credits:not(:has(:is([name="show_in_site_credits"], [name="show_in_video_credits"]):checked)) > .name-opt-in ~ :not(button, .spoken-name-field) { + display: none; + } + + // Grayed out while there's nothing to save or no sign-in email to resend yet + button.button:disabled { + opacity: 0.4; + cursor: default; + } + + // The linked account's name, beside the button that unlinks it + .linked-account { + display: flex; + align-items: center; + gap: 10px; + + &[hidden] { + display: none; + } + + .linked-account-name { + flex: 1 1 auto; + min-width: 0; + font-weight: 700; + // The gold nametag the member has in our Discord server + color: #ff8400; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } + + .field-label { + font-size: calc(1rem * 7 / 9); + font-weight: 800; + text-transform: uppercase; + color: var(--color-walnut); + } + + .field-hint { + font-size: calc(1rem * 7 / 9); + color: var(--color-walnut); + } + + .field { + display: flex; + flex-direction: column; + gap: 4px; + + :is(input, select) { + box-sizing: border-box; + height: calc(var(--font-size-link) * 2); + padding: 0 0.5em; + font: inherit; + color: var(--color-navy); + background-color: white; + border: var(--border-thickness) solid var(--color-navy); + border-radius: 0; + + &:focus-visible { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + } + + // Drawn with its own arrow, since the native one ignores the page's look + select { + appearance: none; + padding-right: 2em; + background-image: url('data:image/svg+xml;utf8,'); + background-position: right 0.5em center; + background-repeat: no-repeat; + background-size: 1em; + cursor: pointer; + + &:hover { + background-color: var(--color-lemon); + } + } + } + + .field[hidden] { + display: none; + } + + // Rewards above the member's tier, until they're tried on + .credits .locked-reward { + display: none; + } + + // Rewards above the member's tier, while they're tried on, down to what's typed or chosen in them + .credits .previewed-reward { + &, + input, + select { + font-style: italic; + } + + option:not(.previewed-reward) { + font-style: normal; + } + } + + // Beside the label of each reward above the member's own tier + .tier-badge { + margin-left: 0.75em; + padding: 0.1em 0.5em; + font-size: calc(1rem * 7 / 9); + font-weight: 800; + text-transform: uppercase; + color: var(--color-fog); + background-color: var(--color-crimson); + } + + // An action in a line of text, which reads as a link + .link-button { + padding: 0; + border: none; + background: none; + font: inherit; + color: var(--color-crimson); + text-decoration: underline; + cursor: pointer; + } + + // Spaced from the fields below as far as from the heading above + .preview-toggle { + align-self: flex-start; + margin-bottom: 10px; + text-align: left; + font-size: calc(1rem * 7 / 9); + } + + .preview-notice { + margin-bottom: 10px; + font-size: calc(1rem * 7 / 9); + color: var(--color-crimson); + + // Links rather than buttons, which can't wrap across lines of text + a { + font-weight: 700; + } + } + + // A row of chosen items followed by buttons to add and remove them, where squares narrow together when the row is too short + .tile-row { + --tile-size: calc(var(--font-size-link) * 2); + + position: relative; + display: flex; + gap: 8px; + margin-top: 4px; + user-select: none; + + &[hidden] { + display: none; + } + + &.shape-row { + flex-wrap: wrap; + } + + .tiles { + display: contents; + } + + .swatch, + .tile-button { + flex: 0 1 var(--tile-size); + min-width: 0; + height: var(--tile-size); + + &[hidden] { + display: none; + } + } + + .shape-choice { + position: relative; + display: flex; + + select { + width: auto; + } + } + + // Horizontal touch moves drag the color, leaving vertical ones to scroll the page + .swatch { + position: relative; + display: flex; + touch-action: pan-y; + + &.dragged { + translate: 0 -4px; + } + } + + &.dragging input[type="color"] { + cursor: grabbing; + } + + .tile-button { + box-sizing: border-box; + padding: 0; + font: inherit; + font-size: var(--font-size-link); + font-weight: 800; + line-height: 1; + color: var(--color-navy); + background-color: white; + border: var(--border-thickness) solid var(--color-navy); + cursor: pointer; + + &:hover:not(:disabled) { + background-color: var(--color-lemon); + } + + &[aria-pressed="true"] { + color: var(--color-parchment); + background-color: var(--color-navy); + } + + &:disabled { + opacity: 0.4; + cursor: default; + } + + &:focus-visible { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + } + + // While removing, the item under the pointer or keyboard focus is crossed out + &.removing :is(.swatch, .shape-choice):is(:hover, :focus-within)::after { + content: ""; + position: absolute; + inset: 0; + pointer-events: none; + background: rgb(255 255 255 / 0.65) + url('data:image/svg+xml;utf8,') + center / auto 70% no-repeat; + } + + input[type="color"] { + width: 100%; + height: 100%; + padding: 3px; + cursor: pointer; + + &::-webkit-color-swatch-wrapper { + padding: 0; + } + + // Kept apart, since a browser drops a whole rule over a pseudo-element it doesn't know + &::-webkit-color-swatch { + border: none; + } + + &::-moz-color-swatch { + border: none; + } + + &.editing { + border-color: var(--color-crimson); + } + } + } + + // A lone color to the right of the menu, sized like the squares it otherwise sits among + .field.color-beside-menu { + display: grid; + grid-template-columns: 1fr calc(var(--font-size-link) * 2); + column-gap: 8px; + + .field-label { + grid-column: 1 / -1; + } + + .tile-row { + margin-top: 0; + } + } + + // Opens below the color it edits, with the brightness falling toward the bottom of the square and the saturation rising toward its right + .color-popover { + position: absolute; + top: calc(100% + 8px); + left: 0; + z-index: 2; + display: grid; + grid-template-columns: 1fr auto; + gap: 8px; + box-sizing: border-box; + width: 240px; + padding: 8px; + background-color: white; + border: var(--border-thickness) solid var(--color-navy); + user-select: auto; + + &[hidden] { + display: none; + } + + .saturation-value, + .hue-slider { + position: relative; + touch-action: none; + + &:focus-visible { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + } + + .saturation-value { + aspect-ratio: 1; + background: linear-gradient(to top, black, transparent), linear-gradient(to right, white, hsl(var(--hue) 100% 50%)); + cursor: crosshair; + } + + .hue-slider { + width: 20px; + background: linear-gradient(to bottom, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); + cursor: ns-resize; + } + + // Ringed in white and then black, so they show against any color + .saturation-value-handle, + .hue-handle { + position: absolute; + box-sizing: border-box; + border: 2px solid white; + box-shadow: + 0 0 0 1px rgb(0 0 0 / 0.6), + inset 0 0 0 1px rgb(0 0 0 / 0.6); + pointer-events: none; + } + + .saturation-value-handle { + left: calc(var(--saturation) * 100%); + top: calc((1 - var(--value)) * 100%); + width: 14px; + height: 14px; + translate: -50% -50%; + border-radius: 50%; + } + + .hue-handle { + left: -3px; + right: -3px; + top: calc(var(--hue) / 360 * 100%); + height: 8px; + translate: 0 -50%; + } + + .hex-field { + grid-column: 1 / -1; + width: 100%; + font-variant-numeric: tabular-nums; + } + } + + .credits-preview { + display: flex; + flex-direction: column; + gap: 4px; + + &[hidden] { + display: none; + } + + // Leaves room for the particles, which are cut off at the edge + .credits-names { + margin: 0; + padding: 1em; + overflow: hidden; + background-color: white; + } + + // A long name runs off the edge rather than wrapping, which would break up its colors + li { + white-space: nowrap; + overflow-wrap: normal; + } + + // Clicking it selects the name field + .credits-name { + cursor: text; + } + } + + .avatar-field { + display: flex; + flex-direction: column; + gap: 4px; + } + + .avatar-picker { + display: flex; + align-items: center; + gap: 12px; + + .avatar { + flex: 0 0 auto; + width: 72px; + height: 72px; + object-fit: cover; + background-color: var(--color-fog); + + &[hidden] { + display: none; + } + } + + .avatar-controls { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; + } + + .checkbox[hidden] { + display: none; + } + + // The native picker words its own status, so it's hidden but still focusable behind a button and status of the page's own + .file-picker { + position: relative; + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + font-size: calc(1rem * 7 / 9); + color: var(--color-walnut); + + input[type="file"] { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; + } + } + + // Drawn like the panel's other buttons + .file-picker-button { + flex: 0 0 auto; + box-sizing: border-box; + height: calc(var(--font-size-link) * 2); + padding: 0 1em; + line-height: calc(var(--font-size-link) * 2 - 2 * var(--border-thickness)); + font-weight: 800; + text-transform: uppercase; + color: var(--color-crimson); + background-color: var(--color-fog); + border: var(--border-thickness) solid currentColor; + cursor: pointer; + + &:hover { + background-color: var(--color-lemon); + } + } + + input[type="file"]:focus-visible + .file-picker-button { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + + .file-picker-status { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } + + .avatar-cropper { + display: flex; + flex-direction: column; + gap: 8px; + max-width: 280px; + margin-top: 8px; + + &[hidden] { + display: none; + } + + // The square that gets uploaded, with the picture moved and scaled behind it + .crop-frame { + position: relative; + box-sizing: border-box; + aspect-ratio: 1; + overflow: hidden; + background-color: var(--color-fog); + border: var(--border-thickness) solid var(--color-navy); + cursor: grab; + touch-action: none; + + &:active { + cursor: grabbing; + } + + &:focus-visible { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + + img { + position: absolute; + top: 0; + left: 0; + max-width: none; + height: auto; + pointer-events: none; + user-select: none; + } + } + + .crop-zoom { + display: flex; + align-items: center; + gap: 12px; + + input { + flex: 1 1 auto; + margin: 0; + accent-color: var(--color-navy); + } + } + } + + .checkboxes { + display: flex; + flex-direction: column; + gap: 8px; + } + + // A native checkbox drawn like the name field, which fills navy with a check like a chosen donation option + .checkbox { + display: flex; + align-items: center; + gap: 0.5em; + width: fit-content; + cursor: pointer; + + input { + appearance: none; + flex: 0 0 auto; + box-sizing: border-box; + width: 1.25em; + height: 1.25em; + margin: 0; + background-color: white; + background-position: center; + background-repeat: no-repeat; + background-size: 100%; + border: var(--border-thickness) solid var(--color-navy); + border-radius: 0; + cursor: inherit; + + &:checked { + background-color: var(--color-navy); + background-image: url('data:image/svg+xml;utf8,'); + } + + &:focus-visible { + outline: var(--border-thickness) solid var(--color-crimson); + outline-offset: var(--border-thickness); + } + + // High contrast mode drops the fill behind the check, so the native control takes over + @media (forced-colors: active) { + appearance: auto; + } + } + + &:hover input:not(:checked) { + background-color: var(--color-lemon); + } + } +} diff --git a/website/sass/template/book.scss b/website/sass/template/book.scss index 90d1dd6a90e..5fd9d4fd4ab 100644 --- a/website/sass/template/book.scss +++ b/website/sass/template/book.scss @@ -38,6 +38,11 @@ width: 100%; } + .development-notice { + padding: 12px 20px; + background: var(--color-lemon); + } + .prev-next { display: flex; justify-content: space-between; diff --git a/website/static/js/component/credits-particles.js b/website/static/js/component/credits-particles.js new file mode 100644 index 00000000000..fe3123e5bb4 --- /dev/null +++ b/website/static/js/component/credits-particles.js @@ -0,0 +1,1519 @@ +/** + * @typedef {{ left: number, top: number, width: number, height: number, em: number }} ParticleArea + * The name's box within its canvases, which reach past it on every side, along with its font size. + * + * @typedef {{ + * x: number, y: number, vx: number, vy: number, phase: number, phaseSpeed: number, + * age: number, life: number, size: number, angle: number, spin: number, seed: number, slot: number, driftX: number, color: string, front: boolean, shape: ParticleShape, + * }} Particle + * Positions and sizes are in CSS pixels, speeds are per second, and angles are in radians. A `slot` places a particle among a motion's steady count. + * Its `driftX` is how fast it has lately been moving sideways, however its motion moves it. + * + * @typedef {{ + * colors: string[], + * size: [number, number], + * tilt: number, + * spin: number, + * density: number, + * draw: (context: CanvasRenderingContext2D, particle: Particle, radius: number, area: ParticleArea) => void, + * }} ParticleShape + * What each particle looks like, drawn around the origin and already turned to the particle's angle, in the member's particle colors or else its own. + * Its size is in ems, its tilt and spin are the most either way, and its density scales how many of it a motion makes. + * + * @typedef {{ + * rate?: number, + * count?: number, + * group?: number, + * spawn: (area: ParticleArea, index: number, origin: { x: number, y: number }, count: number) => Partial, + * update?: (particle: Particle, seconds: number, area: ParticleArea) => void, + * envelope: (particle: Particle) => [scale: number, opacity: number], + * trail?: (particle: Particle, area: ParticleArea) => { x: number, y: number }[], + * }} ParticleMotion + * Where the particles appear, how they move, and how long they last. + * It makes a `rate` of them per second for a name eight letters wide, or keeps a steady `count` alive, with at least one for each chosen shape. + * A `group` makes that many at once, sharing an `origin` picked at random within the name's box, in fractions of its width and height. + */ + +// A pause like a hidden tab resumes where it left off, rather than catching up all at once +const PARTICLES_LONGEST_STEP_SECONDS = 0.1; + +// With reduced motion, each effect is shown as a still frame from this far in +const PARTICLES_STILL_FRAME_SECONDS = 2; + +const PARTICLES_LIMIT = 150; + +// A maple leaf, traced from its top tip down the right side to the end of its stem and back up the left +const MAPLE_LEAF = new Path2D( + "M0,-231 C13,-196 24,-204 28,-210 C20,-172 49,-178 64,-191 C43,-172 48,-142 49,-136 C56,-140 80,-150 92,-161 C97,-150 115,-166 137,-178 " + + "C110,-158 120,-140 125,-125 C112,-115 106,-98 115,-90 C122,-84 136,-86 141,-86 C119,-82 89,-58 91,-52 C100,-46 140,-21 158,-37 C145,-22 100,0 113,15 " + + "C90,8 70,15 73,27 C35,18 7,4 2,2 C3,25 3,50 2,61 C1.5,62 0.5,62 0,62 " + + "C-0.5,62 -1.5,62 -2,61 C-3,50 -3,25 -2,2 C-7,4 -35,18 -73,27 C-70,15 -90,8 -113,15 C-100,0 -145,-22 -158,-37 C-140,-21 -100,-46 -91,-52 " + + "C-89,-58 -119,-82 -141,-86 C-136,-86 -122,-84 -115,-90 C-106,-98 -112,-115 -125,-125 C-120,-140 -110,-158 -137,-178 C-115,-166 -97,-150 -92,-161 " + + "C-80,-150 -56,-140 -49,-136 C-48,-142 -43,-172 -64,-191 C-49,-178 -20,-172 -28,-210 C-24,-204 -13,-196 0,-231 Z", +); + +// A cherry blossom petal reaching up from the flower's middle to its notched tip, about a unit long, and a leaf pointed at both ends +const BLOSSOM_PETAL = new Path2D("M0,-0.08 C0.2,-0.2 0.44,-0.45 0.4,-0.7 C0.37,-0.9 0.24,-1 0.14,-0.97 L0,-0.84 L-0.14,-0.97 C-0.24,-1 -0.37,-0.9 -0.4,-0.7 C-0.44,-0.45 -0.2,-0.2 0,-0.08 Z"); +const BLOSSOM_LEAF = new Path2D("M0,-0.5 C0.28,-0.3 0.26,0.2 0,0.5 C-0.22,0.24 -0.25,-0.26 0,-0.5 Z"); +const BLOSSOM_LEAF_COLORS = ["#c5dc4a", "#a8c83c", "#d6e566"]; + +// The right wings of a butterfly whose body runs down the middle, about two units across with both sides +const BUTTERFLY_FOREWING = new Path2D("M0.05,-0.18 C0.35,-0.75 0.85,-0.88 0.97,-0.62 C1.06,-0.4 0.86,-0.06 0.6,0.04 C0.4,0.1 0.15,0.05 0.05,0.02 Z"); +const BUTTERFLY_HINDWING = new Path2D("M0.05,0 C0.45,-0.02 0.82,0.16 0.73,0.45 C0.66,0.7 0.36,0.8 0.18,0.62 C0.1,0.52 0.05,0.32 0.05,0.15 Z"); + +// Any shape pairs with any motion, which alone decides where particles go and how long they last +/** @type {Record} */ +const PARTICLE_SHAPES = { + hearts: { + colors: ["#d2697c", "#e0435e", "#b83a5a"], + size: [0.26, 0.42], + tilt: 0.3, + spin: 0, + density: 0.55, + draw: (context, particle, radius) => { + // Two lobes meeting at a point, within a box about two units across + context.scale(radius, radius); + context.beginPath(); + context.moveTo(0, 1); + context.bezierCurveTo(-1.2, 0.2, -0.9, -0.9, 0, -0.35); + context.bezierCurveTo(0.9, -0.9, 1.2, 0.2, 0, 1); + context.fillStyle = particle.color; + context.fill(); + }, + }, + + // Jagged zigzags that flicker, reshaped every frame + bolts: { + colors: ["#5468ff", "#7a5cff", "#3f8ff5"], + size: [0.4, 0.85], + tilt: Math.PI, + spin: 0, + density: 0.4, + draw: (context, particle, radius, area) => { + const segments = 6; + context.beginPath(); + context.moveTo(-radius / 2, 0); + for (let i = 1; i <= segments; i++) context.lineTo(-radius / 2 + (radius * i) / segments, i === segments ? 0 : random(-0.18, 0.18) * area.em); + + context.strokeStyle = particle.color; + context.lineJoin = "round"; + context.lineCap = "round"; + const opacity = context.globalAlpha * random(0.4, 1); + context.globalAlpha = opacity * 0.2; + context.lineWidth = 0.2 * area.em; + context.stroke(); + context.globalAlpha = opacity; + context.lineWidth = Math.max(1, 0.055 * area.em); + context.stroke(); + }, + }, + + // Dots that glow softly around their edges + orbs: { + colors: ["#3d7bd9", "#5b9bd5", "#e8a33d"], + size: [0.08, 0.15], + tilt: 0, + spin: 0, + density: 1.3, + draw: (context, particle, radius) => { + context.fillStyle = particle.color; + const opacity = context.globalAlpha; + context.globalAlpha = opacity * 0.25; + circle(context, 0, 0, radius * 2.4); + context.globalAlpha = opacity; + circle(context, 0, 0, radius); + }, + }, + + // Bubbles with a glint, which pop at the end of their life + bubbles: { + colors: ["#4f8fa8", "#6fb3c9", "#4fa58f"], + size: [0.14, 0.3], + tilt: 0, + spin: 0, + density: 0.7, + draw: (context, particle, radius, area) => { + context.strokeStyle = particle.color; + context.fillStyle = particle.color; + context.lineWidth = Math.max(1, 0.045 * area.em); + const opacity = context.globalAlpha; + + // The last moment is a ring bursting outward + const popping = (lifeFraction(particle) - 0.88) / 0.12; + if (popping > 0) { + context.globalAlpha = opacity * (1 - popping); + context.beginPath(); + context.arc(0, 0, radius * (1 + popping * 0.8), 0, Math.PI * 2); + context.stroke(); + return; + } + + context.globalAlpha = opacity * 0.12; + circle(context, 0, 0, radius); + context.globalAlpha = opacity * 0.85; + context.beginPath(); + context.arc(0, 0, radius, 0, Math.PI * 2); + context.stroke(); + + // A glint on the upper left + context.globalAlpha = opacity * 0.6; + context.beginPath(); + context.arc(0, 0, radius * 0.62, Math.PI * 1.1, Math.PI * 1.4); + context.stroke(); + }, + }, + + // Paper scraps that flip over and over + confetti: { + colors: ["#d2697c", "#e8a33d", "#4fa58f", "#5b7bd5", "#cd8f7a"], + size: [0.2, 0.3], + tilt: Math.PI, + spin: 5, + density: 1.2, + draw: (context, particle, radius) => { + // Squashing one axis back and forth reads as the scrap flipping + context.scale(1, Math.cos(particle.age * 7 + particle.seed)); + context.fillStyle = particle.color; + context.fillRect(-radius / 2, -radius * 0.3, radius, radius * 0.6); + }, + }, + + // Four-pointed stars + stars: { + colors: ["#e8b33c", "#f2cf63", "#cd8f7a"], + size: [0.22, 0.42], + tilt: Math.PI / 4, + spin: 1.5, + density: 1, + draw: (context, particle, radius) => { + context.beginPath(); + context.moveTo(0, -radius); + context.quadraticCurveTo(0, 0, radius, 0); + context.quadraticCurveTo(0, 0, 0, radius); + context.quadraticCurveTo(0, 0, -radius, 0); + context.quadraticCurveTo(0, 0, 0, -radius); + context.fillStyle = particle.color; + context.fill(); + }, + }, + + // Bézier segments with their anchors and handles, as drawn by Graphite's Pen tool, flexing as they go + vectors: { + colors: ["#00a8ff"], + size: [0.7, 1], + tilt: Math.PI, + spin: 0.4, + density: 0.5, + draw: (context, particle, radius, area) => { + const half = radius / 2; + const handleLength = radius * 0.45; + const startAngle = Math.sin(particle.age * 1.8 + particle.seed) * 0.9 - 0.5; + const endAngle = Math.PI + Math.sin(particle.age * 1.5 + particle.seed * 2) * 0.9 + 0.5; + const anchors = [ + { x: -half, y: 0 }, + { x: half, y: 0 }, + ]; + const handles = [ + { x: -half + Math.cos(startAngle) * handleLength, y: Math.sin(startAngle) * handleLength }, + { x: half + Math.cos(endAngle) * handleLength, y: Math.sin(endAngle) * handleLength }, + ]; + context.strokeStyle = particle.color; + context.fillStyle = particle.color; + + // Handle lines, then the curve drawn on from its start, then the handle and anchor points over both + context.lineWidth = Math.max(1, 0.03 * area.em); + context.beginPath(); + anchors.forEach((anchor, i) => { + context.moveTo(anchor.x, anchor.y); + context.lineTo(handles[i].x, handles[i].y); + }); + context.stroke(); + + const drawn = Math.min(1, particle.age * 1.2); + context.lineWidth = Math.max(1.2, 0.06 * area.em); + context.beginPath(); + for (let i = 0; i <= 20; i++) { + const t = (i / 20) * drawn; + const x = cubicBezier(anchors[0].x, handles[0].x, handles[1].x, anchors[1].x, t); + const y = cubicBezier(anchors[0].y, handles[0].y, handles[1].y, anchors[1].y, t); + if (i === 0) context.moveTo(x, y); + else context.lineTo(x, y); + } + context.stroke(); + + handles.forEach((handle) => circle(context, handle.x, handle.y, 0.06 * area.em)); + const anchorSide = 0.15 * area.em; + context.fillStyle = "white"; + anchors.forEach((anchor) => { + context.fillRect(anchor.x - anchorSide / 2, anchor.y - anchorSide / 2, anchorSide, anchorSide); + context.strokeRect(anchor.x - anchorSide / 2, anchor.y - anchorSide / 2, anchorSide, anchorSide); + }); + }, + }, + + // Bats seen from the front, beating without a pause, folding their wings back up and spreading them on the way down + bats: { + colors: ["#3d3547", "#4a3b5c", "#2f2a3a"], + size: [0.24, 0.34], + tilt: 0.25, + spin: 0, + density: 0.6, + draw: (context, particle, radius, area) => { + const time = particle.age + particle.seed; + const opacity = context.globalAlpha; + + // The beat quickens and slows a little, like a bat's fluttering hunt + const beat = time * 26 + 0.8 * Math.sin(time * 2.3); + const elevation = 0.2 + 0.7 * Math.cos(beat); + // Fullest partway down and most folded partway back up + const extension = 0.775 + 0.225 * Math.sin(beat); + + // Each downstroke lifts the body a little, and the whole bat banks toward where it's heading + context.translate(0, -Math.sin(beat) * 0.06 * radius); + context.rotate(Math.max(-0.5, Math.min(0.5, (particle.driftX / area.em) * 0.25))); + context.scale(radius, radius); + context.fillStyle = particle.color; + + // The arm swings about the shoulder while the membrane stays fixed at the ankle, and the fingers fold back from the wrist as the wing closes + const shoulder = { x: 0.06, y: -0.1 }; + const ankle = { x: 0.08, y: 0.34 }; + const raise = (/** @type {{ x: number, y: number }} */ point) => { + const x = point.x - shoulder.x; + const y = point.y - shoulder.y; + return { x: shoulder.x + x * Math.cos(elevation) + y * Math.sin(elevation), y: shoulder.y - x * Math.sin(elevation) + y * Math.cos(elevation) }; + }; + const wrist = { x: 0.45 * (0.8 + 0.2 * extension), y: -0.14 }; + const finger = (/** @type {number} */ x, /** @type {number} */ y) => { + const angle = Math.atan2(y, x) + (1 - extension) * 1.3; + const length = Math.hypot(x, y) * (0.7 + 0.3 * extension); + return raise({ x: wrist.x + Math.cos(angle) * length, y: wrist.y + Math.sin(angle) * length }); + }; + const tips = [finger(0.55, 0.12), finger(0.39, 0.44), finger(0.07, 0.58)]; + const raisedWrist = raise(wrist); + + // The leading edge arches over the forearm, and the trailing edge scallops inward between each pair of fingers + const wing = new Path2D(); + const scallop = (/** @type {{ x: number, y: number }} */ from, /** @type {{ x: number, y: number }} */ to, /** @type {number} */ depth) => { + const middle = { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2 }; + wing.quadraticCurveTo(middle.x + (raisedWrist.x - middle.x) * depth, middle.y + (raisedWrist.y - middle.y) * depth, to.x, to.y); + }; + const arch = raise({ x: (shoulder.x + wrist.x) / 2, y: wrist.y - 0.07 }); + wing.moveTo(shoulder.x, shoulder.y); + wing.quadraticCurveTo(arch.x, arch.y, raisedWrist.x, raisedWrist.y); + wing.lineTo(tips[0].x, tips[0].y); + scallop(tips[0], tips[1], 0.35); + scallop(tips[1], tips[2], 0.35); + scallop(tips[2], ankle, 0.3); + wing.closePath(); + + [-1, 1].forEach((side) => { + context.save(); + context.scale(side, 1); + context.globalAlpha = opacity * 0.9; + context.fill(wing); + + // Shaded toward the body, with the arm and finger bones showing through the membrane where they're big enough to see + context.clip(wing); + const root = context.createRadialGradient(0, 0, 0, 0, 0, 0.6); + root.addColorStop(0, "rgb(0 0 0 / 0.3)"); + root.addColorStop(1, "rgb(0 0 0 / 0)"); + context.fillStyle = root; + context.fill(wing); + if (radius > 7) { + context.globalAlpha = opacity * 0.45; + context.strokeStyle = "black"; + context.lineWidth = 0.035; + context.lineCap = "round"; + context.beginPath(); + context.moveTo(shoulder.x, shoulder.y); + context.lineTo(raisedWrist.x, raisedWrist.y); + tips.forEach((tip) => { + context.moveTo(raisedWrist.x, raisedWrist.y); + context.lineTo(tip.x, tip.y); + }); + context.stroke(); + } + context.restore(); + }); + + // The body and head, with pointed ears + context.globalAlpha = opacity; + context.beginPath(); + context.ellipse(0, 0.1, 0.11, 0.24, 0, 0, Math.PI * 2); + context.fill(); + context.beginPath(); + context.arc(0, -0.17, 0.1, 0, Math.PI * 2); + context.fill(); + context.beginPath(); + [-1, 1].forEach((side) => { + context.moveTo(side * 0.02, -0.23); + context.lineTo(side * 0.11, -0.4); + context.lineTo(side * 0.1, -0.19); + }); + context.fill(); + }, + }, + + // Whole cherry blossoms facing the viewer, deepening toward the middle, where white stamens radiate if they're big enough to see + blossoms: { + colors: ["#f2849e", "#f5a3bf", "#f9c0d3", "#ee93ad"], + size: [0.2, 0.3], + tilt: Math.PI, + spin: 0.6, + density: 0.8, + draw: (context, particle, radius) => { + context.scale(radius, radius); + context.fillStyle = particle.color; + for (let i = 0; i < 5; i++) { + context.fill(BLOSSOM_PETAL); + context.rotate((Math.PI * 2) / 5); + } + context.fillStyle = "rgb(170 30 70 / 0.22)"; + circle(context, 0, 0, 0.22); + if (radius <= 6) return; + + context.strokeStyle = "white"; + context.fillStyle = "white"; + context.lineWidth = 0.045; + for (let i = 0; i < 7; i++) { + const angle = (i / 7) * Math.PI * 2; + context.beginPath(); + context.moveTo(0, 0); + context.lineTo(Math.cos(angle) * 0.27, Math.sin(angle) * 0.27); + context.stroke(); + circle(context, Math.cos(angle) * 0.3, Math.sin(angle) * 0.3, 0.045); + } + }, + }, + + // Butterflies seen from above, their beat quickening into bursts and slowing into lazy rests, banking into their turns + butterflies: { + colors: ["#e8803d", "#5b7bd5", "#7a5cff", "#4fa58f"], + size: [0.24, 0.34], + tilt: 0.35, + spin: 0, + density: 0.6, + draw: (context, particle, radius, area) => { + const time = particle.age + particle.seed; + const opacity = context.globalAlpha; + + // The beat's rate swells and eases on a curve that lingers low, so the wings spend longer in slow rests than in quick bursts + const surge = ((1 + Math.sin(time * 1.7)) / 2) ** 2; + const resting = 1 - surge; + + // How far through its beats the butterfly is, which sums its changing rate over time so the wings never jump + const slowest = Math.PI * 2.4; + const quickest = Math.PI * 9; + const beat = (/** @type {number} */ at) => { + // The integral of the surge curve, which expands to 3/8 + sin(x) / 2 - cos(2x) / 8 + const surged = (3 * at) / 8 - Math.cos(1.7 * at) / (2 * 1.7) - Math.sin(3.4 * at) / (16 * 1.7); + return slowest * at + (quickest - slowest) * surged; + }; + const stroke = (/** @type {number} */ lag) => Math.cos(beat(time - lag)); + + // Resting beats stay shallow and near open, while the quick ones close the wings almost shut + const openness = (/** @type {number} */ lag) => 0.18 + 0.82 * ((0.5 + 0.5 * stroke(lag)) * (1 - 0.5 * resting) + 0.5 * resting); + + // Each downstroke lifts the body, less so in the gentle beats, and the whole butterfly banks toward where it's heading + context.translate(0, (1 - 0.7 * resting) * stroke(0) * 0.06 * radius); + context.rotate(Math.max(-0.5, Math.min(0.5, (particle.driftX / area.em) * 0.25))); + context.scale(radius, radius); + context.lineJoin = "round"; + + // One wing seen turned partway up around the body, so its width shrinks toward the closed stroke + const wing = (/** @type {Path2D} */ shape, /** @type {number} */ side, /** @type {number} */ open, /** @type {number} */ tint) => { + context.save(); + context.scale(side * open, 1); + context.fillStyle = particle.color; + context.fill(shape); + + // Shaded where the wing meets the body, banded along its outer edge, and darker at the tip of the forewing + context.clip(shape); + const root = context.createRadialGradient(0, 0, 0, 0, 0, 0.55); + root.addColorStop(0, "rgb(0 0 0 / 0.3)"); + root.addColorStop(1, "rgb(0 0 0 / 0)"); + context.fillStyle = root; + context.fill(shape); + context.globalAlpha = opacity * 0.4; + context.strokeStyle = "black"; + context.lineWidth = 0.11; + context.stroke(shape); + context.globalAlpha = opacity * tint; + context.fillStyle = "black"; + context.beginPath(); + context.ellipse(0.95, -0.62, 0.38, 0.3, -0.5, 0, Math.PI * 2); + context.fill(); + + // Pale spots near the tip, only where they're big enough to see + if (tint > 0 && radius * open > 7) { + context.globalAlpha = opacity * 0.85; + context.fillStyle = "white"; + [ + [0.78, -0.62, 0.05], + [0.88, -0.5, 0.04], + [0.7, -0.7, 0.035], + ].forEach(([x = 0, y = 0, size = 0]) => { + context.beginPath(); + context.arc(x, y, size, 0, Math.PI * 2); + context.fill(); + }); + } + context.restore(); + }; + + // Hindwings trail the forewings slightly through each stroke, and sit beneath them + [-1, 1].forEach((side) => wing(BUTTERFLY_HINDWING, side, openness(0.012), 0)); + [-1, 1].forEach((side) => wing(BUTTERFLY_FOREWING, side, openness(0), 0.35)); + + // The body, with clubbed antennae reaching forward from the head + context.globalAlpha = opacity; + context.fillStyle = "#2b2422"; + context.strokeStyle = "#2b2422"; + context.beginPath(); + context.ellipse(0, -0.12, 0.07, 0.16, 0, 0, Math.PI * 2); + context.ellipse(0, 0.27, 0.05, 0.3, 0, 0, Math.PI * 2); + context.fill(); + context.beginPath(); + context.arc(0, -0.33, 0.065, 0, Math.PI * 2); + context.fill(); + context.lineWidth = Math.max(0.035, 0.6 / radius); + [-1, 1].forEach((side) => { + context.beginPath(); + context.moveTo(side * 0.03, -0.37); + context.quadraticCurveTo(side * 0.06, -0.6, side * 0.2, -0.7); + context.stroke(); + context.beginPath(); + context.arc(side * 0.2, -0.7, 0.035, 0, Math.PI * 2); + context.fill(); + }); + }, + }, + + // Fireworks bursting over and over, each burst a different kind of shell, slowing as they spread and sinking as they fade + fireworks: { + colors: ["#e8a33d", "#d2697c", "#5b7bd5", "#4fa58f"], + size: [0.5, 0.7], + tilt: 0, + spin: 0, + density: 0.35, + draw: (context, particle, radius) => { + // Timed from when the particle appears, so its first burst is seen from the start + const duration = 1.2 + (particle.seed % 1) * 0.4; + const burst = Math.floor(particle.age / duration); + const progress = (particle.age / duration) % 1; + const kind = (Math.floor(particle.seed) + burst) % 4; + const turn = particle.seed + burst * 2.4; + + // Air drag slows the sparks quickly while they soon settle into falling, staying bright until they burn out toward the end + const spread = (/** @type {number} */ at) => 1 - (1 - Math.max(0, at)) ** 3; + const sink = (/** @type {number} */ at) => Math.max(0, at) ** 1.6 * (kind === 1 ? 1.2 : 0.9); + const fade = 1 - progress ** 2.2; + const opacity = context.globalAlpha; + + context.scale(radius, radius); + context.fillStyle = particle.color; + context.strokeStyle = particle.color; + context.lineCap = "round"; + + // The break itself, a white flash at the center + if (progress < 0.12) { + context.globalAlpha = opacity * (1 - progress / 0.12); + context.fillStyle = "white"; + circle(context, 0, 0, 0.3 * (0.5 + progress / 0.12)); + context.fillStyle = particle.color; + } + + // Each spark flies out along its own direction, around a shell that may be smaller, flattened, or tilted, and falls straight down whatever its shell + const position = (/** @type {number} */ angle, /** @type {number} */ at, /** @type {{ size?: number, squash?: number, tilt?: number }} */ shell = {}) => { + const { size = 1, squash = 1, tilt = 0 } = shell; + const x = Math.cos(angle) * spread(at) * size; + const y = Math.sin(angle) * spread(at) * size * squash; + return { x: x * Math.cos(tilt) - y * Math.sin(tilt), y: x * Math.sin(tilt) + y * Math.cos(tilt) + sink(at) }; + }; + const trail = (/** @type {(at: number) => { x: number, y: number }} */ path, /** @type {number} */ length) => { + context.beginPath(); + for (let i = 0; i <= 4; i++) { + const point = path(progress - length * (1 - i / 4)); + if (i === 0) context.moveTo(point.x, point.y); + else context.lineTo(point.x, point.y); + } + context.stroke(); + }; + context.globalAlpha = opacity * fade; + + // A peony, a sphere of sparks seen face-on, so they fill it and crowd toward its rim, glittering as they burn out + if (kind === 0) { + const sparks = 26; + for (let i = 0; i < sparks; i++) { + // Spread evenly over the sphere by stepping the golden angle around while sweeping from pole to pole + const depth = 1 - (2 * (i + 0.5)) / sparks; + const point = position(turn + i * 2.39996, progress, { size: Math.sqrt(1 - depth * depth) }); + const twinkle = progress > 0.55 && Math.sin(particle.age * 45 + i * 2.1) < 0 ? 0.25 : 1; + context.globalAlpha = opacity * fade * twinkle; + circle(context, point.x, point.y, 0.07 * (0.4 + 0.6 * fade)); + } + } + + // A willow, whose long trails droop as they hang in the air + if (kind === 1) { + context.lineWidth = 0.05; + for (let i = 0; i < 12; i++) { + const angle = turn + (i / 12) * Math.PI * 2; + trail((at) => position(angle, at), 0.3); + } + } + + // A ring seen tilted, with a smaller ring of white inside it + if (kind === 2) { + const tilt = Math.sin(turn) * 0.6; + for (let i = 0; i < 18; i++) { + const point = position((i / 18) * Math.PI * 2, progress, { squash: 0.45, tilt }); + circle(context, point.x, point.y, 0.07 * (0.4 + 0.6 * fade)); + } + context.fillStyle = "white"; + for (let i = 0; i < 8; i++) { + const point = position((i / 8) * Math.PI * 2, progress, { size: 0.45, squash: 0.45, tilt }); + circle(context, point.x, point.y, 0.05 * fade); + } + } + + // A crossette, whose few stars each split in two halfway out + if (kind === 3) { + context.lineWidth = 0.06; + const star = (/** @type {{ x: number, y: number }} */ point) => circle(context, point.x, point.y, 0.06 * (0.5 + 0.5 * fade)); + for (let i = 0; i < 5; i++) { + const angle = turn + (i / 5) * Math.PI * 2; + if (progress < 0.45) { + trail((at) => position(angle, at), 0.15); + star(position(angle, progress)); + continue; + } + + // Past the split, each half carries on from where its star broke apart + const split = position(angle, 0.45); + [-0.55, 0.55].forEach((offset) => { + const branch = (/** @type {number} */ at) => { + if (at <= 0.45) return position(angle, at); + const beyond = (spread(at) - spread(0.45)) * 1.6; + return { x: split.x + Math.cos(angle + offset) * beyond, y: split.y + Math.sin(angle + offset) * beyond + sink(at) - sink(0.45) }; + }; + trail(branch, 0.15); + star(branch(progress)); + }); + } + } + }, + }, + + // Flames rippled by turbulence that rises through them like hot air, leaning away from their movement and now and then tearing a lick off the tip + flames: { + colors: ["#e8592b", "#f08a24", "#d2452b"], + size: [0.22, 0.34], + tilt: 0, + spin: 0, + density: 0.9, + draw: (context, particle, radius, area) => { + const time = particle.age + particle.seed; + const opacity = context.globalAlpha; + const base = radius * 0.9; + const width = radius * 0.62; + const height = radius * 2.5; + + // Drag bends the upper flame away from the way it's moving + const lean = Math.max(-1, Math.min(1, (-particle.driftX / area.em) * 0.35)) * radius; + + // The middle of the flame some fraction of the way up, swayed by ripples that travel upward and grow toward the free tip + const middle = (/** @type {number} */ fraction, /** @type {number} */ calm, /** @type {number} */ phase) => { + const ripple = Math.sin(fraction * 7 - time * 9 + phase) * 0.55 + Math.sin(fraction * 13 - time * 15.5 + phase * 2) * 0.25; + return ripple * fraction ** 1.5 * width * (1 - calm) + lean * fraction ** 2; + }; + + // One layer of the flame, traced up its right side and back down its left, then smoothed through the midpoints between + const layer = (/** @type {number} */ widthScale, /** @type {number} */ heightScale, /** @type {number} */ calm, /** @type {number} */ phase) => { + const steps = 16; + /** @type {[number, number][]} */ + const points = []; + const trace = (/** @type {number} */ fraction, /** @type {number} */ side) => { + // Widest a third of the way up, rounded at the bottom and tapering to the tip, with bulges rising along the sides + const profile = 2.8 * Math.sqrt(fraction) * (1 - fraction) ** 1.2; + const bulge = 1 + 0.15 * Math.sin(fraction * 9 - time * 12 + phase) * (1 - calm); + points.push([middle(fraction, calm, phase) + side * width * widthScale * profile * bulge, base - fraction * height * heightScale]); + }; + for (let i = 0; i <= steps; i++) trace(i / steps, 1); + for (let i = steps - 1; i > 0; i--) trace(i / steps, -1); + + const midpoint = (/** @type {[number, number]} */ a, /** @type {[number, number]} */ b) => /** @type {[number, number]} */ ([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]); + const last = points[points.length - 1]; + const first = points[0]; + if (!last || !first) return; + context.beginPath(); + context.moveTo(...midpoint(last, first)); + points.forEach((point, i) => context.quadraticCurveTo(point[0], point[1], ...midpoint(point, points[(i + 1) % points.length] || first))); + context.fill(); + }; + + // Each layer fades out toward the tip, where the flame burns away into the air + const fill = (/** @type {string} */ bottom, /** @type {string} */ top, /** @type {number} */ heightScale) => { + const gradient = context.createLinearGradient(0, base, 0, base - height * heightScale); + gradient.addColorStop(0, bottom); + gradient.addColorStop(0.55, bottom); + gradient.addColorStop(1, top); + context.fillStyle = gradient; + }; + + // A soft glow of the flame's own color + const glowY = base - height * 0.35; + const glow = context.createRadialGradient(0, glowY, 0, 0, glowY, height * 0.75); + glow.addColorStop(0, `${particle.color}40`); + glow.addColorStop(1, `${particle.color}00`); + context.fillStyle = glow; + circle(context, 0, glowY, height * 0.75); + + // The outer fire, then hotter and steadier layers toward the core + fill(particle.color, `${particle.color}33`, 1); + layer(1, 1, 0, 0); + fill("rgb(255 255 255 / 0.4)", "rgb(255 255 255 / 0)", 0.72); + layer(0.6, 0.72, 0.35, 1.3); + fill("rgb(255 255 255 / 0.8)", "rgb(255 255 255 / 0.1)", 0.42); + layer(0.34, 0.42, 0.6, 2.6); + + // Now and then the tip pinches off a lick that rises and burns away + const tearing = (time * 0.8 + particle.seed * 0.37) % 1; + if (tearing < 0.45) { + const progress = tearing / 0.45; + const size = width * 0.32 * (1 - progress); + const x = middle(1, 0, 0) + Math.sin(time * 6) * width * 0.2; + const y = base - height * (1.02 + progress * 0.4); + const curl = Math.sin(time * 5) * size * 0.6; + + // A wisp tapered at both ends, its lower end trailing toward the flame it tore from + context.globalAlpha = opacity * (1 - progress) * 0.8; + context.fillStyle = particle.color; + context.beginPath(); + context.moveTo(x + curl, y - size * 1.6); + context.quadraticCurveTo(x + size * 0.9, y - size * 0.1, x - curl * 0.5, y + size * 1.4); + context.quadraticCurveTo(x - size * 0.9, y - size * 0.1, x + curl, y - size * 1.6); + context.fill(); + } + }, + }, + + // Cut gems, their facets catching the light + gems: { + colors: ["#4fa58f", "#5b7bd5", "#d2697c"], + size: [0.16, 0.26], + tilt: 0.3, + spin: 0.8, + density: 0.8, + draw: (context, particle, radius, area) => { + context.beginPath(); + context.moveTo(-0.5 * radius, -0.55 * radius); + context.lineTo(0.5 * radius, -0.55 * radius); + context.lineTo(radius, -0.15 * radius); + context.lineTo(0, radius); + context.lineTo(-radius, -0.15 * radius); + context.closePath(); + context.fillStyle = particle.color; + context.fill(); + + // The girdle across the widest part, and the facets running down from the top + context.beginPath(); + context.moveTo(-radius, -0.15 * radius); + context.lineTo(radius, -0.15 * radius); + context.moveTo(-0.5 * radius, -0.55 * radius); + context.lineTo(0, radius); + context.lineTo(0.5 * radius, -0.55 * radius); + context.strokeStyle = "rgb(255 255 255 / 0.55)"; + context.lineWidth = Math.max(1, 0.025 * area.em); + context.stroke(); + }, + }, + + // The lit part of the moon in its phases from a thin crescent up to half + crescents: { + colors: ["#e8b33c", "#cd8f7a", "#495875"], + size: [0.16, 0.26], + tilt: 0.5, + spin: 0.6, + density: 0.7, + draw: (context, particle, radius) => { + // How much of the face is lit, picked per particle from its seed + const fullness = 0.08 + 0.42 * (Math.abs(Math.sin(particle.seed * 12.9898) * 43758.5453) % 1); + + // Down the lit half of the rim, then back up the line between light and dark, which bows into the lit side less the fuller it is + context.beginPath(); + context.arc(0, 0, radius, -Math.PI / 2, Math.PI / 2); + context.ellipse(0, 0, (1 - 2 * fullness) * radius, radius, 0, Math.PI / 2, -Math.PI / 2, true); + context.closePath(); + context.fillStyle = particle.color; + context.fill(); + }, + }, + + // Eighth notes, some alone and some beamed in pairs + notes: { + colors: ["#16323f", "#5b7bd5", "#803847"], + size: [0.22, 0.32], + tilt: 0.3, + spin: 0, + density: 0.6, + draw: (context, particle, radius) => { + const head = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ scale) => { + context.beginPath(); + context.ellipse(x * radius, y * radius, 0.32 * scale * radius, 0.24 * scale * radius, -0.35, 0, Math.PI * 2); + context.fill(); + }; + context.fillStyle = particle.color; + context.strokeStyle = particle.color; + context.lineWidth = radius * 0.12; + + // Two smaller heads, each with a stem up to the beam slanting across their tops + if (Math.floor(particle.seed) % 2 === 1) { + head(-0.5, 0.6, 0.8); + head(0.45, 0.45, 0.8); + + context.beginPath(); + context.moveTo(-radius * 0.26, radius * 0.55); + context.lineTo(-radius * 0.26, -radius * 0.8); + context.moveTo(radius * 0.69, radius * 0.4); + context.lineTo(radius * 0.69, -radius * 0.95); + context.stroke(); + + context.lineWidth = radius * 0.2; + context.beginPath(); + context.moveTo(-radius * 0.32, -radius * 0.72); + context.lineTo(radius * 0.75, -radius * 0.87); + context.stroke(); + return; + } + + head(-0.25, 0.55, 1); + + // The stem rising from the head, with its flag curling down from the top + context.lineCap = "round"; + context.beginPath(); + context.moveTo(radius * 0.05, radius * 0.5); + context.lineTo(radius * 0.05, -radius * 0.85); + context.bezierCurveTo(radius * 0.45, -radius * 0.6, radius * 0.55, -radius * 0.3, radius * 0.3, -radius * 0.05); + context.stroke(); + }, + }, + + // Leaves, turning over as they go + leaves: { + colors: ["#c2352b", "#e8803d", "#e8b33c"], + size: [0.26, 0.38], + tilt: 0.6, + spin: 0.8, + density: 0.6, + draw: (context, particle, radius) => { + turnOver(context, particle); + + // The outline is about 300 units across, centered 85 units below its origin + context.scale(radius / 150, radius / 150); + context.translate(0, 85); + context.fillStyle = particle.color; + context.fill(MAPLE_LEAF); + }, + }, + + // Loose cherry blossom petals and the odd fresh leaf, turning over around their length as they tumble + petals: { + colors: ["#f2849e", "#f5a3bf", "#f9c0d3", "#ee93ad"], + size: [0.3, 0.45], + tilt: Math.PI, + spin: 1, + density: 1, + draw: (context, particle, radius) => { + context.scale(radius, radius); + turnOver(context, particle); + + // Three in five are petals, centered on their middle rather than where they met the flower, and the rest are leaves + if (Math.floor(particle.seed * 13) % 5 < 3) { + context.translate(0, 0.53); + context.fillStyle = particle.color; + context.fill(BLOSSOM_PETAL); + return; + } + + context.fillStyle = BLOSSOM_LEAF_COLORS[Math.floor(particle.seed) % BLOSSOM_LEAF_COLORS.length] || particle.color; + context.fill(BLOSSOM_LEAF); + }, + }, + + // Crisp squares, kept upright like the pixels of an image + pixels: { + colors: ["#5b7bd5", "#4fa58f", "#e8a33d", "#d2697c"], + size: [0.08, 0.14], + tilt: 0, + spin: 0, + density: 1.4, + draw: (context, particle, radius) => { + context.fillStyle = particle.color; + context.fillRect(-radius, -radius, radius * 2, radius * 2); + }, + }, + + // Six arms, each with a pair of short branches partway along it + snowflakes: { + colors: ["#6fb3c9", "#4f8fa8", "#8fb3e0"], + size: [0.18, 0.3], + tilt: Math.PI / 6, + spin: 0.8, + density: 0.7, + draw: (context, particle, radius, area) => { + turnOver(context, particle); + + context.beginPath(); + for (let i = 0; i < 6; i++) { + context.moveTo(0, 0); + context.lineTo(radius, 0); + context.moveTo(radius * 0.55, 0); + context.lineTo(radius * 0.8, -radius * 0.22); + context.moveTo(radius * 0.55, 0); + context.lineTo(radius * 0.8, radius * 0.22); + context.rotate(Math.PI / 3); + } + context.strokeStyle = particle.color; + context.lineWidth = Math.max(1, 0.035 * area.em); + context.lineCap = "round"; + context.stroke(); + }, + }, +}; + +// How many particles the motions with a steady count keep alive, unless more shapes are chosen +const PARTICLES_ENCIRCLING = 10; +const PARTICLES_LEVITATING = 7; +const PARTICLES_ORBITING = 6; +const ORBIT_PLANES = 3; +const PARTICLES_PER_BURST = 8; + +/** @type {Record} */ +const PARTICLE_MOTIONS = { + // Appearing in place around the name, swelling and shrinking away + blink: { + rate: 9, + spawn: (area) => ({ + x: area.left + random(-0.4, 0.4) * area.em + Math.random() * area.width, + y: area.top + random(-0.45, 0.45) * area.em + Math.random() * area.height, + life: random(0.7, 1.3), + front: Math.random() < 0.4, + }), + envelope: (particle) => [Math.sin(Math.PI * lifeFraction(particle)), 1], + }, + + // Dropping from above and bouncing on the bottom of the name, lower each time + bounce: { + rate: 6, + spawn: (area) => ({ + x: area.left + Math.random() * area.width, + y: area.top - random(0.3, 0.8) * area.em, + vx: random(-0.35, 0.35) * area.em, + life: random(1.8, 2.6), + front: Math.random() < 0.5, + }), + update: (particle, seconds, area) => { + particle.vy += 7 * area.em * seconds; + + const floor = area.top + area.height; + if (particle.y > floor && particle.vy > 0) { + particle.y = floor; + particle.vy *= -0.55; + } + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1, Math.min(1, progress * 8, (1 - progress) * 4)]; + }, + }, + + // Evenly spaced around the outside of the name, running along its edges and rounding its corners like marquee lights + encircle: { + count: PARTICLES_ENCIRCLING, + spawn: (_area, index, _origin, count) => ({ life: Infinity, phase: index / count }), + update: (particle, seconds, area) => { + const path = encirclingPath(0.35 * area.em, 0.6 * area.em, area); + + // Each one's pace swells and slackens on its own rhythm, so neighbors bunch up and spread apart without overtaking + const pace = 1 + 0.5 * Math.sin(particle.age * (0.5 + (particle.seed % 1) * 0.5) + particle.seed); + particle.phase += ((1.2 * area.em) / path.length) * pace * seconds; + + const position = path.at(particle.phase); + particle.x = position.x; + particle.y = position.y; + }, + envelope: () => [1, 1], + }, + + // Floating slowly up and around, fading in and out + drift: { + rate: 6, + spawn: (area) => ({ + x: area.left + Math.random() * area.width, + y: area.top + random(-0.2, 1.2) * area.height, + vx: random(-0.12, 0.12) * area.em, + vy: -random(0.1, 0.25) * area.em, + life: random(2.2, 3.2), + front: Math.random() < 0.2, + }), + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1, Math.min(1, progress * 5, (1 - progress) * 4)]; + }, + }, + + // Tumbling down across the name from above it + fall: { + rate: 3.5, + spawn: (area) => { + const fallSpeed = random(0.5, 0.9) * area.em; + return { + x: area.left + random(-0.4, 0.4) * area.em + Math.random() * area.width, + y: area.top - random(0.2, 0.7) * area.em, + vx: random(-0.25, 0.25) * area.em, + vy: fallSpeed, + life: (area.height + 1.4 * area.em) / fallSpeed, + front: Math.random() < 0.5, + }; + }, + update: (particle, seconds, area) => { + particle.x += Math.sin(particle.age * 2.5 + particle.seed) * 0.3 * area.em * seconds; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1, Math.min(1, progress * 8, (1 - progress) * 5)]; + }, + }, + + // Coming in from all around the name and shrinking away as they reach it + gather: { + rate: 9, + spawn: (area) => { + const angle = random(0, Math.PI * 2); + const centerX = area.left + area.width / 2; + const centerY = area.top + area.height / 2; + const startX = centerX + Math.cos(angle) * (area.width / 2 + 0.85 * area.em); + const startY = centerY + Math.sin(angle) * (area.height / 2 + 0.85 * area.em); + const endX = centerX + (Math.cos(angle) * area.width) / 4; + const endY = centerY + (Math.sin(angle) * area.height) / 4; + const life = random(1.1, 1.6); + return { x: startX, y: startY, vx: (endX - startX) / life, vy: (endY - startY) / life, life, front: Math.random() < 0.4 }; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1 - 0.6 * progress ** 3, Math.min(1, progress * 4, (1 - progress) * 5)]; + }, + }, + + // A row floating above the name, bobbing one after another like a wave + levitate: { + count: PARTICLES_LEVITATING, + spawn: (_area, index, _origin, count) => ({ life: Infinity, slot: (index + 0.5) / count, phase: index * 0.9 }), + update: (particle, _seconds, area) => { + const bob = Math.sin(particle.phase + particle.age * 2.6); + particle.x = area.left + particle.slot * area.width; + particle.y = area.top - 0.3 * area.em + bob * 0.14 * area.em; + }, + envelope: (particle) => [1 + 0.1 * Math.sin(particle.phase + particle.age * 2.6), 1], + }, + + // Circling the name on tilted orbits, passing in front of it and behind, each trailing where it just was + orbit: { + count: PARTICLES_ORBITING, + // Taking the orbits in turn spaces out the particles that share one, which all keep its pace + spawn: (_area, index, _origin, count) => ({ + life: Infinity, + phase: (index * Math.PI * 2) / count, + phaseSpeed: 1.1 + (index % ORBIT_PLANES) * 0.175, + slot: index % ORBIT_PLANES, + }), + update: (particle, seconds, area) => { + particle.phase += particle.phaseSpeed * seconds; + const position = orbitPosition(particle.phase, particle.slot, area); + particle.x = position.x; + particle.y = position.y; + particle.front = Math.sin(particle.phase) > 0; + }, + // Nearer is bigger, which sells the depth of the orbit + envelope: (particle) => [1 + 0.25 * Math.sin(particle.phase), 1], + trail: (particle, area) => Array.from({ length: 6 }, (_, i) => orbitPosition(particle.phase - (i + 1) * 0.11, particle.slot, area)), + }, + + // Swaying upward from the name and fading out + rise: { + rate: 7.5, + spawn: (area) => ({ + x: area.left + Math.random() * area.width, + y: area.top + random(0.5, 1.1) * area.height, + vx: random(-0.15, 0.15) * area.em, + vy: -random(0.5, 0.9) * area.em, + life: random(1, 1.8), + front: Math.random() < 0.3, + }), + update: (particle, seconds, area) => { + particle.x += Math.sin(particle.age * 3 + particle.seed) * 0.3 * area.em * seconds; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1 - (1 - Math.min(1, progress / 0.15)) ** 2, Math.min(1, (1 - progress) / 0.4)]; + }, + }, + + // Bursting outward from points on the name, slowing to a stop as they fade + burst: { + rate: 14, + group: PARTICLES_PER_BURST, + spawn: (area, index, origin) => { + const angle = (index / PARTICLES_PER_BURST) * Math.PI * 2 + random(-0.3, 0.3); + const speed = random(1.1, 1.7) * area.em; + return { + x: area.left + origin.x * area.width, + y: area.top + origin.y * area.height, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed, + life: random(0.9, 1.3), + front: Math.random() < 0.4, + }; + }, + update: (particle, seconds, area) => { + const drag = Math.exp(-2.6 * seconds); + particle.vx *= drag; + particle.vy = particle.vy * drag + 0.8 * area.em * seconds; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [Math.min(1, progress * 10), 1 - progress ** 2]; + }, + }, + + // Climbing from below the name to above it while wrapping around it, passing in front and behind + ascent: { + rate: 7, + spawn: (area) => ({ + life: random(1.8, 2.4), + phase: random(0, Math.PI * 2), + // Turns at a pace that keeps the same speed across any width of name + phaseSpeed: ((2 * area.em) / (area.width / 2 + 0.4 * area.em)) * random(0.8, 1.2), + }), + update: (particle, seconds, area) => { + particle.phase += particle.phaseSpeed * seconds; + particle.x = area.left + area.width / 2 + Math.cos(particle.phase) * (area.width / 2 + 0.4 * area.em); + particle.y = area.top + area.height + 0.4 * area.em - lifeFraction(particle) * (area.height + area.em); + particle.front = Math.sin(particle.phase) > 0; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1 + 0.2 * Math.sin(particle.phase), Math.min(1, progress * 5, (1 - progress) * 5)]; + }, + }, + + // Flowing along the name from start to end, weaving above and below its middle + stream: { + rate: 4, + spawn: (area) => { + const speed = random(1.4, 2) * area.em; + return { + x: area.left - 0.6 * area.em, + vx: speed, + life: (area.width + 1.2 * area.em) / speed, + front: Math.random() < 0.5, + }; + }, + update: (particle, _seconds, area) => { + const along = (particle.x - area.left) / area.em; + particle.y = area.top + area.height / 2 + Math.sin(along * 1.6 + particle.seed) * (area.height / 2 + 0.2 * area.em) * 0.9; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [1, Math.min(1, progress * 6, (1 - progress) * 6)]; + }, + }, + + // Whirling up from a tight point below the name into a funnel that widens above it, fading out at the top + tornado: { + rate: 10, + spawn: () => ({ + life: random(1.6, 2.2), + phase: random(0, Math.PI * 2), + front: false, + }), + update: (particle, seconds, area) => { + const progress = lifeFraction(particle); + const narrowest = 0.15 * area.em; + const radius = narrowest + (area.width / 2 + 0.6 * area.em - narrowest) * progress ** 1.5; + + // Spins fastest where the funnel is narrow, like a real tornado + particle.phase += ((4 * area.em) / (radius + 0.5 * area.em)) * seconds; + + const depth = Math.sin(particle.phase); + particle.x = area.left + area.width / 2 + Math.cos(particle.phase) * radius; + particle.y = area.top + area.height + 0.5 * area.em - progress * (area.height + 1.3 * area.em) + depth * radius * 0.15; + particle.front = depth > 0; + }, + envelope: (particle) => { + const progress = lifeFraction(particle); + return [(0.5 + 0.5 * progress) * (1 + 0.2 * Math.sin(particle.phase)), Math.min(1, progress * 6, (1 - progress) * 3)]; + }, + }, +}; + +// Every name marked with particles gets canvases behind and in front of it, animated only while on screen +window.addEventListener("DOMContentLoaded", () => { + const hosts = Array.from(document.querySelectorAll("[data-name-particle-shapes]")).filter((host) => host instanceof HTMLElement); + if (hosts.length === 0) return; + + const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); + const scenes = hosts.map(createParticleScene); + + let frameRequest = 0; + let previousTime = 0; + const animate = (/** @type {number} */ time) => { + const seconds = Math.min((time - previousTime) / 1000, PARTICLES_LONGEST_STEP_SECONDS); + previousTime = time; + + const active = scenes.filter((scene) => scene.active()); + active.forEach((scene) => { + scene.step(seconds); + scene.draw(); + }); + frameRequest = active.length > 0 ? window.requestAnimationFrame(animate) : 0; + }; + + // Reduced motion draws each scene once, and otherwise the animation runs while any scene is on screen + const refresh = () => { + if (reducedMotion.matches) { + window.cancelAnimationFrame(frameRequest); + frameRequest = 0; + scenes.forEach((scene) => scene.still()); + return; + } + + if (frameRequest || !scenes.some((scene) => scene.active())) return; + previousTime = performance.now(); + frameRequest = window.requestAnimationFrame(animate); + }; + scenes.forEach((scene) => scene.onChange(refresh)); + reducedMotion.addEventListener("change", refresh); +}); + +/** @param {HTMLElement} host */ +function createParticleScene(host) { + const [back, front] = ["back", "front"].map((layer) => { + const canvas = document.createElement("canvas"); + canvas.className = `credits-particles ${layer}`; + canvas.setAttribute("aria-hidden", "true"); + return canvas; + }); + const backContext = back.getContext("2d"); + const frontContext = front.getContext("2d"); + + /** @type {ParticleShape[]} */ + let shapes = []; + /** @type {ParticleMotion | undefined} */ + let motion; + let choices = ""; + /** @type {Particle[]} */ + let particles = []; + /** @type {string[]} */ + let palette = []; + /** @type {ParticleArea} */ + let area = { left: 0, top: 0, width: 0, height: 0, em: 16 }; + let spawnDebt = 0; + let onScreen = false; + let notify = () => {}; + + const measure = () => { + const ratio = window.devicePixelRatio || 1; + [back, front].forEach((canvas) => { + canvas.width = Math.round(canvas.clientWidth * ratio); + canvas.height = Math.round(canvas.clientHeight * ratio); + canvas.getContext("2d")?.setTransform(ratio, 0, 0, ratio, 0, 0); + }); + + const left = (back.clientWidth - host.clientWidth) / 2; + const top = (back.clientHeight - host.clientHeight) / 2; + area = { left, top, width: host.clientWidth, height: host.clientHeight, em: parseFloat(getComputedStyle(host).fontSize) }; + }; + + // The choices and the member's colors are read from the host, which the membership page's preview changes as the member edits + const configure = () => { + const shapeNames = host.dataset.nameParticleShapes || ""; + const motionName = host.dataset.nameParticleMotion || ""; + if (`${shapeNames} ${motionName}` !== choices) { + choices = `${shapeNames} ${motionName}`; + shapes = shapeNames.split(",").flatMap((name) => PARTICLE_SHAPES[name] || []); + motion = shapes.length > 0 ? PARTICLE_MOTIONS[motionName] : undefined; + particles = []; + spawnDebt = 0; + if (motion) host.append(back, front); + else [back, front].forEach((canvas) => canvas.remove()); + } + if (!motion) return; + + const chosenPalette = getComputedStyle(host) + .getPropertyValue("--particle-colors") + .split(",") + .map((color) => color.trim()) + .filter(Boolean); + if (chosenPalette.join() !== palette.join()) { + palette = chosenPalette; + particles.forEach((particle, i) => { + particle.color = colorFor(particle.shape, i); + }); + } + + measure(); + }; + + // The member's particle colors, or else the shape's own + const colorFor = (/** @type {ParticleShape} */ shape, /** @type {number} */ index) => { + const colors = palette.length > 0 ? palette : shape.colors; + return colors[index % colors.length] || ""; + }; + + // A steady count takes the shapes and colors in turn, so each one shows, while the rest are picked at random + const spawn = (/** @type {ParticleMotion} */ chosenMotion, /** @type {number} */ index, origin = { x: 0.5, y: 0.5 }, count = 0) => { + const turn = (/** @type {number} */ length) => (chosenMotion.count ? index % length : Math.floor(Math.random() * length)); + const shape = shapes[turn(shapes.length)] || PARTICLE_SHAPES.orbs; + const colors = palette.length > 0 ? palette : shape.colors; + return particle(shape, { + size: random(...shape.size) * area.em, + angle: random(-shape.tilt, shape.tilt), + spin: random(-shape.spin, shape.spin), + color: colors[turn(colors.length)] || "", + ...chosenMotion.spawn(area, index, origin, count), + }); + }; + + const step = (/** @type {number} */ seconds) => { + if (!motion) return; + + if (motion.count) { + const count = Math.max(motion.count, shapes.length); + while (particles.length < count) particles.push(spawn(motion, particles.length, undefined, count)); + } else { + const group = motion.group || 1; + const density = shapes.reduce((sum, shape) => sum + shape.density, 0) / shapes.length; + spawnDebt += (motion.rate || 0) * density * Math.max(0.6, area.width / (8 * area.em)) * seconds; + for (; spawnDebt >= group; spawnDebt -= group) { + const origin = { x: Math.random(), y: Math.random() }; + for (let i = 0; i < group && particles.length < PARTICLES_LIMIT; i++) particles.push(spawn(motion, i, origin)); + } + } + + particles.forEach((particle) => { + const startX = particle.x; + particle.age += seconds; + particle.x += particle.vx * seconds; + particle.y += particle.vy * seconds; + particle.angle += particle.spin * seconds; + motion?.update?.(particle, seconds, area); + + // Skips the first step, where a motion that places its particles jumps them from the origin + if (seconds > 0 && particle.age > seconds) particle.driftX += ((particle.x - startX) / seconds - particle.driftX) * Math.min(1, seconds * 6); + }); + particles = particles.filter((particle) => particle.age < particle.life); + }; + + const draw = () => { + if (!motion || !backContext || !frontContext) return; + + backContext.clearRect(0, 0, back.clientWidth, back.clientHeight); + frontContext.clearRect(0, 0, front.clientWidth, front.clientHeight); + particles.forEach((particle) => { + const context = particle.front ? frontContext : backContext; + const [scale, opacity] = motion?.envelope(particle) || [1, 1]; + const drawAt = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ fade, /** @type {number} */ shrink) => { + context.save(); + context.translate(x, y); + context.rotate(particle.angle); + context.globalAlpha = opacity * fade; + particle.shape.draw(context, particle, Math.max(0, particle.size * scale * shrink), area); + context.restore(); + }; + + // A trail fades and shrinks behind the particle, oldest first so the newer copies cover it + const trail = motion?.trail?.(particle, area) || []; + trail.toReversed().forEach((position, i) => { + const nearness = (i + 1) / (trail.length + 1); + drawAt(position.x, position.y, nearness * 0.5, 0.6 + nearness * 0.4); + }); + drawAt(particle.x, particle.y, 1, 1); + }); + }; + + const changed = () => { + configure(); + notify(); + }; + new MutationObserver(changed).observe(host, { attributes: true, attributeFilter: ["data-name-particle-shapes", "data-name-particle-motion", "style"] }); + new ResizeObserver(changed).observe(host); + new IntersectionObserver(([entry]) => { + onScreen = entry?.isIntersecting || false; + notify(); + }).observe(host); + configure(); + + return { + step, + draw, + active: () => onScreen && motion !== undefined, + // A moment from partway through, drawn once + still: () => { + particles = []; + spawnDebt = 0; + for (let i = 0; i < PARTICLES_STILL_FRAME_SECONDS * 30; i++) step(1 / 30); + draw(); + }, + onChange: (/** @type {() => void} */ callback) => { + notify = callback; + callback(); + }, + }; +} + +/** + * @param {ParticleShape} shape + * @param {Partial} fields + * @returns {Particle} + */ +function particle(shape, fields) { + return { + x: 0, + y: 0, + vx: 0, + vy: 0, + phase: 0, + phaseSpeed: 0, + age: 0, + life: 1, + size: 1, + angle: 0, + spin: 0, + seed: Math.random() * 1000, + slot: 0, + driftX: 0, + color: "", + front: false, + shape, + ...fields, + }; +} + +/** @param {Particle} particle */ +function lifeFraction(particle) { + return particle.age / particle.life; +} + +/** + * @param {number} min + * @param {number} max + */ +function random(min, max) { + return min + Math.random() * (max - min); +} + +/** + * @param {CanvasRenderingContext2D} context + * @param {number} x + * @param {number} y + * @param {number} radius + */ +function circle(context, x, y, radius) { + context.beginPath(); + context.arc(x, y, Math.max(0, radius), 0, Math.PI * 2); + context.fill(); +} + +/** + * @param {number} start + * @param {number} startHandle + * @param {number} endHandle + * @param {number} end + * @param {number} t + */ +function cubicBezier(start, startHandle, endHandle, end, t) { + const remaining = 1 - t; + return remaining ** 3 * start + 3 * remaining ** 2 * t * startHandle + 3 * remaining * t ** 2 * endHandle + t ** 3 * end; +} + +/** + * Squashes the drawing across its upright axis to turn it all the way over, lingering near full width and sweeping quickly through edge-on. + * @param {CanvasRenderingContext2D} context + * @param {Particle} particle + */ +function turnOver(context, particle) { + const turn = Math.cos(particle.age * 2.5 + particle.seed); + context.scale(Math.sign(turn) * Math.abs(turn) ** 0.3, 1); +} + +/** + * A flattened circle tilted by which of the orbit planes it is, then stretched to wrap the name's box. + * @param {number} phase + * @param {number} plane + * @param {ParticleArea} area + */ +function orbitPosition(phase, plane, area) { + const tilt = (plane - 1) * 0.55; + const across = Math.cos(phase); + const depth = Math.sin(phase) * 0.32; + const radiusX = area.width / 2 + 0.45 * area.em; + const radiusY = area.height / 2 + 0.45 * area.em; + + return { + x: area.left + area.width / 2 + (across * Math.cos(tilt) - depth * Math.sin(tilt)) * radiusX, + y: area.top + area.height / 2 + (across * Math.sin(tilt) + depth * Math.cos(tilt)) * radiusY, + }; +} + +/** + * The way clockwise around the name's box, grown by a margin with its corners rounded, from the start of its top edge. + * @param {number} margin + * @param {number} rounding + * @param {ParticleArea} area + */ +function encirclingPath(margin, rounding, area) { + const left = area.left - margin; + const top = area.top - margin; + const right = area.left + area.width + margin; + const bottom = area.top + area.height + margin; + const corner = Math.min(rounding, (right - left) / 2, (bottom - top) / 2); + const across = right - left - corner * 2; + const down = bottom - top - corner * 2; + const turn = (Math.PI / 2) * corner; + + // Each corner turns a quarter of the way around a circle set in from it + const around = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ startAngle) => (/** @type {number} */ distance) => ({ + x: x + Math.cos(startAngle + distance / corner) * corner, + y: y + Math.sin(startAngle + distance / corner) * corner, + }); + + /** @type {[number, (distance: number) => { x: number, y: number }][]} */ + const stretches = [ + [across, (distance) => ({ x: left + corner + distance, y: top })], + [turn, around(right - corner, top + corner, -Math.PI / 2)], + [down, (distance) => ({ x: right, y: top + corner + distance })], + [turn, around(right - corner, bottom - corner, 0)], + [across, (distance) => ({ x: right - corner - distance, y: bottom })], + [turn, around(left + corner, bottom - corner, Math.PI / 2)], + [down, (distance) => ({ x: left, y: bottom - corner - distance })], + [turn, around(left + corner, top + corner, Math.PI)], + ]; + const length = stretches.reduce((sum, [stretch]) => sum + stretch, 0); + + return { + length, + // The point a fraction of the way around + at: (/** @type {number} */ fraction) => { + let distance = (((fraction % 1) + 1) % 1) * length; + for (let i = 0; i < stretches.length - 1; i++) { + const [stretch, point] = stretches[i] || [0, () => ({ x: left, y: top })]; + if (distance <= stretch) return point(distance); + distance -= stretch; + } + const [, last] = stretches[stretches.length - 1] || [0, () => ({ x: left, y: top })]; + return last(distance); + }, + }; +} diff --git a/website/static/js/page/membership.js b/website/static/js/page/membership.js new file mode 100644 index 00000000000..b95387ee91a --- /dev/null +++ b/website/static/js/page/membership.js @@ -0,0 +1,1070 @@ +// Several times the size the credits show it at, so it stays sharp on high-density screens +const AVATAR_SIZE = 256; + +// Matches the Worker's wait before it will email the same address another sign-in link +const SIGN_IN_EMAIL_INTERVAL_MILLISECONDS = 60 * 1000; + +// Matches how long the Worker's sign-in links work, which is as long as the button offers to resend one +const SIGN_IN_LINK_LIFETIME_MILLISECONDS = 15 * 60 * 1000; +const SIGN_IN_EMAIL_STORAGE_KEY = "graphite-membership-sign-in-email"; + +// Encoding the crop waits for this long a pause, rather than running on every step of a drag +const COMMIT_DELAY_MILLISECONDS = 150; + +// Matches the Worker's limit, which is as many as fit in a row of pickers +const COLORS_LIMIT = 9; + +// How far a press on a color travels before it's a drag rather than a click that opens the picker +const COLOR_DRAG_THRESHOLD_PIXELS = 4; + +// Each added color starts as the first of these not already in its row, so it stands apart from the others +const ADDED_COLORS = ["#16323f", "#cd8f7a", "#d2697c", "#4fa58f", "#5b7bd5", "#e8a33d", "#7a5cff", "#803847", "#e5c299"]; + +// A chosen picture is framed in a square the member drags and zooms, and only that square is uploaded +window.addEventListener("DOMContentLoaded", () => { + const fileInput = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-credits-avatar-file]")); + const preview = /** @type {HTMLImageElement | null} */ (document.querySelector("[data-credits-avatar]")); + const removeCheckbox = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-remove-avatar-checkbox]")); + const cropper = /** @type {HTMLElement | null} */ (document.querySelector("[data-avatar-cropper]")); + const frame = /** @type {HTMLElement | null} */ (document.querySelector("[data-crop-frame]")); + const image = /** @type {HTMLImageElement | null} */ (document.querySelector("[data-crop-image]")); + const zoomSlider = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-crop-zoom]")); + const fileStatus = document.querySelector("[data-credits-avatar-file-name]"); + const form = fileInput?.form; + if (!fileInput || !preview || !cropper || !frame || !image || !zoomSlider || !form) return; + + let fileName = ""; + let zoom = 1; + // The center of the cropped square, in the picture's own pixels + let centerX = 0; + let centerY = 0; + let commitTimeout = 0; + /** @type {{ pointerX: number, pointerY: number, centerX: number, centerY: number } | undefined} */ + let dragStart; + + const side = () => Math.min(image.naturalWidth, image.naturalHeight) / zoom; + const pixelsPerImagePixel = () => frame.clientWidth / side(); + + const commit = () => { + window.clearTimeout(commitTimeout); + commitTimeout = 0; + + const cropped = cropToFile(image, centerX - side() / 2, centerY - side() / 2, side(), fileName); + if (!cropped) return; + + const transfer = new DataTransfer(); + transfer.items.add(cropped); + fileInput.files = transfer.files; + + if (preview.src.startsWith("blob:")) URL.revokeObjectURL(preview.src); + preview.src = URL.createObjectURL(cropped); + preview.hidden = false; + }; + + // Keeps the square within the picture, then moves and scales the picture behind the frame to match + const render = () => { + const half = side() / 2; + centerX = Math.min(Math.max(centerX, half), image.naturalWidth - half); + centerY = Math.min(Math.max(centerY, half), image.naturalHeight - half); + + const scale = pixelsPerImagePixel(); + image.style.width = `${image.naturalWidth * scale}px`; + image.style.translate = `${(half - centerX) * scale}px ${(half - centerY) * scale}px`; + + window.clearTimeout(commitTimeout); + commitTimeout = window.setTimeout(commit, COMMIT_DELAY_MILLISECONDS); + }; + + const setZoom = (/** @type {number} */ value) => { + zoom = Math.min(Math.max(value, Number(zoomSlider.min)), Number(zoomSlider.max)); + zoomSlider.value = String(zoom); + render(); + }; + + const storedSource = preview.getAttribute("src"); + const storedHidden = preview.hidden; + + fileInput.addEventListener("change", async () => { + const file = fileInput.files?.[0]; + if (fileStatus) fileStatus.textContent = file?.name || "No file selected"; + + // Clearing the choice, as canceling the file dialog or undoing a previewed picture does, brings back the stored picture or none + if (!file) { + window.clearTimeout(commitTimeout); + commitTimeout = 0; + cropper.hidden = true; + + if (preview.src.startsWith("blob:")) URL.revokeObjectURL(preview.src); + if (storedSource) preview.src = storedSource; + else preview.removeAttribute("src"); + preview.hidden = storedHidden; + return; + } + + // A picture the browser can't decode is sent as it is, for the server to turn down + if (image.src.startsWith("blob:")) URL.revokeObjectURL(image.src); + /** @type {Promise} */ + const loaded = new Promise((resolve) => { + image.onload = () => resolve(true); + image.onerror = () => resolve(false); + }); + image.src = URL.createObjectURL(file); + + // Firefox's decoding answers for the picture already shown, so it waits for the new one to load first + const decoded = + (await loaded) && + (await image.decode().then( + () => true, + () => false, + )); + cropper.hidden = !decoded; + if (!decoded) return; + + fileName = file.name; + centerX = image.naturalWidth / 2; + centerY = image.naturalHeight / 2; + if (removeCheckbox) removeCheckbox.checked = false; + + setZoom(1); + commit(); + }); + + frame.addEventListener("pointerdown", (e) => { + frame.setPointerCapture(e.pointerId); + dragStart = { pointerX: e.clientX, pointerY: e.clientY, centerX, centerY }; + }); + frame.addEventListener("pointermove", (e) => { + if (!dragStart) return; + + // The picture follows the pointer, so the square moves the opposite way across it + centerX = dragStart.centerX - (e.clientX - dragStart.pointerX) / pixelsPerImagePixel(); + centerY = dragStart.centerY - (e.clientY - dragStart.pointerY) / pixelsPerImagePixel(); + render(); + }); + const endDrag = () => { + dragStart = undefined; + }; + frame.addEventListener("pointerup", endDrag); + frame.addEventListener("pointercancel", endDrag); + + // The frame narrows with the page on small screens, which changes how far the picture sits from its edges + new ResizeObserver(() => { + if (!cropper.hidden) render(); + }).observe(frame); + + frame.addEventListener( + "wheel", + (e) => { + e.preventDefault(); + setZoom(zoom * Math.exp(-e.deltaY / 500)); + }, + { passive: false }, + ); + zoomSlider.addEventListener("input", () => setZoom(Number(zoomSlider.value))); + + // Arrow keys move the picture a twentieth of the frame, as dragging would + frame.addEventListener("keydown", (e) => { + /** @type {Record} */ + const directions = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }; + const direction = directions[e.key]; + if (!direction) return; + + e.preventDefault(); + centerX -= (direction[0] * side()) / 20; + centerY -= (direction[1] * side()) / 20; + render(); + }); + + // The form is read after this event, so a crop still waiting to be encoded is finished first + form.addEventListener("submit", () => { + if (commitTimeout) commit(); + }); +}); + +// The preview mirrors the form as it's edited, styled and animated by the same stylesheet and particles script as the credits +window.addEventListener("DOMContentLoaded", () => { + const previewBox = /** @type {HTMLElement | null} */ (document.querySelector("[data-credits-preview]")); + const entry = /** @type {HTMLElement | null} */ (document.querySelector("[data-credits-preview-entry]")); + let previewName = /** @type {HTMLElement | null} */ (document.querySelector("[data-credits-preview-name]")); + const previewAvatar = /** @type {HTMLImageElement | null} */ (document.querySelector("[data-credits-preview-avatar]")); + const nameInput = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-credits-name]")); + const linkInput = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-credits-link]")); + const colorStyle = /** @type {HTMLSelectElement | null} */ (document.querySelector("[data-credits-color-style]")); + const nameColorsRow = /** @type {HTMLElement | null} */ (document.querySelector(`[data-color-row="credits_colors"]`)); + const particleColorsRow = /** @type {HTMLElement | null} */ (document.querySelector(`[data-color-row="credits_particle_colors"]`)); + const particleColorsField = /** @type {HTMLElement | null} */ (document.querySelector("[data-particle-colors-field]")); + const swatchTemplate = /** @type {HTMLTemplateElement | null} */ (document.querySelector("[data-swatch-template]")); + const shapeRow = /** @type {HTMLElement | null} */ (document.querySelector("[data-shape-row]")); + const shapeList = /** @type {HTMLElement | null} */ (document.querySelector("[data-shape-list]")); + const shapeTemplate = /** @type {HTMLTemplateElement | null} */ (document.querySelector("[data-shape-template]")); + const addShape = /** @type {HTMLButtonElement | null} */ (document.querySelector("[data-add-shape]")); + const removeShape = /** @type {HTMLButtonElement | null} */ (document.querySelector("[data-remove-shape]")); + const particleMotion = /** @type {HTMLSelectElement | null} */ (document.querySelector("[data-credits-particle-motion]")); + const particleShapesField = /** @type {HTMLElement | null} */ (document.querySelector("[data-particle-shapes-field]")); + const avatar = /** @type {HTMLImageElement | null} */ (document.querySelector("[data-credits-avatar]")); + const avatarFile = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-credits-avatar-file]")); + const removeAvatar = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-remove-avatar-checkbox]")); + const showInSiteCredits = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-show-in-site-credits]")); + const showInVideoCredits = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-show-in-video-credits]")); + const speakInVideoCredits = /** @type {HTMLInputElement | null} */ (document.querySelector("[data-speak-in-video-credits]")); + const tryHigherTiers = /** @type {HTMLButtonElement | null} */ (document.querySelector("[data-try-higher-tiers]")); + const stopPreviewingLink = /** @type {HTMLButtonElement | null} */ (document.querySelector("[data-credits-form] > [data-stop-previewing]")); + + // The billing control the upgrade link presses, preferring a membership's tier change over renewing one that's ending + const upgradeControl = document.querySelector(`[data-change-tier="change"]`) || document.querySelector("[data-change-tier]"); + const creditsLocked = /** @type {HTMLElement | null} */ (document.querySelector("[data-credits-locked]")); + const previewNotice = /** @type {HTMLElement | null} */ (document.querySelector("[data-preview-notice]")); + const previewSentence = /** @type {HTMLTemplateElement | null} */ (document.querySelector("[data-preview-sentence]")); + const previewSentences = document.querySelector("[data-preview-sentences]"); + const previewPronoun = document.querySelector("[data-preview-pronoun]"); + const form = colorStyle?.form; + if (!previewBox || !entry || !previewName || !nameInput || !colorStyle || !nameColorsRow || !swatchTemplate || !form) return; + + // Rewards and the color menu's options are marked with the tier they begin at, ranked by the Worker's list of tiers + const tiers = (form.dataset.tiers || "").split(" ").filter(Boolean); + const rank = (/** @type {string | null | undefined} */ tier) => tiers.findIndex((name) => name.toLowerCase() === tier); + const memberRank = rank(form.dataset.memberTier); + const tierOf = (/** @type {Element | null | undefined} */ element) => rank(element?.closest("[data-reward-tier]")?.getAttribute("data-reward-tier")); + const aboveTier = (/** @type {Element | null | undefined} */ element) => tierOf(element) > memberRank; + const tierPrices = (form.dataset.tierPrices || "").split(" "); + const tierLabel = (/** @type {number} */ tierRank) => `${tiers[tierRank]} Tier`; + + const marked = Array.from(/** @type {NodeListOf} */ (form.querySelectorAll("[data-reward-tier]"))); + const rewards = marked.filter((element) => !(element instanceof HTMLOptionElement)); + const styleNames = new Map(Array.from(colorStyle.options, (option) => [option, option.textContent || ""])); + + // The rewards that are fields, by their own label, which leaves out the credits preview and the save button + const ownLabel = (/** @type {HTMLElement} */ reward) => Array.from(reward.querySelectorAll("[data-reward-label]")).find((candidate) => candidate.closest("[data-reward-tier]") === reward); + const rewardFields = rewards.filter((reward) => ownLabel(reward)); + + // Fields above the member's tier are labeled with the tier they need, which shows once they're tried on + rewardFields.filter(aboveTier).forEach((reward) => { + const badge = document.createElement("span"); + badge.className = "tier-badge"; + badge.textContent = tierLabel(tierOf(reward)); + ownLabel(reward)?.append(badge); + }); + + const optedIn = () => Boolean(showInSiteCredits?.checked || showInVideoCredits?.checked); + + // Each choice that puts something in the credits, with its name in the preview line and how to undo it + const choices = () => [ + { + element: showInSiteCredits, + used: optedIn(), + name: "your name", + undo: () => { + if (showInSiteCredits) showInSiteCredits.checked = false; + if (showInVideoCredits) showInVideoCredits.checked = false; + }, + }, + { + element: colorStyle.selectedOptions[0], + used: Boolean(colorStyle.value), + // Menu choices are quoted as the menu names them, so they don't read as part of the sentence + name: `your "${styleNames.get(colorStyle.selectedOptions[0])}" name color`, + // The best style the member's tier includes takes its place, or none + undo: () => { + colorStyle.value = + Array.from(colorStyle.options) + .filter((option) => !aboveTier(option)) + .at(-1)?.value || ""; + }, + }, + { + element: avatar, + used: Boolean(avatar && !avatar.hidden && !removeAvatar?.checked), + name: "your avatar picture", + // A newly chosen picture is dropped, and a stored one is marked for removal + undo: () => { + if (avatarFile?.files?.length) { + avatarFile.value = ""; + avatarFile.dispatchEvent(new Event("change")); + } + if (removeAvatar && avatar && !avatar.hidden) removeAvatar.checked = true; + }, + }, + { + element: linkInput, + used: Boolean(linkInput?.value.trim()), + name: "the link on your name", + undo: () => { + if (linkInput) linkInput.value = ""; + }, + }, + { + element: particleMotion, + used: Boolean(particleMotion?.value), + name: `your "${particleMotion?.selectedOptions[0]?.textContent}" particles`, + plural: true, + undo: () => { + if (particleMotion) particleMotion.value = ""; + }, + }, + { + element: speakInVideoCredits, + used: Boolean(speakInVideoCredits?.checked), + name: "your spoken name", + undo: () => { + if (speakInVideoCredits) speakInVideoCredits.checked = false; + }, + }, + ]; + const previewedChoices = () => choices().filter((choice) => choice.used && aboveTier(choice.element)); + const singular = (/** @type {{ plural?: boolean }[]} */ listed) => listed.length === 1 && !listed[0].plural; + + // While tried on, higher rewards are in view, and color styles above their field's tier name their own + let previewing = false; + const previewHigherTiers = () => { + previewing = true; + if (creditsLocked) creditsLocked.hidden = true; + + const badgedRank = Math.max(memberRank, tierOf(colorStyle)); + Array.from(colorStyle.options) + .filter((option) => tierOf(option) > badgedRank) + .forEach((option) => { + option.textContent = `${styleNames.get(option)} (${tierLabel(tierOf(option))})`; + }); + }; + + // Stopping puts the form back to what the member's tier includes, undoing each choice above it + const stopPreviewingHigherTiers = () => { + previewedChoices().forEach((choice) => choice.undo()); + previewing = false; + if (creditsLocked) creditsLocked.hidden = false; + + Array.from(colorStyle.options).forEach((option) => { + option.textContent = styleNames.get(option) || ""; + }); + }; + + // Saved choices above the member's tier, like those kept from a higher tier they've left, open the page already trying them on + if (previewedChoices().length > 0) previewHigherTiers(); + + const showTiers = () => { + if (tiers.length === 0) return; + + rewards.forEach((reward) => reward.classList.toggle("locked-reward", !previewing && aboveTier(reward))); + Array.from(colorStyle.options).forEach((option) => { + option.hidden = !previewing && aboveTier(option); + option.disabled = option.hidden; + }); + + // While tried on, the fields and color styles that are only a preview are set in italics + rewardFields.forEach((reward) => reward.classList.toggle("previewed-reward", previewing && aboveTier(reward))); + Array.from(colorStyle.options).forEach((option) => option.classList.toggle("previewed-reward", previewing && aboveTier(option))); + colorStyle.classList.toggle("previewed-reward", previewing && aboveTier(colorStyle.selectedOptions[0])); + if (tryHigherTiers) tryHigherTiers.hidden = previewing || !rewards.some(aboveTier); + + const previewed = previewedChoices().sort((a, b) => tierOf(a.element) - tierOf(b.element)); + const neededRank = Math.max(memberRank, ...previewed.map((choice) => tierOf(choice.element))); + if (previewNotice) previewNotice.hidden = previewed.length === 0; + if (stopPreviewingLink) stopPreviewingLink.hidden = !previewing || previewed.length > 0; + + // Each tier the choices need gets its own sentence, cheapest first, so a costly choice doesn't make the smaller steps look out of reach + const sentences = [...new Set(previewed.map((choice) => tierOf(choice.element)))].flatMap((tierRank) => { + const sentence = previewSentence?.content.firstElementChild?.cloneNode(true); + if (!(sentence instanceof HTMLElement)) return []; + + // Without a billing control to press, the upgrade is named in plain text + const upgradeLink = sentence.querySelector("[data-upgrade-button]"); + if (!upgradeControl) upgradeLink?.replaceWith(...upgradeLink.childNodes); + + const inTier = previewed.filter((choice) => tierOf(choice.element) === tierRank); + const listed = new Intl.ListFormat("en", { type: "conjunction" }).format(inTier.map((choice) => choice.name)); + const fill = (/** @type {string} */ selector, /** @type {string} */ text) => { + const part = sentence.querySelector(selector); + if (part) part.textContent = text; + }; + fill("[data-preview-choices]", listed.charAt(0).toUpperCase() + listed.slice(1)); + fill("[data-preview-verb]", singular(inTier) ? "is" : "are"); + fill("[data-needed-tier]", tiers[tierRank]); + fill("[data-needed-tier-price]", tierPrices[tierRank]); + return [sentence, " "]; + }); + previewSentences?.replaceChildren(...sentences); + if (previewPronoun) previewPronoun.textContent = singular(previewed) ? "it" : "them"; + + // Names are sized by tier in the credits, so the preview takes the size of the tier that would show it, starting from the first with credits + const shownTier = tiers[Math.max(neededRank, Math.min(...rewards.map(tierOf)))]; + previewBox.classList.remove(...tiers.map((tier) => tier.toLowerCase())); + if (shownTier) previewBox.classList.add(shownTier.toLowerCase()); + }; + + const shapeSelects = () => Array.from(/** @type {NodeListOf} */ (shapeList?.querySelectorAll("[data-particle-shape]") || [])); + const shapeTemplateMenu = shapeTemplate?.content.querySelector("[data-particle-shape]"); + const shapeCount = shapeTemplateMenu instanceof HTMLSelectElement ? shapeTemplateMenu.options.length : 0; + + const shapeRemoval = removalMode(shapeRow, removeShape); + const colorPopoverElement = /** @type {HTMLElement | null} */ (document.querySelector("[data-color-popover]")); + const picker = colorPopoverElement ? colorPopover(colorPopoverElement) : undefined; + + // The name and the particles each keep their own colors, sharing the one picker + const nameColors = colorRow(nameColorsRow, swatchTemplate, picker, () => update()); + const particleColors = particleColorsRow ? colorRow(particleColorsRow, swatchTemplate, picker, () => update()) : undefined; + + // Each new shape copies its template, starting as the first one not already chosen + const appendShape = () => { + const choice = shapeTemplate?.content.firstElementChild?.cloneNode(true); + const select = choice instanceof HTMLElement ? choice.querySelector("[data-particle-shape]") : undefined; + if (!(choice instanceof HTMLElement) || !(select instanceof HTMLSelectElement) || !shapeList) return; + + const used = shapeSelects().map((other) => other.value); + select.value = Array.from(select.options, (option) => option.value).find((shape) => !used.includes(shape)) || select.value; + shapeList.append(choice); + }; + + const setProperty = (/** @type {string} */ property, /** @type {string | undefined} */ value) => { + if (value) entry.style.setProperty(property, value); + else entry.style.removeProperty(property); + }; + + const update = () => { + if (!previewName) return; + showTiers(); + + // Choosing a motion starts the particles with a shape, while None hides them but keeps the shapes for later + const motion = particleMotion?.value || ""; + const particlesOn = motion !== ""; + if (particlesOn && shapeSelects().length === 0) appendShape(); + const shapes = shapeSelects().map((select) => select.value); + + const style = colorStyle.value; + const fading = style !== "" && style !== "solid"; + + // A fade needs two colors and shows all of them with the buttons for more, while a solid name shows just its first, beside the menu + const fewest = fading ? 2 : style ? 1 : 0; + while (nameColors.inputs().length < fewest) nameColors.append(); + const inputs = nameColors.inputs(); + inputs.forEach((input, index) => { + if (input.parentElement) input.parentElement.hidden = !fading && index >= fewest; + input.setAttribute("aria-label", `Color ${index + 1}`); + }); + nameColorsRow.hidden = fewest === 0; + nameColorsRow.parentElement?.classList.toggle("color-beside-menu", style === "solid"); + nameColors.showButtons(fading, fewest); + + // The particles take any number of colors, or none to leave each shape its own + const particleInputs = particleColors?.inputs() || []; + particleInputs.forEach((input, index) => input.setAttribute("aria-label", `Particle color ${index + 1}`)); + particleColors?.showButtons(true, 0); + if (particleColorsField) particleColorsField.hidden = !particlesOn; + + // The picker closes along with the color it was editing, whether that was removed or hidden + const editing = picker?.editing(); + if (editing && (!editing.isConnected || !editing.offsetParent)) picker?.close(); + + // The name takes its first color, or fades through them all + const colors = inputs.filter((input) => !input.parentElement?.hidden).map((input) => input.value); + setProperty("--name-color", style ? colors[0] : undefined); + setProperty("--name-fade-colors", fading ? colors.slice(1).join(", ") : undefined); + setProperty("--name-color-count", fading ? String(colors.length) : undefined); + setProperty("--name-color-bands", fading ? colorBands(colors) : undefined); + setProperty("--particle-colors", particlesOn ? particleInputs.map((input) => input.value).join(", ") : undefined); + entry.className = fading ? `name-fade ${style}` : ""; + + // The last shape can't be removed, since None is what turns the particles off + if (addShape) addShape.hidden = shapes.length >= shapeCount; + if (removeShape) removeShape.hidden = shapes.length <= 1; + if (shapes.length <= 1) shapeRemoval.set(false); + if (particleShapesField) particleShapesField.hidden = !particlesOn; + entry.dataset.nameParticleShapes = particlesOn ? shapes.join(",") : ""; + entry.dataset.nameParticleMotion = motion; + + // A linked name is a link in the credits, which underlines it + const linked = Boolean(linkInput?.value.trim()); + if (linked !== (previewName.tagName === "A")) { + const replacement = document.createElement(linked ? "a" : "span"); + replacement.className = "credits-name"; + replacement.toggleAttribute("data-credits-preview-name", true); + previewName.replaceWith(replacement); + previewName = replacement; + } + previewName.textContent = nameInput.value.trim() || "Your name"; + + if (previewAvatar && avatar) { + previewAvatar.src = avatar.src; + previewAvatar.hidden = avatar.hidden || Boolean(removeAvatar?.checked); + } + }; + + form.addEventListener("input", update); + + // Someone who mistakes the previewed name for the field is taken to the field + entry.addEventListener("click", (e) => { + if (!(e.target instanceof Element) || !e.target.closest("[data-credits-preview-name]")) return; + + nameInput.focus(); + nameInput.select(); + }); + + // Focus moves to the link that takes the step back, since the one pressed disappears + tryHigherTiers?.addEventListener("click", () => { + previewHigherTiers(); + update(); + stopPreviewingLink?.focus(); + }); + form.querySelectorAll("[data-stop-previewing]").forEach((button) => + button.addEventListener("click", (e) => { + e.preventDefault(); + stopPreviewingHigherTiers(); + update(); + tryHigherTiers?.focus(); + }), + ); + + // Upgrade links press the billing control, or follow their own address to the tiers when there's none + form.addEventListener("click", (e) => { + if (!(e.target instanceof Element) || !e.target.closest("[data-upgrade-button]") || !(upgradeControl instanceof HTMLElement)) return; + + e.preventDefault(); + upgradeControl.click(); + }); + + addShape?.addEventListener("click", () => { + shapeRemoval.set(false); + appendShape(); + update(); + }); + + // While removing, pressing a shape's menu takes it out instead of opening it + shapeList?.addEventListener("mousedown", (e) => { + if (!shapeRemoval.on() || !(e.target instanceof HTMLSelectElement)) return; + + e.preventDefault(); + e.target.parentElement?.remove(); + update(); + }); + shapeList?.addEventListener("keydown", (e) => { + if (!shapeRemoval.on() || !(e.target instanceof HTMLSelectElement) || !["Enter", " "].includes(e.key)) return; + + e.preventDefault(); + e.target.parentElement?.remove(); + update(); + }); + + // The picture's thumbnail changes when a crop is encoded, which no form event announces + if (avatar) new MutationObserver(update).observe(avatar, { attributes: true, attributeFilter: ["src", "hidden"] }); + + update(); + previewBox.hidden = false; +}); + +// The form for a new email address opens beneath the account it changes +window.addEventListener("DOMContentLoaded", () => { + const toggle = document.querySelector("[data-change-email-toggle]"); + const form = document.querySelector("[data-change-email]"); + if (!(toggle instanceof HTMLButtonElement) || !(form instanceof HTMLFormElement)) return; + + toggle.addEventListener("click", () => { + form.hidden = !form.hidden; + toggle.setAttribute("aria-expanded", String(!form.hidden)); + const input = form.querySelector("[data-new-email-address]"); + if (!form.hidden && input instanceof HTMLInputElement) input.focus(); + }); +}); + +// After a sign-in link is requested, the button counts down until the Worker would send that address another, timed in this browser so it says nothing about who's a member +window.addEventListener("DOMContentLoaded", () => { + const form = document.querySelector("[data-email-sign-in]"); + const input = form?.querySelector("[data-sign-in-address]"); + const button = form?.querySelector("[data-sign-in-button]"); + if (!(form instanceof HTMLFormElement) || !(input instanceof HTMLInputElement) || !(button instanceof HTMLButtonElement)) return; + + const label = button.textContent; + const normalized = () => input.value.trim().toLowerCase(); + form.addEventListener("submit", () => storeSignInEmail({ address: normalized() })); + + // The countdown starts once the Worker has replied with its confirmation, which comes after it timed the request + const requested = readSignInEmail(); + const confirmation = document.querySelector(`[data-notice="sign-in-link-sent"]`); + const confirmed = confirmation instanceof HTMLElement && !confirmation.hidden; + if (requested && confirmed && requested.sentAt === undefined) { + requested.sentAt = Date.now(); + storeSignInEmail(requested); + } + if (!requested || requested.sentAt === undefined) return; + + const { address, sentAt } = requested; + const resendableAt = sentAt + SIGN_IN_EMAIL_INTERVAL_MILLISECONDS; + const expiresAt = sentAt + SIGN_IN_LINK_LIFETIME_MILLISECONDS; + if (Date.now() >= expiresAt) { + forgetSignInEmail(); + return; + } + if (confirmed || Date.now() < resendableAt) input.value = address; + + // Another address can be sent to right away, since the wait is for each address + const update = () => { + const resending = normalized() === address && Date.now() < expiresAt; + const seconds = resending ? Math.ceil((resendableAt - Date.now()) / 1000) : 0; + + button.disabled = seconds > 0; + button.classList.toggle("arrow", seconds <= 0); + if (seconds > 0) button.textContent = `Resend in ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + else button.textContent = resending ? "Resend sign-in link" : label; + }; + + input.addEventListener("input", update); + update(); + + // Once the earlier link expires, even with the page left open, the button asks for a new one as if for the first time + setTimeout(() => { + forgetSignInEmail(); + update(); + }, expiresAt - Date.now()); + + if (Date.now() >= resendableAt) return; + + const timer = setInterval(() => { + update(); + if (Date.now() >= resendableAt) clearInterval(timer); + }, 250); +}); + +// Saving waits for the form to differ from how it loaded, so undoing every change disables it again +window.addEventListener("DOMContentLoaded", () => { + const form = /** @type {HTMLFormElement | null} */ (document.querySelector("[data-credits-form]")); + const saveButton = form?.querySelector("[data-save-changes]"); + if (!form || !(saveButton instanceof HTMLButtonElement)) return; + + // A chosen picture is compared by its details, since each new crop is a new file, while an empty file input reads as nothing + const contents = () => { + const describe = (/** @type {FormDataEntryValue} */ value) => { + if (typeof value === "string") return value; + return value.size > 0 ? `${value.name} ${value.size} ${value.lastModified}` : ""; + }; + return JSON.stringify(Array.from(new FormData(form), ([name, value]) => [name, describe(value)])); + }; + + // Taken after the preview has run, since it can add the colors a stored style needs + const loaded = contents(); + const refresh = () => { + saveButton.disabled = contents() === loaded; + }; + + // Colors and shapes are added, removed, and reordered without form events, and a crop shows itself only through the picture's address + form.addEventListener("input", refresh); + form.addEventListener("change", refresh); + new MutationObserver(refresh).observe(form, { childList: true, subtree: true, attributes: true, attributeFilter: ["src"] }); + + refresh(); +}); + +/** + * A row of colors, each added with its plus button, taken out while its minus button is pressed, dragged into order, and edited in the page's picker. + * @param {HTMLElement} row + * @param {HTMLTemplateElement} template + * @param {ReturnType | undefined} picker + * @param {() => void} changed + */ +function colorRow(row, template, picker, changed) { + const swatches = row.querySelector("[data-color-swatches]") || row; + const addButton = /** @type {HTMLButtonElement | null} */ (row.querySelector("[data-add-color]")); + const removeButton = /** @type {HTMLButtonElement | null} */ (row.querySelector("[data-remove-color]")); + const removal = removalMode(row, removeButton); + + const inputs = () => Array.from(/** @type {NodeListOf} */ (swatches.querySelectorAll("[data-color-picker]"))); + + // Each new color copies the template, named for this row's field and starting as the first color not already in it + const append = () => { + const swatch = template.content.firstElementChild?.cloneNode(true); + const input = swatch instanceof HTMLElement ? swatch.querySelector("[data-color-picker]") : undefined; + if (!(swatch instanceof HTMLElement) || !(input instanceof HTMLInputElement)) return; + + const used = inputs().map((other) => other.value); + input.name = row.dataset.colorRow || input.name; + input.value = ADDED_COLORS.find((color) => !used.includes(color)) || input.value; + swatches.append(swatch); + }; + + // A full row has no plus button, which leaves its place for the last color, and the minus stops at the fewest the row needs + const showButtons = (/** @type {boolean} */ shown, /** @type {number} */ fewest) => { + const count = inputs().length; + if (addButton) addButton.hidden = !shown || count >= COLORS_LIMIT; + if (removeButton) { + removeButton.hidden = !shown; + removeButton.disabled = count <= fewest; + } + if (!shown || count <= fewest) removal.set(false); + }; + + addButton?.addEventListener("click", () => { + removal.set(false); + append(); + changed(); + }); + + // Dragging a color slides it into place among the others, while a press that doesn't move still opens its picker + /** @type {{ swatch: HTMLElement, startX: number, moved: boolean } | undefined} */ + let drag; + let suppressClick = false; + + const dragMove = (/** @type {PointerEvent} */ e) => { + if (!drag || (!drag.moved && Math.abs(e.clientX - drag.startX) < COLOR_DRAG_THRESHOLD_PIXELS)) return; + const dragged = drag.swatch; + const others = Array.from(swatches.children).filter((other) => other !== dragged && other instanceof HTMLElement && !other.hidden); + if (others.length === 0) return; + + if (!drag.moved) picker?.close(); + drag.moved = true; + dragged.classList.add("dragged"); + row.classList.add("dragging"); + + // It goes before the first other color with its middle past the pointer, or last when there's none + const next = others.find((other) => { + const box = other.getBoundingClientRect(); + return e.clientX < box.left + box.width / 2; + }); + if (next ? next === dragged.nextElementSibling : !dragged.nextElementSibling) return; + + if (next) next.before(dragged); + else swatches.append(dragged); + changed(); + }; + + // Listened for on the window, since a swatch that moves in the page can lose its hold on the pointer + const dragEnd = () => { + suppressClick = Boolean(drag?.moved); + drag?.swatch.classList.remove("dragged"); + row.classList.remove("dragging"); + drag = undefined; + + window.removeEventListener("pointermove", dragMove); + window.removeEventListener("pointerup", dragEnd); + window.removeEventListener("pointercancel", dragEnd); + }; + + swatches.addEventListener("pointerdown", (e) => { + if (!(e instanceof PointerEvent)) return; + suppressClick = false; + const swatch = e.target instanceof HTMLInputElement ? e.target.parentElement : undefined; + if (removal.on() || !swatch || e.button !== 0) return; + + drag = { swatch, startX: e.clientX, moved: false }; + window.addEventListener("pointermove", dragMove); + window.addEventListener("pointerup", dragEnd); + window.addEventListener("pointercancel", dragEnd); + }); + + swatches.addEventListener("click", (e) => { + if (!(e.target instanceof HTMLInputElement)) return; + + // A drag ends with a click, which would otherwise open the picker + if (suppressClick) { + suppressClick = false; + e.preventDefault(); + return; + } + + e.preventDefault(); + + // While removing, clicking a color takes it out instead of opening its picker + if (removal.on()) { + e.target.parentElement?.remove(); + changed(); + return; + } + + // The page's own picker opens in place of the browser's + picker?.toggle(e.target); + }); + + return { inputs, append, showButtons }; +} + +/** + * The colors twice over as bands with crisp edges, matching how the Worker writes them for the credits. + * @param {string[]} colors + */ +function colorBands(colors) { + const sequence = [...colors, ...colors]; + const position = (/** @type {number} */ index) => `${Math.round((index / sequence.length) * 10000) / 100}%`; + return sequence.map((color, index) => `${color} ${position(index)} ${position(index + 1)}`).join(", "); +} + +/** + * A minus button that stays pressed while it's on, crossing out each item in its row under the pointer until one is clicked away. + * @param {HTMLElement | null} row + * @param {HTMLButtonElement | null} button + */ +function removalMode(row, button) { + let active = false; + const set = (/** @type {boolean} */ on) => { + active = on; + row?.classList.toggle("removing", on); + button?.setAttribute("aria-pressed", String(on)); + }; + button?.addEventListener("click", () => set(!active)); + + return { on: () => active, set }; +} + +/** + * A square of saturation and brightness beside a hue slider, above the hex code to type or copy, editing one color input at a time. + * @param {HTMLElement} popover + */ +function colorPopover(popover) { + const area = popover.querySelector("[data-saturation-value]"); + const hueSlider = popover.querySelector("[data-hue-slider]"); + const hexField = popover.querySelector("[data-hex-field]"); + + /** @type {HTMLInputElement | undefined} */ + let editing; + // Held apart from the hex code, so the hue survives passing through grays and black + let hue = 0; + let saturation = 0; + let value = 0; + + const clamp = (/** @type {number} */ fraction) => Math.min(Math.max(fraction, 0), 1); + + const render = () => { + popover.style.setProperty("--hue", String(hue)); + popover.style.setProperty("--saturation", String(saturation)); + popover.style.setProperty("--value", String(value)); + hueSlider?.setAttribute("aria-valuenow", String(Math.round(hue))); + area?.setAttribute("aria-valuetext", `Saturation ${Math.round(saturation * 100)}%, brightness ${Math.round(value * 100)}%`); + if (hexField instanceof HTMLInputElement && document.activeElement !== hexField) hexField.value = hsvToHex(hue, saturation, value); + }; + + // The input announces the change like the browser's picker would, so the form follows it + const commit = () => { + const hex = hsvToHex(hue, saturation, value); + if (editing && editing.value !== hex) { + editing.value = hex; + editing.dispatchEvent(new Event("input", { bubbles: true })); + } + render(); + }; + + const close = (returnFocus = false) => { + if (returnFocus) editing?.focus(); + editing?.classList.remove("editing"); + editing = undefined; + popover.hidden = true; + }; + + // Opens below the color, kept within its field so it doesn't spill out of the panel + const open = (/** @type {HTMLInputElement} */ input) => { + editing?.classList.remove("editing"); + editing = input; + editing.classList.add("editing"); + [hue, saturation, value] = hexToHsv(input.value, hue); + + // The one picker moves into whichever row holds the color, so it opens below that row + const holder = input.closest("[data-color-row]"); + if (holder && popover.parentElement !== holder) holder.append(popover); + popover.hidden = false; + render(); + + // A row beside the menu is narrower than the popover, which then reaches back under the menu + const swatch = input.parentElement; + const row = popover.offsetParent; + const field = row?.parentElement; + if (swatch && row && field) { + const fieldStart = field.getBoundingClientRect().left - row.getBoundingClientRect().left; + popover.style.left = `${Math.max(fieldStart, Math.min(swatch.offsetLeft, row.clientWidth - popover.offsetWidth))}px`; + } + if (area instanceof HTMLElement) area.focus(); + }; + + /** + * Follows a pointer pressed on the element until it lets go, wherever it goes in the meantime. + * @param {Element | null} element + * @param {(x: number, y: number) => void} move + */ + const followPointer = (element, move) => { + if (!(element instanceof HTMLElement)) return; + const report = (/** @type {PointerEvent} */ e) => { + const box = element.getBoundingClientRect(); + move(clamp((e.clientX - box.left) / box.width), clamp((e.clientY - box.top) / box.height)); + commit(); + }; + element.addEventListener("pointerdown", (e) => { + element.setPointerCapture(e.pointerId); + report(e); + }); + element.addEventListener("pointermove", (e) => { + if (element.hasPointerCapture(e.pointerId)) report(e); + }); + }; + followPointer(area, (x, y) => { + saturation = x; + value = 1 - y; + }); + followPointer(hueSlider, (_x, y) => { + hue = y * 360; + }); + + // Arrow keys step by a hundredth of the way, or a tenth with Shift held + area?.addEventListener("keydown", (e) => { + if (!(e instanceof KeyboardEvent)) return; + const step = e.shiftKey ? 0.1 : 0.01; + /** @type {Record} */ + const directions = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }; + const direction = directions[e.key]; + if (!direction) return; + + e.preventDefault(); + saturation = clamp(saturation + direction[0] * step); + value = clamp(value + direction[1] * step); + commit(); + }); + hueSlider?.addEventListener("keydown", (e) => { + if (!(e instanceof KeyboardEvent)) return; + /** @type {Record} */ + const directions = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1 }; + const direction = directions[e.key]; + if (!direction) return; + + e.preventDefault(); + hue = clamp((hue + direction * (e.shiftKey ? 36 : 3.6)) / 360) * 360; + commit(); + }); + + // A typed code takes effect once it's complete, accepting three or six digits with or without the number sign + if (hexField instanceof HTMLInputElement) { + hexField.addEventListener("input", () => { + const hex = parseHex(hexField.value); + if (!hex) return; + + [hue, saturation, value] = hexToHsv(hex, hue); + commit(); + }); + hexField.addEventListener("focus", () => hexField.select()); + hexField.addEventListener("blur", render); + + // Enter would otherwise submit the form + hexField.addEventListener("keydown", (e) => { + if (e.key !== "Enter") return; + e.preventDefault(); + close(true); + }); + } + + // Pressing anywhere outside the picker and its color closes it, as does Escape + document.addEventListener("pointerdown", (e) => { + if (editing && e.target instanceof Node && !popover.contains(e.target) && e.target !== editing) close(); + }); + document.addEventListener("keydown", (e) => { + if (editing && e.key === "Escape") close(true); + }); + + return { + editing: () => editing, + close, + toggle: (/** @type {HTMLInputElement} */ input) => (input === editing ? close() : open(input)), + }; +} + +/** + * @param {number} hue In degrees. + * @param {number} saturation From 0 to 1. + * @param {number} value From 0 to 1. + */ +function hsvToHex(hue, saturation, value) { + const channel = (/** @type {number} */ offset) => { + const position = (offset + hue / 60) % 6; + return value - value * saturation * Math.max(0, Math.min(position, 4 - position, 1)); + }; + return `#${[5, 3, 1] + .map((offset) => + Math.round(channel(offset) * 255) + .toString(16) + .padStart(2, "0"), + ) + .join("")}`; +} + +/** + * A gray has no hue of its own, so it keeps the one given. + * @param {string} hex + * @param {number} grayHue + * @returns {[number, number, number]} + */ +function hexToHsv(hex, grayHue) { + const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16) / 255); + const brightest = Math.max(red, green, blue); + const range = brightest - Math.min(red, green, blue); + + let hue = grayHue; + if (range > 0 && brightest === red) hue = (60 * ((green - blue) / range) + 360) % 360; + else if (range > 0 && brightest === green) hue = 60 * ((blue - red) / range + 2); + else if (range > 0) hue = 60 * ((red - green) / range + 4); + + return [hue, brightest === 0 ? 0 : range / brightest, brightest]; +} + +/** + * A six-digit lowercase hex code from three or six digits, with or without the number sign. + * @param {string} text + */ +function parseHex(text) { + const digits = text.trim().replace(/^#/, ""); + if (!/^([\da-f]{3}|[\da-f]{6})$/i.test(digits)) return undefined; + + return `#${(digits.length === 3 ? digits.replace(/./g, "$&$&") : digits).toLowerCase()}`; +} + +/** + * Encodes synchronously so it can finish within a form's submit event. + * @param {HTMLImageElement} image + * @param {number} x + * @param {number} y + * @param {number} side + * @param {string} name + */ +function cropToFile(image, x, y, side, name) { + const size = Math.min(Math.round(side), AVATAR_SIZE); + + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const context = canvas.getContext("2d"); + if (!context) return undefined; + + context.imageSmoothingQuality = "high"; + context.drawImage(image, x, y, side, side, 0, 0, size, size); + + // Browsers that can't encode WebP give PNG instead, which the server also accepts + const [header, base64] = canvas.toDataURL("image/webp", 0.9).split(","); + const type = header.slice("data:".length, header.indexOf(";")); + const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)); + + return new File([bytes], name, { type }); +} + +/** + * The address this tab last requested a sign-in link for, and when the Worker confirmed it, if it has. + * Storage can be blocked or throw, which just leaves the button without its countdown. + * @returns {{ address: string, sentAt?: number } | undefined} + */ +function readSignInEmail() { + try { + const stored = JSON.parse(sessionStorage.getItem(SIGN_IN_EMAIL_STORAGE_KEY) || "{}"); + if (typeof stored.address !== "string") return undefined; + + return { address: stored.address, sentAt: typeof stored.sentAt === "number" ? stored.sentAt : undefined }; + } catch { + return undefined; + } +} + +/** + * @param {{ address: string, sentAt?: number }} request + */ +function storeSignInEmail(request) { + try { + sessionStorage.setItem(SIGN_IN_EMAIL_STORAGE_KEY, JSON.stringify(request)); + } catch { + // Without storage, the next page load simply shows no countdown + } +} + +function forgetSignInEmail() { + try { + sessionStorage.removeItem(SIGN_IN_EMAIL_STORAGE_KEY); + } catch { + // Storage that can't be reached has nothing to forget + } +} diff --git a/website/templates/book.html b/website/templates/book.html index 48c3d60a4c2..c5402881de6 100644 --- a/website/templates/book.html +++ b/website/templates/book.html @@ -77,6 +77,9 @@

+ {%- if page.extra.development_notice %} +

This page documents the development version of Graphite at dev.graphite.art, which may differ from the current release.

+ {%- endif %} {{ page.content | safe }}
From f125e78ddaf6664b2ca33ff510499a42ce069b66 Mon Sep 17 00:00:00 2001 From: VimYoung Date: Mon, 23 Nov 2026 17:08:40 +0530 Subject: [PATCH 14/15] Fix: Removed default palette, enabled edit of palette name --- .../palette/palette_message_handler.rs | 187 +++++------------- frontend/src/components/panels/Palette.svelte | 49 ++--- 2 files changed, 70 insertions(+), 166 deletions(-) diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index 4014436c928..0eb798d0a90 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -9,59 +9,6 @@ use crate::messages::portfolio::document::palette::PaletteMessage; use crate::messages::prelude::*; use serde::{Deserialize, Serialize}; -// TODO: Ig this should be imported from some preloaded assets file after the -// implementation of import from file feature. -pub const DEFAULT_PALETTES: [(&str, u32, &[SRGBA8]); 3] = [ - ( - "Warm Landscape", - 5, - &[ - SRGBA8::new_opaque(0x26, 0x46, 0x53), - SRGBA8::new_opaque(0x2A, 0x9D, 0x8F), - SRGBA8::new_opaque(0xE9, 0xC4, 0x6A), - SRGBA8::new_opaque(0xF4, 0xA2, 0x61), - SRGBA8::new_opaque(0xE7, 0x6F, 0x51), - SRGBA8::new_opaque(0xD6, 0x28, 0x28), - SRGBA8::new_opaque(0x00, 0x30, 0x49), - SRGBA8::new_opaque(0xF7, 0x7F, 0x00), - SRGBA8::new_opaque(0xFC, 0xBF, 0x49), - SRGBA8::new_opaque(0xEA, 0xE2, 0xB7), - ], - ), - ( - "Nordic Frost", - 3, - &[ - SRGBA8::new_opaque(0x2E, 0x34, 0x40), - SRGBA8::new_opaque(0x3B, 0x42, 0x52), - SRGBA8::new_opaque(0x43, 0x4C, 0x5E), - SRGBA8::new_opaque(0x4C, 0x56, 0x6A), - SRGBA8::new_opaque(0xD8, 0xDE, 0xE9), - SRGBA8::new_opaque(0xE5, 0xE9, 0xF0), - SRGBA8::new_opaque(0xEC, 0xEF, 0xF4), - SRGBA8::new_opaque(0x88, 0xC0, 0xD0), - SRGBA8::new_opaque(0x81, 0xA1, 0xC1), - SRGBA8::new_opaque(0x5E, 0x81, 0xAC), - ], - ), - ( - "Something", - 2, - &[ - SRGBA8::new_opaque(0x26, 0x46, 0x53), - SRGBA8::new_opaque(0x2A, 0x9D, 0x8F), - SRGBA8::new_opaque(0xE9, 0xC4, 0x6A), - SRGBA8::new_opaque(0xF4, 0xA2, 0x61), - SRGBA8::new_opaque(0xE7, 0x6F, 0x51), - SRGBA8::new_opaque(0xD6, 0x28, 0x28), - SRGBA8::new_opaque(0x00, 0x30, 0x49), - SRGBA8::new_opaque(0xF7, 0x7F, 0x00), - SRGBA8::new_opaque(0xFC, 0xBF, 0x49), - SRGBA8::new_opaque(0xEA, 0xE2, 0xB7), - ], - ), -]; - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] pub struct PaletteId(pub u64); @@ -95,54 +42,14 @@ pub struct PaletteMessageContext { pub palette_open: bool, } -#[derive(Debug, Clone, ExtractField)] +#[derive(Debug, Clone, ExtractField, Default)] pub struct PaletteMessageHandler { // At any moment in time at least one palette should be open in the palette section - pub active_palette: PaletteId, + pub active_palette: Option, pub order: Vec, pub palettes: HashMap, } -impl Default for PaletteMessageHandler { - fn default() -> Self { - let mut palettes = HashMap::new(); - let mut order = Vec::new(); - for &(name, columns, colors) in &DEFAULT_PALETTES { - let mut grid = Vec::new(); - let mut swatches = HashMap::new(); - for color in colors { - let id = SwatchId { 0: generate_uuid() }; - grid.push(Some(id)); - swatches.insert( - id, - ColorSwatch { - id, - name: "Untitled Color".to_string(), - color: (*color).into(), - }, - ); - } - let palette_id = PaletteId { 0: generate_uuid() }; - order.push(palette_id); - palettes.insert( - palette_id, - Palette { - id: palette_id, - name: name.to_string(), - columns: Some(columns), - grid, - swatches, - }, - ); - } - Self { - active_palette: order[0], - order, - palettes, - } - } -} - #[message_handler_data] impl MessageHandler for PaletteMessageHandler { fn process_message(&mut self, message: PaletteMessage, responses: &mut VecDeque, context: PaletteMessageContext) { @@ -156,7 +63,7 @@ impl MessageHandler for PaletteMessageHan self.refresh_palette(responses); } PaletteMessage::ActivePaletteChanged { id } => { - self.active_palette = PaletteId(id); + self.active_palette = Some(PaletteId(id)); responses.add(PaletteMessage::Refresh); } PaletteMessage::PaletteNameChange { id, name } => { @@ -192,60 +99,57 @@ impl PaletteMessageHandler { if true { let mut widgets = Vec::new(); - for palette_id in self.order.iter() { - let Palette { id: _, name, columns, grid, swatches } = self.palettes.get(palette_id).unwrap(); - let is_active = *palette_id == self.active_palette; - let target_id = palette_id.0; + if let Some(active_id) = self.active_palette { + let Palette { id, name, columns, grid, swatches } = self.palettes.get(&active_id).unwrap(); + let current_id = id.clone(); let header_row = vec![ - TextLabel::new(name).bold(true).sizing(WidgetSizing::default().grow(true)).widget_instance(), + TextLabel::new(name).sizing(WidgetSizing::default().grow(true)).widget_instance(), TextInput::new(name.clone()) - .sizing(WidgetSizing::default().grow(true)) .disabled(true) .on_update(move |input: &TextInput| { PaletteMessage::PaletteNameChange { - id: target_id, + id: current_id.0, name: input.value.clone(), } .into() }) .widget_instance(), - TextButton::new("") - .flush(true) - .sizing(WidgetSizing::fixed(24)) - .disabled(is_active) - .on_commit(move |_| PaletteMessage::ActivePaletteChanged { id: target_id }.into()) - .widget_instance(), ]; widgets.push(LayoutGroup::row(header_row)); - if is_active { - let mut table_rows = Vec::new(); - if let Some(columns) = columns { - for chunk in grid.chunks(*columns as usize) { - let mut row: Vec<_> = chunk - .iter() - .map(|&id| { - if let Some(swatch_id) = id { - let swatch = swatches.get(&swatch_id).unwrap(); - ColorInput::new(FillChoice::Solid(swatch.color.into())) - .narrow(true) - .tooltip_label(swatch.name.clone()) - .widget_instance() - } else { - ColorInput::new(FillChoice::None).narrow(true).widget_instance() - } - }) - .collect(); - row.extend((row.len()..*columns as usize).map(|_| ColorInput::new(FillChoice::None).narrow(true).widget_instance())); - table_rows.push(row); - } - } else { - //TODO: Manage the case when the column size is not determined - } - - widgets.push(LayoutGroup::table(table_rows, true)); + let mut table_rows = Vec::new(); + for chunk in grid.chunks(columns.unwrap_or(5) as usize) { + let mut row: Vec<_> = chunk + .iter() + .map(|&id| { + if let Some(swatch_id) = id { + let swatch = swatches.get(&swatch_id).unwrap(); + ColorInput::new(FillChoice::Solid(swatch.color.into())) + .narrow(true) + .tooltip_label(swatch.name.clone()) + .widget_instance() + } else { + ColorInput::new(FillChoice::None).narrow(true).widget_instance() + } + }) + .collect(); + row.extend((row.len()..columns.unwrap_or(5) as usize).map(|_| ColorInput::new(FillChoice::None).narrow(true).widget_instance())); + table_rows.push(row); } + + widgets.push(LayoutGroup::table(table_rows, true)); + } else { + widgets.push(LayoutGroup::row(vec![])); + widgets.push(LayoutGroup::row(vec![ + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + TextLabel::new("Import your desired palettes to get started") + .multiline(true) + .center_align(true) + .disabled(true) + .widget_instance(), + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + ])); } let available_palettes: Vec = self @@ -261,17 +165,16 @@ impl PaletteMessageHandler { .collect(); let left_bottom_bar = LayoutGroup::row(vec![ - IconButton::new("Add", 24) - .tooltip_label("Add Palette") - .on_update(|_| IngestMessage::ImportPalette.into()) - .widget_instance(), DropdownInput::new(vec![available_palettes]) - .selected_index(self.order.iter().position(|x| x == &self.active_palette).and_then(|n| Some(n as u32))) - .draw_icon(true) + .selected_index(self.active_palette.as_ref().and_then(|palette| self.order.iter().position(|x| x == palette)).map(|n| n as u32)) .tooltip_label("Palette") .tooltip_description("Select a default entry or import a palette file to attach to the artwork") .menu_direction(Some(MenuDirection::Top)) .widget_instance(), + IconButton::new("Add", 24) + .tooltip_label("Add Palette") + .on_update(|_| IngestMessage::ImportPalette.into()) + .widget_instance(), ]); responses.add(LayoutMessage::SendLayout { @@ -360,7 +263,7 @@ impl PaletteMessageHandler { self.order.push(palette_id); self.palettes.insert(palette_id, palette); - self.active_palette = palette_id; + self.active_palette = Some(palette_id); return Ok(()); } diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte index 11388b4a56d..7f654ede97d 100644 --- a/frontend/src/components/panels/Palette.svelte +++ b/frontend/src/components/panels/Palette.svelte @@ -34,6 +34,8 @@ addEventListener("mousedown", draggingMouseDown); // Capture phase so this runs before a section header's own click handler addEventListener("click", suppressClickAfterDrag, true); + addEventListener("keydown", paletteNameKeyDown); + addEventListener("focusout", paletteNameFocusOut); }); onDestroy(() => { @@ -44,6 +46,8 @@ removeEventListener("keydown", draggingKeyDown); removeEventListener("mousedown", draggingMouseDown); removeEventListener("click", suppressClickAfterDrag, true); + removeEventListener("keydown", paletteNameKeyDown); + removeEventListener("focusout", paletteNameFocusOut); autoScroller.stop(); }); @@ -58,7 +62,7 @@ function editPaletteName(e: MouseEvent) { const target = e.target instanceof Element ? e.target : undefined; // eslint-disable-next-line graphite/require-data-selectors - const label = target?.closest(".widget-span.row:has(> .text-label + .text-input + .text-button) > .text-label"); + const label = target?.closest(".widget-span.row:has(> .text-label + .text-input) > .text-label"); const row = label?.parentElement; if (!label || !row) return; // eslint-disable-next-line graphite/require-data-selectors @@ -75,10 +79,10 @@ input.select(); } - function finishPaletteNameEdit(target: EventTarget | undefined) { + function finishPaletteNameEdit(target?: EventTarget) { const element = target instanceof Element ? target : undefined; // eslint-disable-next-line graphite/require-data-selectors - const row = element?.closest(".widget-span.row.palette-name-editing"); + const row = element?.closest(".widget-span.row.palette-name-editing") ?? sectionsCol?.div()?.querySelector(".widget-span.row.palette-name-editing"); // eslint-disable-next-line graphite/require-data-selectors const field = row?.querySelector(":scope > .text-input"); // eslint-disable-next-line graphite/require-data-selectors @@ -88,11 +92,17 @@ row.classList.remove("palette-name-editing"); field.classList.add("disabled"); input.disabled = true; + input.blur(); } - function paletteNameKeyDown(e: CustomEvent) { - const key = e.detail?.key; - if (key === "Enter") finishPaletteNameEdit(e.target instanceof Element ? e.target : undefined); + function paletteNameKeyDown(e: KeyboardEvent) { + if (e.key === "Enter" || e.key === "Escape") { + finishPaletteNameEdit(e.target instanceof Element ? e.target : undefined); + } + } + + function paletteNameFocusOut(e: FocusEvent) { + finishPaletteNameEdit(e.target instanceof Element ? e.target : undefined); } function reorderableSections(): Element[] { @@ -223,16 +233,7 @@ - finishPaletteNameEdit(e.target ?? undefined)} - on:keydown={paletteNameKeyDown} - > + {#if dragging && insertMarker} @@ -310,27 +311,27 @@ } } - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-label), - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-input) { + :global(.widget-span.row:has(> .text-label + .text-input) > .text-label), + :global(.widget-span.row:has(> .text-label + .text-input) > .text-input) { flex: 1 1 0; min-width: 0; overflow: visible; } - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-input) { + :global(.widget-span.row:has(> .text-label + .text-input) > .text-input) { display: none; } - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-input.disabled) { + :global(.widget-span.row:has(> .text-label + .text-input) > .text-input.disabled) { background: none; } - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-input.disabled input) { + :global(.widget-span.row:has(> .text-label + .text-input) > .text-input.disabled input) { color: var(--color-e-nearwhite); -webkit-text-fill-color: var(--color-e-nearwhite); } - :global(.widget-span.row:has(> .text-label + .text-input + .text-button) > .text-input input) { + :global(.widget-span.row:has(> .text-label + .text-input) > .text-input input) { width: 100%; min-width: 0; margin: 0; @@ -339,11 +340,11 @@ text-overflow: ellipsis; } - :global(.widget-span.row.palette-name-editing:has(> .text-label + .text-input + .text-button) > .text-label) { + :global(.widget-span.row.palette-name-editing:has(> .text-label + .text-input) > .text-label) { display: none; } - :global(.widget-span.row.palette-name-editing:has(> .text-label + .text-input + .text-button) > .text-input) { + :global(.widget-span.row.palette-name-editing:has(> .text-label + .text-input) > .text-input) { display: flex; } From 80c886b39bf8cad2338f5641796d7125c41ccea6 Mon Sep 17 00:00:00 2001 From: VimYoung Date: Mon, 23 Nov 2026 19:08:15 +0530 Subject: [PATCH 15/15] Add: Right bottom bar section in Palette --- .../document/palette/palette_message_handler.rs | 11 +++++++++++ .../portfolio/ingest/ingest_message_handler.rs | 2 +- frontend/src/components/panels/Palette.svelte | 5 +++-- frontend/src/stores/portfolio.ts | 6 ++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs index 0eb798d0a90..977bd3b2a1d 100644 --- a/editor/src/messages/portfolio/document/palette/palette_message_handler.rs +++ b/editor/src/messages/portfolio/document/palette/palette_message_handler.rs @@ -171,6 +171,13 @@ impl PaletteMessageHandler { .tooltip_description("Select a default entry or import a palette file to attach to the artwork") .menu_direction(Some(MenuDirection::Top)) .widget_instance(), + ]); + + let right_bottom_bar = LayoutGroup::row(vec![ + IconButton::new("Edit", 24) + .tooltip_label("Edit the name of Palette") + .on_update(|_| IngestMessage::ImportPalette.into()) + .widget_instance(), IconButton::new("Add", 24) .tooltip_label("Add Palette") .on_update(|_| IngestMessage::ImportPalette.into()) @@ -185,6 +192,10 @@ impl PaletteMessageHandler { layout: Layout(vec![left_bottom_bar]), layout_target: LayoutTarget::PalettePanelBottomLeftBar, }); + responses.add(LayoutMessage::SendLayout { + layout: Layout(vec![right_bottom_bar]), + layout_target: LayoutTarget::PalettePanelBottomRightBar, + }); } else { // TODO: Add attached palettes instead } diff --git a/editor/src/messages/portfolio/ingest/ingest_message_handler.rs b/editor/src/messages/portfolio/ingest/ingest_message_handler.rs index a88ca3b75e0..210b79ade99 100644 --- a/editor/src/messages/portfolio/ingest/ingest_message_handler.rs +++ b/editor/src/messages/portfolio/ingest/ingest_message_handler.rs @@ -33,7 +33,7 @@ impl MessageHandler for IngestMessageHandle }), IngestMessage::ImportPalette => responses.add(IngestMessage::Browse { filters: vec![TypeFilter::palette()], - multiple: false, + multiple: true, action: IngestAction::ImportPalette, }), IngestMessage::SetResourceInput { diff --git a/frontend/src/components/panels/Palette.svelte b/frontend/src/components/panels/Palette.svelte index 7f654ede97d..6c602e3c8f7 100644 --- a/frontend/src/components/panels/Palette.svelte +++ b/frontend/src/components/panels/Palette.svelte @@ -5,7 +5,7 @@ import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutRow from "/src/components/layout/LayoutRow.svelte"; import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; - import { paletteLayout, palettePanelBottomLeftBarLayout } from "/src/stores/portfolio"; + import { paletteLayout, palettePanelBottomLeftBarLayout, palettePanelBottomRightBarLayout } from "/src/stores/portfolio"; import { createAutoScroller } from "/src/utility-functions/auto-scroll"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; @@ -240,8 +240,9 @@
{/if}
- + +
diff --git a/frontend/src/stores/portfolio.ts b/frontend/src/stores/portfolio.ts index ec6d55af193..710b0d6cb70 100644 --- a/frontend/src/stores/portfolio.ts +++ b/frontend/src/stores/portfolio.ts @@ -41,6 +41,7 @@ export const welcomeScreenButtonsLayout = persistedLayout("welcomeScreenButtonsL export const inspectorLayout = persistedLayout("inspectorLayout"); export const paletteLayout = persistedLayout("paletteLayout"); export const palettePanelBottomLeftBarLayout = persistedLayout("palettePanelBottomLeftBarLayout"); +export const palettePanelBottomRightBarLayout = persistedLayout("palettePanelBottomRightBarLayout"); export const dataPanelLayout = persistedLayout("dataPanelLayout"); export const dataPanelContextLayout = persistedLayout("dataPanelContextLayout"); export const dataPanelPathLayout = persistedLayout("dataPanelPathLayout"); @@ -157,6 +158,10 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor: patchLayout(palettePanelBottomLeftBarLayout, data); }); + subscriptions.subscribeLayoutUpdate("PalettePanelBottomRightBar", (data) => { + patchLayout(palettePanelBottomRightBarLayout, data); + }); + subscriptions.subscribeLayoutUpdate("CollaborationPanel", (data) => { patchLayout(collaborationPanelLayout, data); }); @@ -223,6 +228,7 @@ export function destroyPortfolioStore() { subscriptions.unsubscribeLayoutUpdate("Inspector"); subscriptions.unsubscribeLayoutUpdate("Palette"); subscriptions.unsubscribeLayoutUpdate("PalettePanelBottomLeftBar"); + subscriptions.unsubscribeLayoutUpdate("PalettePanelBottomRightBar"); subscriptions.unsubscribeLayoutUpdate("DataPanel"); subscriptions.unsubscribeLayoutUpdate("DataPanelContext"); subscriptions.unsubscribeLayoutUpdate("DataPanelPath");