Add typed length and angle values with a per-document resolution

This commit is contained in:
Keavon Chambers committed 2026-11-26 02:35:55 -08:00
1 parent 6a28b82b91
commit ea9c44e003
57 files changed
+1286 -50

No files matched your search

Generated
+1
View File
@@ -1226,6 +1226,7 @@ dependencies = [
"kurbo",
"log",
"lyon_geom",
"math-parser",
"node-macro",
"num-derive",
"num-traits",
@@ -57,6 +57,10 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names";
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
/// is the default, CSS's 96. Only the root network's applies.
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
}
pub mod delta {
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
attributes
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
}
Ok(())
}
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: Vec<String>,
pub export_descriptions: Vec<String>,
/// The document's pixels per inch, where it differs from the default.
pub pixels_per_inch: Option<f64>,
}
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
Vec::new()
}
/// The network's pixels per inch, where it differs from the default.
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
None
}
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
Vec::new()
}
+1
View File
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
}
}
@@ -0,0 +1,65 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&CircleV1, &contract());
check_undo(&CircleV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&CircleV1);
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&CircleV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
}
}
@@ -1,4 +1,5 @@
//! Migrations of the nodes in `vector_nodes`.
mod circle_v1;
mod path_from_path_network;
mod renames;
@@ -6,6 +6,8 @@ use crate::messages::prelude::*;
pub enum DialogMessage {
// Sub-messages
#[child]
DocumentSetupDialog(DocumentSetupDialogMessage),
#[child]
ExportDialog(ExportDialogMessage),
#[child]
NewDocumentDialog(NewDocumentDialogMessage),
@@ -34,6 +36,7 @@ pub enum DialogMessage {
localized_commit_year: String,
},
RequestDemoArtworkDialog,
RequestDocumentSetupDialog,
RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String,
@@ -16,6 +16,7 @@ pub struct DialogMessageContext<'a> {
pub struct DialogMessageHandler {
on_dismiss: Option<Message>,
redisplay: Option<Message>,
document_setup_dialog: DocumentSetupDialogMessageHandler,
export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler,
@@ -27,6 +28,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let DialogMessageContext { portfolio, preferences } = context;
match message {
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
@@ -100,6 +102,15 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = DemoArtworkDialog;
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestDocumentSetupDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
pixels_per_inch: document.network_interface.pixels_per_inch(),
};
self.document_setup_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestExportDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
@@ -0,0 +1,9 @@
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DocumentSetupDialogMessage {
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -0,0 +1,158 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
/// A dialog to allow users to change the settings of the active document.
#[derive(Debug, Clone, ExtractField)]
pub struct DocumentSetupDialogMessageHandler {
pub pixels_per_inch: f64,
}
impl Default for DocumentSetupDialogMessageHandler {
fn default() -> Self {
Self {
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
}
#[message_handler_data]
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
DocumentSetupDialogMessage::Submit => {
// The settings apply as one undo step, which ending the transaction drops if nothing changed
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
responses.add(DocumentMessage::EndTransaction);
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions!(DocumentSetupDialogUpdate;
);
}
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Document Setup";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for DocumentSetupDialogMessageHandler {
fn layout(&self) -> Layout {
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
Layout(vec![LayoutGroup::row(resolution)])
}
}
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
vec![
TextLabel::new("Resolution")
.table_align(true)
.sizing(WidgetSizing::fixed(90))
.tooltip_label("Resolution")
.tooltip_description(description)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(pixels_per_inch))
.unit(" PPI")
.min(1.)
.max(100_000.)
.tooltip_label("Resolution")
.tooltip_description(description)
// Matches the width of the New Document dialog's Name field
.sizing(WidgetSizing::default().min_width(204))
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
.widget_instance(),
]
}
#[cfg(test)]
mod tests {
use crate::test_utils::test_prelude::*;
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
editor.active_document().network_interface.pixels_per_inch()
}
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
}
async fn confirm(editor: &mut EditorTestUtils) {
editor
.handle_message(DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
})
.await;
}
#[tokio::test]
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer_count = editor.active_document().metadata().all_layers().count();
open_and_set_resolution(&mut editor, 300.).await;
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
// Undoing reverts only the resolution, leaving the rectangle drawn before it
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96.);
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(pixels_per_inch(&editor), 300.);
}
#[tokio::test]
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
open_and_set_resolution(&mut editor, 300.).await;
confirm(&mut editor).await;
open_and_set_resolution(&mut editor, 150.).await;
editor.handle_message(DialogMessage::Close).await;
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
}
}
@@ -0,0 +1,7 @@
mod document_setup_dialog_message;
mod document_setup_dialog_message_handler;
#[doc(inline)]
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
#[doc(inline)]
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
+1
View File
@@ -8,6 +8,7 @@
mod dialog_message;
mod dialog_message_handler;
pub mod document_setup_dialog;
pub mod export_dialog;
pub mod new_document_dialog;
pub mod preferences_dialog;
@@ -417,16 +417,20 @@ impl LayoutMessageHandler {
}
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => {
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
return;
};
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
if number_input.value == Some(evaluated) {
if number_input.value == Some(evaluated) && number_input.unit == unit {
return;
}
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
responses.add((number_input.on_commit.callback)(&()));
number_input.value = Some(evaluated);
number_input.unit = unit;
responses.add((number_input.on_update.callback)(number_input));
}
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
@@ -704,30 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) {
}
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
let value = math_parser::evaluate(expression)
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
pub fn unit_suffix(symbol: &str) -> String {
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
let value = math_parser::ast::Node::try_parse_from_str(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.eval(&context)
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?;
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
let field_unit = math_parser::units::Unit::named(number_input.unit.trim());
let real = match (value.as_quantity(), field_unit) {
(Some(quantity), Some(unit)) => quantity
.read_in(unit, math_parser::units::DEFAULT_PIXELS_PER_INCH)
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
.ok()?
.as_real()?,
_ => value.as_real()?,
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
(Some(quantity), Some(unit)) => {
let read = quantity
.read_in(unit, number_input.pixels_per_inch)
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
.ok()?
.as_real()?;
(read, Some(*quantity))
}
_ => (value.as_real()?, None),
};
if real.is_nan() {
if in_field_unit.is_nan() {
return None;
}
let mut validated = real;
let mut validated = in_field_unit;
if let Some(min) = number_input.min {
validated = validated.max(min);
}
@@ -738,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
validated = validated.round();
}
Some(validated)
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
let kept_unit = quantity.and_then(|quantity| {
let symbol = quantity.unit.single()?.definition().symbol;
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
});
if let Some((quantity, symbol)) = kept_unit
&& validated == in_field_unit
&& let Some(kept_value) = quantity.value.as_real()
{
return Some((kept_value, Some(symbol.to_string())));
}
Some((validated, None))
}
@@ -247,6 +247,14 @@ pub struct NumberInput {
#[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool,
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
#[serde(skip)]
pub kept_units: Vec<String>,
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
#[serde(skip)]
#[derivative(Default(value = "96."))]
pub pixels_per_inch: f64,
// Tooltips
#[serde(rename = "tooltipLabel")]
@@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Document Setup…")
.label("Document Setup…")
.icon("Settings")
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))]
vec![preferences],
])
@@ -25,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::Footprint;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::units::{Angle, Length};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
@@ -401,6 +402,8 @@ macro_rules! inspectable_types {
List<Generator>,
List<String>,
List<f64>,
List<Length>,
List<Angle>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -461,6 +464,8 @@ macro_rules! inspectable_types {
Item<Generator>,
Item<String>,
Item<f64>,
Item<Length>,
Item<Angle>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -1100,6 +1105,30 @@ impl TableItemLayout for f64 {
}
}
impl TableItemLayout for Length {
fn type_name() -> &'static str {
"Length"
}
fn identifier(&self) -> String {
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for Angle {
fn type_name() -> &'static str {
"Angle"
}
fn identifier(&self) -> String {
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for u8 {
fn type_name() -> &'static str {
"Byte"
@@ -266,6 +266,11 @@ pub enum DocumentMessage {
SetRenderMode {
render_mode: RenderMode,
},
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
/// The caller wraps it in a transaction to make it one undo step.
SetPixelsPerInch {
pixels_per_inch: f64,
},
ShowNodeInGraph {
node_id: NodeId,
},
@@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::{GradientStops, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -1694,6 +1695,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.render_mode = render_mode;
responses.add_front(NodeGraphMessage::RunDocumentGraph);
}
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
return;
}
self.network_interface.set_pixels_per_inch(pixels_per_inch);
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(InspectorMessage::Refresh);
}
DocumentMessage::ShowNodeInGraph { node_id } => {
// The node is in the document network, so the graph first leaves any nested network it's showing
if !self.breadcrumb_network_path.is_empty() {
@@ -3230,7 +3241,10 @@ impl DocumentMessageHandler {
}
pub fn current_hash(&self) -> u64 {
self.network_interface.document_network().current_hash()
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
hasher.finish()
}
pub fn is_auto_saved(&self) -> bool {
@@ -2,6 +2,7 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::layout_message_handler::unit_suffix;
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
@@ -31,6 +32,7 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
@@ -305,7 +307,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
step,
} = options;
let mut number_input = NumberInput::default();
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
if slider {
number_input = number_input.mode_range();
}
@@ -387,6 +389,8 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Angle>(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
@@ -896,6 +900,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
@@ -912,6 +917,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
.on_commit(commit_value)
.widget_instance(),
@@ -923,6 +929,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -938,6 +945,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
.on_commit(commit_value)
.widget_instance(),
@@ -949,6 +957,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -1317,6 +1326,92 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
widgets
}
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
NumberInput {
min: convert(number_input.min),
max: convert(number_input.max),
range_min: convert(number_input.range_min),
range_max: convert(number_input.range_max),
..number_input
}
}
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
/// field's bounds given in pixels.
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let length = match input.as_non_exposed_value() {
Some(&TaggedValue::Length(length)) => length,
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
_ => return widgets,
};
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(length.value))
.unit(unit_suffix(length.unit.symbol()))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
TaggedValue::Length(TypedLength {
value: input.value.unwrap_or_default(),
unit,
})
}))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
/// field's bounds given in degrees.
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let angle = match input.as_non_exposed_value() {
Some(&TaggedValue::Angle(angle)) => angle,
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
_ => return widgets,
};
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees)));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(angle.value))
.unit(unit_suffix(angle.unit.symbol()))
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
TaggedValue::Angle(TypedAngle {
value: input.value.unwrap_or_default(),
unit,
})
}))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
// TODO: Auto-generate this enum dropdown menu widget
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
@@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() {
);
}
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
#[test]
fn pixels_per_inch_round_trips_through_the_registry() {
let round_trip = |pixels_per_inch: f64| {
let mut document = open_demo("changing-seasons.graphite");
document.network_interface.set_pixels_per_inch(pixels_per_inch);
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
(
rebuilt.pixels_per_inch(),
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
)
};
assert_eq!(round_trip(300.), (300., Some(300.)));
assert_eq!(round_trip(96.), (96., None));
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
@@ -105,6 +105,7 @@ impl NodeNetworkInterface {
match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
@@ -75,6 +75,7 @@ pub enum NetworkMetadataChange {
Reference(Option<String>),
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
PinnedOrder(Vec<NodeId>),
PixelsPerInch(Option<f64>),
ImportMetadata(Vec<InputMetadata>),
ExportNames(Vec<String>),
ExportDescriptions(Vec<String>),
@@ -256,6 +257,12 @@ impl EditorDelta {
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
}
}
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta {
key: network_attr::PIXELS_PER_INCH.to_string(),
value: pixels_per_inch
.map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch))
.transpose()?,
},
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
@@ -1254,6 +1254,19 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
/// Sets how many pixels make an inch in the document, stored only where it differs from the default.
pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) {
let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch);
let Some(mut network) = self.network_mut(&[]) else {
log::error!("Could not get the root network in set_pixels_per_inch");
return;
};
network.set_pixels_per_inch(stored);
self.transaction_modified();
}
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_visibility");
@@ -128,10 +128,18 @@ impl NodeNetworkInterface {
});
let mut hasher = std::hash::DefaultHasher::new();
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher);
hasher.finish()
}
/// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit.
pub fn pixels_per_inch(&self) -> f64 {
self.network_metadata(&[])
.and_then(|metadata| metadata.persistent_metadata.pixels_per_inch)
.filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.)
.unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH)
}
/// Get the specified document node in the nested network based on node_id and network_path
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
self.query(network_path, "document_node", |view| view.node(node_id))
@@ -143,6 +143,9 @@ impl NodeNetworkInterface {
if current_metadata.pinned_node_order != target.metadata.pinned_order {
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
}
if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch {
deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch)));
}
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
@@ -111,6 +111,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
}
fn pixels_per_inch(&self, network: NetworkLocation) -> Option<f64> {
self.network_persistent(network)?.pixels_per_inch
}
}
impl DocumentSettings<'_> {
@@ -307,6 +311,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
network_metadata.persistent_metadata.reference = Some(reference);
}
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch;
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
network_metadata.persistent_metadata.export_names = entry.export_names;
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
@@ -538,6 +538,16 @@ impl NetworkMut<'_> {
changed
}
/// How many pixels make an inch in the document, or `None` for the default.
pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option<f64>) -> bool {
let changed = self.metadata.pixels_per_inch != pixels_per_inch;
self.metadata.pixels_per_inch = pixels_per_inch;
if changed {
self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch));
}
changed
}
/// The display order of pinned nodes in the Inspector.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
@@ -511,6 +511,7 @@ impl NodeNetworkInterface {
.into_iter()
.chain([
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
@@ -291,6 +291,7 @@ impl NodeTemplateImplementation {
reference,
node_metadata,
pinned_node_order,
pixels_per_inch: None,
previewing,
navigation_metadata,
selection_undo_history: Default::default(),
@@ -674,6 +674,9 @@ pub struct NodeNetworkPersistentMetadata {
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
#[serde(default)]
pub pinned_node_order: Vec<NodeId>,
/// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pixels_per_inch: Option<f64>,
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
/// 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.
pub previewing: Previewing,
+1
View File
@@ -11,6 +11,7 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext,
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
pub use crate::messages::dialog::document_setup_dialog::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant, DocumentSetupDialogMessageHandler};
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
@@ -194,9 +194,15 @@ impl RadiusHandle {
// The size is snapped, which keeps whichever sign the radius has come to
let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum();
// A radius typed in a unit like millimeters stays in it
let input_connector = InputConnector::node(node_id, radius_parameter);
let radius = match document.network_interface.input_from_connector(&input_connector, &[]).and_then(|input| input.as_value()) {
Some(existing @ TaggedValue::Length(_)) => existing.length_in_same_unit(snapped_radius, document.network_interface.pixels_per_inch()),
_ => TaggedValue::Number(snapped_radius),
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
input_connector,
input: NodeInput::value(radius, false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -12,6 +12,7 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
use crate::messages::tool::tool_messages::tool_prelude::*;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::units::TypedLength;
#[derive(Clone, Debug, Default)]
pub struct CircleGizmoHandler {
@@ -108,7 +109,7 @@ impl Circle {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
input: NodeInput::value(TaggedValue::Number(radius), false),
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
@@ -421,11 +421,7 @@ pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) ->
pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<f64> {
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?;
let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else {
return None;
};
Some(radius)
node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch())
}
/// Calculate the viewport position of as a star vertex given its index
+4
View File
@@ -271,6 +271,7 @@ impl NodeGraphExecutor {
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -301,6 +302,7 @@ impl NodeGraphExecutor {
previewed,
layers,
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
@@ -492,6 +494,7 @@ impl NodeGraphExecutor {
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -891,6 +894,7 @@ impl NodeGraphExecutor {
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.is_err()
{
+6 -3
View File
@@ -124,6 +124,8 @@ pub struct GraphUpdate {
pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
/// The document's pixels per inch, which sizes lengths typed in a physical unit.
pub(super) pixels_per_inch: f64,
}
/// Replaces each network's primary export with its previewed node.
@@ -240,6 +242,7 @@ impl NodeRuntime {
previewed,
layers,
observations,
pixels_per_inch,
}) = graph
else {
return;
@@ -252,7 +255,7 @@ impl NodeRuntime {
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
let result = self.update_network(network.clone(), pixels_per_inch);
self.compile_failed = result.is_err();
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -521,8 +524,8 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
fn update_network(&mut self, graph: NodeNetwork, pixels_per_inch: f64) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle(), pixels_per_inch);
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
@@ -75,6 +75,9 @@
let inputRangeElement: HTMLInputElement | undefined;
let text = exact ?? displayText(value, unit);
let editing = false;
// While editing, the unit a number typed without one is read in shows faintly after the text
$: ghostUnit = editing && exact === undefined && unit.trim() !== "" && !endsInUnit(text) ? unit : "";
let isDragging = false;
let pressingArrow = false;
let repeatTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
@@ -118,7 +121,7 @@
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
$: watchValue(value, unit);
$: watchValue(value, unit, min, max);
$: if (exact !== undefined && !editing) text = exact;
$: present = exact !== undefined || value !== undefined;
// A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
@@ -176,8 +179,8 @@
// TRACKING AND UPDATING THE VALUE
// ===============================
// Called only when `value` is changed from outside this component.
function watchValue(value: number | undefined, unit: string) {
// Called only when `value`, its unit, or its bounds are changed from outside this component.
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) {
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag)
if (rangeSliderClickDragState === "Dragging") return;
@@ -381,6 +384,11 @@
return `${number}`;
}
// Whether typed text ends in a unit (or a name), so no unit is assumed after it
function endsInUnit(typed: string): boolean {
return /[\p{L}%°'"]\s*$/u.test(typed);
}
// Removes the trailing "s" from a unit if the quantity is 1.
function unPluralize(unit: string, quantity: number): string {
if (quantity !== 1 || !unit.endsWith("s")) return unit;
@@ -1002,6 +1010,9 @@
>{text.slice(markedDigit + 1)}</span
>
{/if}
{#if ghostUnit}
<span class="ghost-unit">{text}<span class="unit">{ghostUnit}</span></span>
{/if}
{#if present}
{#if mode === "Increment" && incrementBehavior !== "None"}
<button
@@ -1103,6 +1114,24 @@
display: none;
}
// Laid out like the field's text while it's edited, which it mirrors in transparent characters before the faint unit
.ghost-unit {
position: absolute;
inset: 0;
margin: 0 8px;
padding: 3px 0;
line-height: calc(var(--widget-height) - 6px);
text-align: left;
white-space: pre;
overflow: hidden;
color: transparent;
pointer-events: none;
.unit {
color: var(--color-8-uppergray);
}
}
// A disabled field's underline only marks the stepped digit, with no press target to hover or drag
&.disabled .digit-mark .marked::after {
pointer-events: none;
@@ -6,6 +6,7 @@ use core_types::color::SRGBA8;
use core_types::list::{Item, List, NodeIdPath};
use core_types::transfer_curve::TransferCurve;
use core_types::transform::Footprint;
use core_types::units::{Angle, AngleUnit, DEFAULT_PIXELS_PER_INCH, Length, LengthUnit, TypedAngle, TypedLength};
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
@@ -83,6 +84,11 @@ macro_rules! tagged_value {
BoxCorners(Vec<f64>),
/// Stored compactly as a `Vec<DVec2>` of control points, materializes as an `Item<TransferCurve>` at runtime via `to_dynany`/`to_any`.
TransferCurve(Vec<DVec2>),
/// A length in the unit it was typed in, materializing as an `Item<Length>` in pixels. A physical unit needs the document's resolution,
/// so the preprocessor replaces it with a conversion node reading that from the scope.
Length(TypedLength),
/// An angle in the unit it was typed in, materializing as an `Item<Angle>`.
Angle(TypedAngle),
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
@@ -132,6 +138,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => lengths.cache_hash(state),
Self::BoxCorners(values) => values.cache_hash(state),
Self::TransferCurve(points) => points.cache_hash(state),
Self::Length(length) => length.cache_hash(state),
Self::Angle(angle) => angle.cache_hash(state),
Self::GradientRamp(ramp) => ramp.cache_hash(state),
Self::Strokes(strokes) => strokes.cache_hash(state),
Self::BrushCache(cache) => cache.cache_hash(state),
@@ -189,6 +197,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => Box::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Box::new(Item::new_from_element(BoxCorners::from(values))),
Self::TransferCurve(points) => Box::new(Item::new_from_element(TransferCurve::from(points))),
Self::Length(length) => Box::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
Self::Angle(angle) => Box::new(Item::new_from_element(angle.to_angle())),
Self::GradientRamp(ramp) => Box::new(Item::<Gradient>::from(ramp)),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -249,6 +259,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => Arc::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Arc::new(Item::new_from_element(BoxCorners::from(values))),
Self::TransferCurve(points) => Arc::new(Item::new_from_element(TransferCurve::from(points))),
Self::Length(length) => Arc::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
Self::Angle(angle) => Arc::new(Item::new_from_element(angle.to_angle())),
Self::GradientRamp(ramp) => Arc::new(Item::<Gradient>::from(ramp)),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -284,6 +296,8 @@ macro_rules! tagged_value {
Self::DashPattern(_) => item!(DashPattern),
Self::BoxCorners(_) => item!(BoxCorners),
Self::TransferCurve(_) => item!(TransferCurve),
Self::Length(_) => item!(Length),
Self::Angle(_) => item!(Angle),
Self::GradientRamp(_) => item!(Gradient),
Self::Strokes(_) => list!(Stroke),
Self::BrushCache(_) => item!(BrushCache),
@@ -325,6 +339,10 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast::<Item<BoxCorners>>().unwrap().into_element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast::<TransferCurve>().unwrap().points().to_vec())),
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast::<Item<TransferCurve>>().unwrap().into_element().points().to_vec())),
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Length>().unwrap().pixels()))),
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Item<Length>>().unwrap().into_element().pixels()))),
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Angle>().unwrap().degrees()))),
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Item<Angle>>().unwrap().into_element().degrees()))),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*input.downcast::<Gradient>().unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*input.downcast::<Item<Gradient>>().unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast::<List<Stroke>>().unwrap().into_iter().map(Item::into_element).collect())),
@@ -361,6 +379,10 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<Item<BoxCorners>>().unwrap().element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<TransferCurve>().unwrap().points().to_vec())),
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<Item<TransferCurve>>().unwrap().element().points().to_vec())),
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Length>().unwrap().pixels()))),
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Item<Length>>().unwrap().element().pixels()))),
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Angle>().unwrap().degrees()))),
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Item<Angle>>().unwrap().element().degrees()))),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Gradient>().unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Item<Gradient>>().unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast_ref::<List<Stroke>>().unwrap().iter_element_values().cloned().collect())),
@@ -392,6 +414,8 @@ macro_rules! tagged_value {
if name == std::any::type_name::<DashPattern>() { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == std::any::type_name::<BoxCorners>() { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == std::any::type_name::<TransferCurve>() { return Some(TaggedValue::TransferCurve(TransferCurve::default().points().to_vec())) }
if name == std::any::type_name::<Length>() { return Some(TaggedValue::Length(TypedLength::default())) }
if name == std::any::type_name::<Angle>() { return Some(TaggedValue::Angle(TypedAngle::default())) }
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
if name == std::any::type_name::<List<Stroke>>() { return Some(TaggedValue::Strokes(Vec::new())) }
if name == std::any::type_name::<BrushCache>() { return Some(TaggedValue::BrushCache(Default::default())) }
@@ -442,6 +466,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => format!("DashPattern({lengths:?})"),
Self::BoxCorners(values) => format!("BoxCorners({values:?})"),
Self::TransferCurve(points) => format!("TransferCurve({points:?})"),
Self::Length(length) => format!("Length({} {})", length.value, length.unit.symbol()),
Self::Angle(angle) => format!("Angle({} {})", angle.value, angle.unit.symbol()),
Self::GradientRamp(ramp) => format!("GradientRamp({ramp:?})"),
Self::Strokes(strokes) => format!("Strokes({strokes:?})"),
Self::BrushCache(cache) => format!("{cache:?}"),
@@ -574,6 +600,8 @@ tagged_value! {
TextAlign(text_nodes::TextAlign),
TextDenomination(text_nodes::TextDenomination),
ScaleType(core_types::transform::ScaleType),
LengthUnit(LengthUnit),
AngleUnit(AngleUnit),
// Legacy
PaintOrder(vector::style::PaintOrder), // TODO: Eventually remove this document upgrade code
#[serde(alias = "Fill")]
@@ -583,6 +611,48 @@ tagged_value! {
}
impl TaggedValue {
/// A length input's value in pixels, whether stored as a typed length or as a plain number of pixels.
pub fn as_length_pixels(&self, pixels_per_inch: f64) -> Option<f64> {
match self {
Self::Length(length) => Some(length.to_length(pixels_per_inch).pixels()),
Self::Number(pixels) => Some(*pixels),
_ => None,
}
}
/// A length in pixels as a value for a length input, kept in the unit `self` was typed in, like a dragged radius that stays in millimeters.
pub fn length_in_same_unit(&self, pixels: f64, pixels_per_inch: f64) -> Self {
let unit = match self {
Self::Length(length) => length.unit,
_ => LengthUnit::Pixel,
};
Self::Length(TypedLength {
value: LengthUnit::Pixel.convert(pixels, unit, pixels_per_inch),
unit,
})
}
/// An angle input's value in degrees, whether stored as a typed angle or as a plain number of degrees.
pub fn as_angle_degrees(&self) -> Option<f64> {
match self {
Self::Angle(angle) => Some(angle.to_angle().degrees()),
Self::Number(degrees) => Some(*degrees),
_ => None,
}
}
/// An angle in degrees as a value for an angle input, kept in the unit `self` was typed in.
pub fn angle_in_same_unit(&self, degrees: f64) -> Self {
let unit = match self {
Self::Angle(angle) => angle.unit,
_ => AngleUnit::Degree,
};
Self::Angle(TypedAngle {
value: unit.from_angle(Angle::from_degrees(degrees)),
unit,
})
}
pub fn to_primitive_string(&self) -> String {
match self {
TaggedValue::None => "()".to_string(),
@@ -758,6 +828,8 @@ impl TaggedValue {
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<Length>() => to_number(string).map(|pixels| TaggedValue::Length(TypedLength::pixels(pixels)))?,
() if ty == TypeId::of::<Angle>() => to_number(string).map(|degrees| TaggedValue::Angle(TypedAngle::degrees(degrees)))?,
_ => {
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
return None;
+1 -1
View File
@@ -1120,7 +1120,7 @@ mod test {
// If this assert fails: These NodeIds seem to be changing when you modify TaggedValue, just update them.
assert_eq!(
ids,
vec![NodeId(7074930193456627328), NodeId(651950451264872860), NodeId(15983493604836528424), NodeId(2458326405488235061)]
vec![NodeId(7958315323958235311), NodeId(7951824047151403135), NodeId(16894780098949252642), NodeId(8854475046694858618)]
);
}
+1 -1
View File
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
write_layer_paths(&mut network, layers);
let mut network = wrap_network_in_scope(network, editor_api, runtime);
let mut network = wrap_network_in_scope(network, editor_api, runtime, graphene_std::units::DEFAULT_PIXELS_PER_INCH);
let preprocessor = preprocessor::Preprocessor::new();
let preprocessed = match gdd {
@@ -13,7 +13,12 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
.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)).handle());
let mut network = wrap_network_in_scope(
network,
editor_api,
AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle(),
graphene_std::units::DEFAULT_PIXELS_PER_INCH,
);
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
@@ -70,7 +70,7 @@ impl 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());
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle(), graphene_std::units::DEFAULT_PIXELS_PER_INCH);
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.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
@@ -231,7 +231,7 @@ fn generator_frames_over_a_list_parameter() {
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Length>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
@@ -415,7 +415,7 @@ fn as_graphic_converts_a_vector_list_element_wise() {
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Length>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
@@ -21,6 +21,7 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
@@ -320,6 +321,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
RowsOrColumns,
Resource,
AnimationCurve,
Length,
Angle,
LengthUnit,
AngleUnit,
)
};
}
@@ -371,6 +376,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
String,
DVec2,
DAffine2,
Length,
Angle,
BlendMode,
GradientForm,
GradientSpread,
@@ -483,6 +490,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Numeric wires cast between numeric element types, splat to fill both axes of a `DVec2` connector, and format into a `String` connector
node_types.extend(convert_adapter_wildcard!(from: f64, to: [i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: i64, to: [f64, DVec2, String]));
// A number wire may feed a length or angle connector, read in pixels or degrees as their fields show them
node_types.extend(convert_adapter_wildcard!(from: f64, to: [Length, Angle]));
node_types.extend(convert_adapter_wildcard!(from: i64, to: [Length, Angle]));
// Length and angle wires may feed a ranked String connector by formatting each element with its unit
node_types.extend(convert_adapter_node!(from_element: Length, element: String));
node_types.extend(convert_adapter_node!(from_element: Angle, element: String));
// A bool embeds in number types as exactly 0 or 1 and formats as text as true or false, but deliberately has no `DVec2` row, which would silently turn a stray bool wire into (1., 1.)
node_types.extend(convert_adapter_wildcard!(from: bool, to: [f64, i64, String]));
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
+9 -1
View File
@@ -9,7 +9,9 @@ use graphene_std::RuntimeHandle;
use graphene_std::uuid::NodeId;
use std::sync::Arc;
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
/// Wraps the document network in the scope the runtime supplies: the editor API, the async runtime, and the pixels per inch that
/// sizes lengths typed in a physical unit.
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle, pixels_per_inch: f64) -> NodeNetwork {
let definitions = std::mem::take(&mut network.definitions);
let inner_network = DocumentNode {
@@ -128,10 +130,16 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
inputs: vec![NodeInput::value(TaggedValue::Runtime(runtime), false)],
..Default::default()
},
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(pixels_per_inch), false)],
..Default::default()
},
];
let scope_injections = vec![
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
(graphene_std::units::PIXELS_PER_INCH_SCOPE.to_string(), (NodeId(4), item!(f64))),
];
NodeNetwork {
@@ -24,6 +24,7 @@ wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
graphene-hash = { workspace = true, features = ["derive"] }
math-parser = { workspace = true }
# Workspace dependencies
color = { workspace = true }
@@ -19,6 +19,7 @@ pub mod registry;
pub mod runtime;
pub mod transfer_curve;
pub mod transform;
pub mod units;
pub mod uuid;
pub mod value;
@@ -203,6 +203,7 @@ pub const CATEGORY_ORDER: &[&str] = &[
"Math: Numeric",
"Math: Trig",
"Math: Vec2",
"Math: Units",
"Data: List",
"Data: Context",
"Data: Animation",
@@ -0,0 +1,465 @@
//! Lengths and angles as the node graph carries them, and the units an input remembers its value was typed in.
use dyn_any::DynAny;
use math_parser::quantity::Quantity;
use math_parser::units::Unit;
use math_parser::value::Value;
use std::iter::Sum;
use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
/// The pixels per inch of a document that sets none of its own, CSS's reference pixel, which every SVG reader also assumes.
pub const DEFAULT_PIXELS_PER_INCH: f64 = math_parser::units::DEFAULT_PIXELS_PER_INCH;
/// The scope key under which the graph's runtime injects the document's pixels per inch.
pub const PIXELS_PER_INCH_SCOPE: &str = "pixels-per-inch";
/// A distance across the canvas, measured in pixels: the one type a length travels the node graph as, whatever unit it was typed in.
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
pub struct Length(f64);
impl Length {
pub const ZERO: Self = Self(0.);
pub const fn from_pixels(pixels: f64) -> Self {
Self(pixels)
}
pub const fn pixels(self) -> f64 {
self.0
}
pub fn abs(self) -> Self {
Self(self.0.abs())
}
pub fn min(self, other: Self) -> Self {
Self(self.0.min(other.0))
}
pub fn max(self, other: Self) -> Self {
Self(self.0.max(other.0))
}
}
/// An angle, which node bodies read in radians or degrees as their math needs.
/// It's held in degrees, so sums and comparisons of whole degrees stay exact.
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
pub struct Angle(f64);
impl Angle {
pub const ZERO: Self = Self(0.);
pub const fn from_radians(radians: f64) -> Self {
Self(radians.to_degrees())
}
pub const fn from_degrees(degrees: f64) -> Self {
Self(degrees)
}
pub const fn radians(self) -> f64 {
self.0.to_radians()
}
pub const fn degrees(self) -> f64 {
self.0
}
pub fn abs(self) -> Self {
Self(self.0.abs())
}
pub fn min(self, other: Self) -> Self {
Self(self.0.min(other.0))
}
pub fn max(self, other: Self) -> Self {
Self(self.0.max(other.0))
}
}
/// Arithmetic that keeps a measurement's meaning: sums and differences of like measurements, scaling by a plain number, and the
/// plain ratio of two like measurements.
macro_rules! measurement_arithmetic {
($($measurement:ident),*) => {
$(
impl Add for $measurement {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
impl Sub for $measurement {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self(self.0 - other.0)
}
}
impl AddAssign for $measurement {
fn add_assign(&mut self, other: Self) {
self.0 += other.0;
}
}
impl SubAssign for $measurement {
fn sub_assign(&mut self, other: Self) {
self.0 -= other.0;
}
}
impl Neg for $measurement {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Mul<f64> for $measurement {
type Output = Self;
fn mul(self, factor: f64) -> Self {
Self(self.0 * factor)
}
}
impl Mul<$measurement> for f64 {
type Output = $measurement;
fn mul(self, measurement: $measurement) -> $measurement {
$measurement(self * measurement.0)
}
}
impl Div<f64> for $measurement {
type Output = Self;
fn div(self, divisor: f64) -> Self {
Self(self.0 / divisor)
}
}
impl Div for $measurement {
type Output = f64;
fn div(self, divisor: Self) -> f64 {
self.0 / divisor.0
}
}
impl Sum for $measurement {
fn sum<I: Iterator<Item = Self>>(iterator: I) -> Self {
Self(iterator.map(|measurement| measurement.0).sum())
}
}
)*
};
}
measurement_arithmetic!(Length, Angle);
impl std::fmt::Display for Length {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} px", self.0)
}
}
impl std::fmt::Display for Angle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}°", self.degrees())
}
}
/// A unit a length can be typed in.
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Dropdown)]
pub enum LengthUnit {
/// A pixel of the canvas, which the document's resolution sizes against an inch.
#[default]
Pixel,
/// A typographic point, 1/72 of an inch.
Point,
/// A typographic pica, 12 points or 1/6 of an inch.
Pica,
/// An inch, 25.4 millimeters.
Inch,
/// A foot, 12 inches.
Foot,
/// A yard, 3 feet.
Yard,
/// A mile, 5280 feet.
Mile,
/// A thou, 1/1000 of an inch.
Thou,
/// A micrometer, 1/1000 of a millimeter.
Micrometer,
/// A millimeter.
Millimeter,
/// A centimeter, 10 millimeters.
Centimeter,
/// A meter, 100 centimeters.
Meter,
/// A kilometer, 1000 meters.
Kilometer,
}
impl LengthUnit {
pub const ALL: [Self; 13] = [
Self::Pixel,
Self::Point,
Self::Pica,
Self::Inch,
Self::Foot,
Self::Yard,
Self::Mile,
Self::Thou,
Self::Micrometer,
Self::Millimeter,
Self::Centimeter,
Self::Meter,
Self::Kilometer,
];
/// The unit's symbol as the expression language spells it, like `mm`.
pub fn symbol(self) -> &'static str {
match self {
Self::Pixel => "px",
Self::Point => "pt",
Self::Pica => "pc",
Self::Inch => "in",
Self::Foot => "ft",
Self::Yard => "yd",
Self::Mile => "mi",
Self::Thou => "thou",
Self::Micrometer => "µm",
Self::Millimeter => "mm",
Self::Centimeter => "cm",
Self::Meter => "m",
Self::Kilometer => "km",
}
}
/// The unit a math expression's unit is, if it is one of these.
pub fn from_unit(unit: Unit) -> Option<Self> {
Self::ALL.into_iter().find(|candidate| candidate.unit() == unit)
}
/// The expression language's unit of the same size.
pub fn unit(self) -> Unit {
Unit::named(self.symbol()).unwrap_or(Unit::NONE)
}
/// Whether the unit is a physical size, which converts to pixels by the document's resolution.
pub fn is_physical(self) -> bool {
self != Self::Pixel
}
/// Converts a number in this unit into another, exactly where the ratio between them allows.
pub fn convert(self, value: f64, into: Self, pixels_per_inch: f64) -> f64 {
if self == into {
return value;
}
Quantity::new(Value::from_f64(value), self.unit())
.convert(into.unit(), pixels_per_inch)
.ok()
.and_then(|converted| converted.as_real())
.unwrap_or(value)
}
}
/// A unit an angle can be typed in.
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Dropdown)]
pub enum AngleUnit {
/// A degree, 1/360 of a turn.
#[default]
Degree,
/// A radian, the angle of an arc as long as its radius, 1/(2π) of a turn.
Radian,
/// A whole turn around the circle.
Turn,
}
impl AngleUnit {
pub const ALL: [Self; 3] = [Self::Degree, Self::Radian, Self::Turn];
/// The unit's symbol as the expression language spells it, like `°`.
pub fn symbol(self) -> &'static str {
match self {
Self::Degree => "°",
Self::Radian => "rad",
Self::Turn => "turn",
}
}
pub fn from_unit(unit: Unit) -> Option<Self> {
Self::ALL.into_iter().find(|candidate| candidate.unit() == unit)
}
pub fn unit(self) -> Unit {
Unit::named(self.symbol()).unwrap_or(Unit::NONE)
}
pub fn to_angle(self, value: f64) -> Angle {
match self {
Self::Degree => Angle::from_degrees(value),
Self::Radian => Angle::from_radians(value),
Self::Turn => Angle::from_degrees(value * 360.),
}
}
pub fn from_angle(self, angle: Angle) -> f64 {
match self {
Self::Degree => angle.degrees(),
Self::Radian => angle.radians(),
Self::Turn => angle.degrees() / 360.,
}
}
}
/// A length as typed into an input, kept in its unit so a physical size stays physical when the document's resolution changes.
#[derive(Clone, Copy, Debug, Default, PartialEq, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TypedLength {
pub value: f64,
pub unit: LengthUnit,
}
impl TypedLength {
pub const fn pixels(pixels: f64) -> Self {
Self {
value: pixels,
unit: LengthUnit::Pixel,
}
}
pub fn to_length(self, pixels_per_inch: f64) -> Length {
Length::from_pixels(self.unit.convert(self.value, LengthUnit::Pixel, pixels_per_inch))
}
}
/// An angle as typed into an input, kept in its unit for display.
#[derive(Clone, Copy, Debug, Default, PartialEq, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TypedAngle {
pub value: f64,
pub unit: AngleUnit,
}
impl TypedAngle {
pub const fn degrees(degrees: f64) -> Self {
Self {
value: degrees,
unit: AngleUnit::Degree,
}
}
pub fn to_angle(self) -> Angle {
self.unit.to_angle(self.value)
}
}
// A plain number wired into a length or angle reads in the unit its field shows, pixels or degrees
impl crate::ops::Convert<Length, ()> for f64 {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Length {
Length::from_pixels(self)
}
}
impl crate::ops::Convert<Length, ()> for i64 {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Length {
Length::from_pixels(self as f64)
}
}
impl crate::ops::Convert<Angle, ()> for f64 {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Angle {
Angle::from_degrees(self)
}
}
impl crate::ops::Convert<Angle, ()> for i64 {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Angle {
Angle::from_degrees(self as f64)
}
}
impl crate::ops::Convert<String, ()> for Length {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> String {
format!("{} px", crate::math::float_noise::round_away_float_noise(self.pixels()))
}
}
impl crate::ops::Convert<String, ()> for Angle {
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> String {
format!("{}°", crate::math::float_noise::round_away_float_noise(self.degrees()))
}
}
// A length's bounds are in pixels and an angle's in degrees, the units their fields show
impl crate::misc::Clampable for Length {
fn clamp_hard_min(self, min: f64) -> Self {
Self(self.0.max(min))
}
fn clamp_hard_max(self, max: f64) -> Self {
Self(self.0.min(max))
}
}
impl crate::misc::Clampable for Angle {
fn clamp_hard_min(self, min: f64) -> Self {
Self(self.0.max(min))
}
fn clamp_hard_max(self, max: f64) -> Self {
Self(self.0.min(max))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_unit_is_one_of_the_expression_language() {
for unit in LengthUnit::ALL {
assert_eq!(LengthUnit::from_unit(unit.unit()), Some(unit), "`{}`", unit.symbol());
assert_eq!(unit.unit().dimension(), math_parser::units::Dimension::LENGTH);
}
for unit in AngleUnit::ALL {
assert_eq!(AngleUnit::from_unit(unit.unit()), Some(unit), "`{}`", unit.symbol());
}
}
#[test]
fn typed_lengths_convert_to_pixels_by_the_resolution() {
assert_eq!(TypedLength { value: 1., unit: LengthUnit::Inch }.to_length(96.), Length::from_pixels(96.));
assert_eq!(TypedLength { value: 1., unit: LengthUnit::Inch }.to_length(300.), Length::from_pixels(300.));
assert_eq!(TypedLength { value: 72., unit: LengthUnit::Point }.to_length(96.), Length::from_pixels(96.));
assert_eq!(TypedLength::pixels(12.).to_length(300.), Length::from_pixels(12.));
let millimeters = TypedLength {
value: 25.4,
unit: LengthUnit::Millimeter,
}
.to_length(96.)
.pixels();
assert!((millimeters - 96.).abs() < 1e-9);
}
#[test]
fn angles_read_in_any_unit() {
assert!((TypedAngle::degrees(90.).to_angle().radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
assert!((AngleUnit::Turn.to_angle(0.25).degrees() - 90.).abs() < 1e-12);
assert!((AngleUnit::Turn.from_angle(Angle::from_degrees(180.)) - 0.5).abs() < 1e-12);
}
// Arithmetic on whole degrees compares equal to the degrees it should give
#[test]
fn whole_degrees_stay_exact_through_arithmetic() {
assert_eq!(Angle::from_degrees(1.) + Angle::from_degrees(5.), Angle::from_degrees(6.));
assert_eq!(AngleUnit::Turn.to_angle(0.25), Angle::from_degrees(90.));
}
}
+2
View File
@@ -20,6 +20,8 @@ use rand::{RngExt, SeedableRng};
use std::sync::{Arc, Mutex, PoisonError};
use vector_types::Gradient;
pub mod units;
/// Why a math node's expression or operator gives no result.
#[derive(Debug, thiserror::Error)]
pub enum MathExpressionError {
+81
View File
@@ -0,0 +1,81 @@
//! Nodes converting between plain numbers and the lengths and angles the graph carries, sizing physical units by the document's resolution.
use core_types::Ctx;
use core_types::list::Item;
use core_types::units::{Angle, AngleUnit, Length, LengthUnit};
/// Constructs a length, typed in pixels or a physical unit like millimeters or inches, which the document's resolution sizes in pixels.
#[node_macro::node(category("Value"))]
fn length_value(_: impl Ctx, _primary: (), length: Item<Length>) -> Item<Length> {
length
}
/// Constructs an angle, typed in degrees, radians, or turns.
#[node_macro::node(category("Value"))]
fn angle_value(_: impl Ctx, _primary: (), angle: Item<Angle>) -> Item<Angle> {
angle
}
/// Converts a number into a length, reading it in the chosen unit.
///
/// A physical unit like millimeters is sized in pixels by the document's resolution.
#[node_macro::node(category("Math: Units"))]
fn number_to_length(
_: impl Ctx,
/// The number to read as a length.
number: Item<f64>,
/// The unit the number is in.
unit: Item<LengthUnit>,
#[scope("pixels-per-inch")] pixels_per_inch: Item<f64>,
) -> Item<Length> {
let (number, attributes) = number.into_parts();
let pixels = unit.element().convert(number, LengthUnit::Pixel, *pixels_per_inch.element());
Item::from_parts(Length::from_pixels(pixels), attributes)
}
/// Converts a length into a number, measuring it in the chosen unit.
///
/// A physical unit like millimeters is sized in pixels by the document's resolution.
#[node_macro::node(category("Math: Units"))]
fn length_to_number(
_: impl Ctx,
/// The length to measure.
length: Item<Length>,
/// The unit to measure the length in.
unit: Item<LengthUnit>,
#[scope("pixels-per-inch")] pixels_per_inch: Item<f64>,
) -> Item<f64> {
let (length, attributes) = length.into_parts();
let number = LengthUnit::Pixel.convert(length.pixels(), *unit.element(), *pixels_per_inch.element());
Item::from_parts(number, attributes)
}
/// Converts a number into an angle, reading it in the chosen unit.
#[node_macro::node(category("Math: Units"))]
fn number_to_angle(
_: impl Ctx,
/// The number to read as an angle.
number: Item<f64>,
/// The unit the number is in.
unit: Item<AngleUnit>,
) -> Item<Angle> {
let (number, attributes) = number.into_parts();
Item::from_parts(unit.element().to_angle(number), attributes)
}
/// Converts an angle into a number, measuring it in the chosen unit.
#[node_macro::node(category("Math: Units"))]
fn angle_to_number(
_: impl Ctx,
/// The angle to measure.
angle: Item<Angle>,
/// The unit to measure the angle in.
unit: Item<AngleUnit>,
) -> Item<f64> {
let (angle, attributes) = angle.into_parts();
Item::from_parts(unit.element().from_angle(angle), attributes)
}
@@ -1,5 +1,6 @@
use crate::grid_topology::Lattice;
use core_types::list::{Item, List};
use core_types::units::Length;
use core_types::{CacheHash, Ctx};
use dyn_any::DynAny;
use glam::DVec2;
@@ -10,15 +11,9 @@ use vector_types::vector::misc::SpiralType;
use vector_types::vector::misc::{ArcType, BoxCorners, GridTopology, GridType};
/// Generates a circle shape with a chosen radius.
#[node_macro::node(category("Vector: Geometry"), icon("NodeCircle"))]
fn circle(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(50.)]
radius: Item<f64>,
) -> Item<Vector> {
let radius = radius.element().abs();
#[node_macro::node(category("Vector: Geometry"), icon("NodeCircle"), version(2))]
fn circle(_: impl Ctx, _primary: (), #[default(50.)] radius: Item<Length>) -> Item<Vector> {
let radius = radius.element().pixels().abs();
Vector::item_from_bezpath(&shapes::ellipse_bezpath(DVec2::splat(-radius), DVec2::splat(radius)))
}
+15
View File
@@ -123,6 +123,21 @@ impl Preprocessor {
id
})
}
// A length typed in a physical unit is sized in pixels by the resolution the document's scope supplies
TaggedValue::Length(length) if length.unit.is_physical() => {
let id = producer_node_id(&graphene_std::math_nodes::units::number_to_length::IDENTIFIER, (consumer_id, input_index));
let conversion = DocumentNode {
inputs: vec![
NodeInput::value(TaggedValue::Number(length.value), false),
NodeInput::value(TaggedValue::LengthUnit(length.unit), false),
NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::units::number_to_length::IDENTIFIER),
..Default::default()
};
new_nodes.push((id, conversion));
id
}
TaggedValue::AnimationCurve(curve) => {
let id = producer_node_id(&graphene_core::animation::evaluate_curve::IDENTIFIER, (consumer_id, input_index));
let curve_node = DocumentNode {
@@ -81,12 +81,14 @@ impl Preprocessor {
(NodeId(0), content),
(NodeId(1), scope_stand_in(item!(Arc<PlatformEditorApi>))),
(NodeId(2), scope_stand_in(item!(RuntimeHandle))),
(NodeId(3), scope_stand_in(item!(f64))),
]
.into_iter()
.collect(),
scope_injections: [
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
(graphene_std::units::PIXELS_PER_INCH_SCOPE.to_string(), (NodeId(3), item!(f64))),
]
.into_iter()
.collect(),
+1
View File
@@ -31,6 +31,7 @@ pub fn category_description(category: &str) -> &str {
"Math: Numeric" => "Nodes in this category perform numeric operations such as rounding, clamping, finding minimums and maximums, remapping between ranges, and interpolating.",
"Math: Trig" => "Nodes in this category perform trigonometric operations such as sine, cosine, tangent, and their inverses.",
"Math: Vec2" => "Nodes in this category perform operations involving `vec2` values (points or arrows in 2D space) such as the dot product, normalization, and distance calculations.",
"Math: Units" => "Nodes in this category convert between plain numbers and lengths or angles measured in a chosen unit, such as millimeters, inches, or degrees.",
"Data: List" => "Nodes in this category build, reorder, filter, and pick from lists of items, and loop over them to transform each one.",
"Data: Context" => "Nodes in this category read data from the evaluation context supplied by downstream nodes, such as the current loop iteration index.",
"Data: Animation" => indoc!(