Skip to content

Make the Pen tool show a path being closed by drawing a filled overlay when hovering the endpoint #2521

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 18 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions editor/src/messages/input_mapper/input_mappings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(Enter); action_dispatch=SplineToolMessage::Confirm),
//
// FillToolMessage
entry!(PointerMove; action_dispatch=FillToolMessage::PointerMove),
entry!(KeyDown(MouseLeft); action_dispatch=FillToolMessage::FillPrimaryColor),
entry!(KeyDown(MouseLeft); modifiers=[Shift], action_dispatch=FillToolMessage::FillSecondaryColor),
entry!(KeyUp(MouseLeft); action_dispatch=FillToolMessage::PointerUp),
Expand Down
46 changes: 44 additions & 2 deletions editor/src/messages/portfolio/document/overlays/utility_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}

/// This is used by the pen and path tool to outline the path of the shape
pub fn outline_vector(&mut self, vector_data: &VectorData, transform: DAffine2) {
self.start_dpi_aware_transform();

Expand All @@ -465,6 +466,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}

/// This is used by the pen tool in order to show how the bezier curve would look like
pub fn outline_bezier(&mut self, bezier: Bezier, transform: DAffine2) {
self.start_dpi_aware_transform();

Expand Down Expand Up @@ -493,7 +495,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}

pub fn outline(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
self.start_dpi_aware_transform();

self.render_context.begin_path();
Expand Down Expand Up @@ -540,10 +542,50 @@ impl OverlayContext {
}
}

self.end_dpi_aware_transform();
}

/// This is used by the select tool to outline a path selected or hovered
pub fn outline(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
self.push_path(subpaths, transform);

self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.stroke();
}

self.end_dpi_aware_transform();
/// Fills the area inside the path
/// This is used by the fill tool to show the area to be filled and by the pen tool to show the path being closed
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.push_path(subpaths, transform);

self.render_context.set_fill_style_str(color);
self.render_context.fill();
}

pub fn strip_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.push_path(subpaths, transform);

// Canvas state must be saved before clipping
self.render_context.save();
self.render_context.clip();

self.render_context.begin_path();
self.render_context.set_line_width(1.0);
self.render_context.set_stroke_style_str(color);

// Draw the diagonal lines
let line_separation = 24 as f64; // in px
let max_dimension = if self.size.x > self.size.y { self.size.x } else { self.size.y };
let end = (max_dimension / line_separation * 2.0).ceil() as i32;
for n in 1..end {
let factor = n as f64;
self.render_context.move_to(line_separation * factor, 0.0);
self.render_context.line_to(0.0, line_separation * factor);
self.render_context.stroke();
}

// Undo the clipping
self.render_context.restore();
}

pub fn get_width(&self, text: &str) -> f64 {
Expand Down
30 changes: 29 additions & 1 deletion editor/src/messages/tool/tool_messages/fill_tool.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
use super::tool_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use graphene_core::vector::style::Fill;

#[derive(Default)]
pub struct FillTool {
fsm_state: FillToolFsmState,
}

#[impl_message(Message, ToolMessage, Fill)]
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
#[derive(PartialEq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum FillToolMessage {
// Standard messages
Abort,
Overlays(OverlayContext),

// Tool-specific messages
PointerMove,
PointerUp,
FillPrimaryColor,
FillSecondaryColor,
Expand Down Expand Up @@ -45,8 +49,10 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for FillToo
FillToolFsmState::Ready => actions!(FillToolMessageDiscriminant;
FillPrimaryColor,
FillSecondaryColor,
PointerMove,
),
FillToolFsmState::Filling => actions!(FillToolMessageDiscriminant;
PointerMove,
PointerUp,
Abort,
),
Expand All @@ -58,6 +64,7 @@ impl ToolTransition for FillTool {
fn event_to_message_map(&self) -> EventToMessageMap {
EventToMessageMap {
tool_abort: Some(FillToolMessage::Abort.into()),
overlay_provider: Some(|overlay_context| FillToolMessage::Overlays(overlay_context).into()),
..Default::default()
}
}
Expand All @@ -82,6 +89,27 @@ impl Fsm for FillToolFsmState {

let ToolMessage::Fill(event) = event else { return self };
match (self, event) {
(_, FillToolMessage::Overlays(mut overlay_context)) => {
// When not in Drawing State
// Only highlight layers if the viewport is not being panned (middle mouse button is pressed)
// TODO: Don't use `Key::MouseMiddle` directly, instead take it as a variable from the input mappings list like in all other places; or find a better way than checking the key state
if !input.keyboard.get(Key::MouseMiddle as usize) {
let primary_color = global_tool_data.primary_color;
let preview_color = primary_color.to_gamma_srgb().to_css();

// Get the layer the user is hovering over
let click = document.click(input);
if let Some(layer) = click {
overlay_context.strip_path(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), preview_color.as_str());
}
}
self
}
(_, FillToolMessage::PointerMove) => {
// Generate the hover outline
responses.add(OverlaysMessage::Draw);
FillToolFsmState::Ready
}
(FillToolFsmState::Ready, color_event) => {
let Some(layer_identifier) = document.click(input) else {
return self;
Expand Down
58 changes: 56 additions & 2 deletions editor/src/messages/tool/tool_messages/pen_tool.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::tool_prelude::*;
use crate::consts::{DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE};
use crate::consts::{COLOR_OVERLAY_BLUE, DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE};
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
Expand All @@ -15,7 +15,7 @@ use bezier_rs::{Bezier, BezierHandles};
use graph_craft::document::NodeId;
use graphene_core::Color;
use graphene_core::vector::{PointId, VectorModificationType};
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, VectorData};
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, StrokeId, VectorData};

#[derive(Default)]
pub struct PenTool {
Expand Down Expand Up @@ -1613,6 +1613,60 @@ impl Fsm for PenToolFsmState {
overlay_context.manipulator_anchor(next_anchor, false, None);
}

// Fill the shape if the new point closes the path
if tool_data.latest_point().is_some() {
let latest_point = tool_data.latest_point().unwrap();

let handle_start = latest_point.handle_start;
let handle_end = tool_data.handle_end.unwrap_or(tool_data.next_handle_start);
let next_point = tool_data.next_point;

// Check if the next point is close to any other point in the vector data
let mut end = None;

let start = latest_point.id;
if layer.is_some() {
let mut vector_data = document.network_interface.compute_modified_vector(layer.unwrap()).unwrap();
for id in vector_data.extendable_points(preferences.vector_meshes).filter(|&point| point != start) {
let Some(pos) = vector_data.point_domain.position_from_id(id) else { continue };
let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point));
let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2);
if transformed_distance_between_squared < snap_point_tolerance_squared {
end = Some(id);
}
}

// We have the point. Join the 2 vertices and check if any path is closed
if end.is_some() {
let id: SegmentId = SegmentId::generate();
vector_data.push(id, start, end.unwrap(), BezierHandles::Cubic { handle_start, handle_end }, StrokeId::ZERO);

let grouped_segments = vector_data.auto_join_paths();

// Find the closed paths with the last added segment
let closed_paths = grouped_segments.iter().filter(|path| path.is_closed() && path.contains(id));

// Get the bezier curves of the closed path
let subpaths: Vec<_> = closed_paths
.filter_map(|path| {
let segments = path.edges.iter().filter_map(|edge| {
vector_data
.segment_domain
.iter()
.find(|(id, _, _, _)| id == &edge.id)
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
});
vector_data.subpath_from_segments_ignore_discontinuities(segments)
})
.collect();

let fill_color = Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.05).to_css();

overlay_context.fill_path(subpaths.iter(), transform, fill_color.as_str());
}
}
}

// Draw the overlays that visualize current snapping
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);

Expand Down
6 changes: 6 additions & 0 deletions node-graph/gcore/src/raster/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,12 @@ impl Color {
}
}

/// Produces a CSS color in the format `rgb(red green blue / alpha%)`.
/// To get the expected color you might have to use `to_gamma_srgb`.
pub fn to_css(&self) -> String {
format!("rgb({} {} {} / {}%)", self.red * 255.0, self.green * 255.0, self.blue * 255.0, self.alpha * 100.0)
}

#[inline(always)]
pub fn srgb_to_linear(channel: f32) -> f32 {
if channel <= 0.04045 { channel / 12.92 } else { ((channel + 0.055) / 1.055).powf(2.4) }
Expand Down
Loading
Loading