effects-w14: net change of 2 commits

- effects-w14: written from its sheet
- effects-w14: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:33:04 +07:00
parent 34e447b3af
commit f38d6acaf3
2 changed files with 771 additions and 522 deletions
+608 -272
View File
@@ -1,58 +1,105 @@
//! Artboard rotation and light controls for the active 3D effect dialog (Extrude & Bevel, Revolve,
//! Inflate, Rotate and the classic 3D effects). Gestures edit fields;
//! the existing effect preview applies commands and owns OK, Cancel and undo.
use egui::{Align2, FontId, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2};
//! Artboard rotation and light controls for the open 3D effect dialog (Extrude & Bevel, Revolve, Inflate, Rotate and
//! the classic 3D effects). [`RevolveGizmo`] is a canvas control over the rotation and light values: a drag is one edit
//! gesture whose values [`show`] writes into the dialog's fields, and the dialog's preview applies them, owns OK,
//! Cancel and undo. Escape during a drag is the gesture's cancel: the values go back to where the press found them.
//!
//! - Rotation page: three rings (X, Y, Z) turn one axis each, a press at the centre or anywhere else in the gizmo's
//! square turns X and Y together. Shift snaps to 15 degrees.
//! - Lighting page: the light's handle, its two rings and their labels move the selected light; Shift snaps to 15
//! degrees. Nothing shows with Preview off or while the lighting page has no light to move ([`lit`]).
//! - A press that never drags changes nothing: the gesture begins at the first drag.
use craft::behavior::{
CancelReason, CanvasView, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Metrics, PartKey, PartRef, PointerButton, PressPhase, Sense,
};
// PLAN: the `craft` facade crate needs to be a dependency in crates/ui-egui/Cargo.toml (owner: hub-w1/hub-w2).
use craft_ui::canvas::{CanvasSpace, canvas_space};
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _,
Role, Show as _,
};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog};
use craft_ui::runtime::focus::KeyUse;
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx};
use egui::{Align2, FontId, Painter, Pos2, Rect, Response, Stroke, Ui, Vec2, vec2};
use serde_json::json;
use vectorcraft_effects::{CLASSIC_REVOLVE, REVOLVE};
use vectorcraft_geom::Point;
use vectorcraft_three_d::Revolve;
use crate::{VectorcraftApp, canvas::Xf, state::Dialog, theme::Tokens};
use super::revolve::{light_options, set_light_value};
use super::three_d;
use crate::VectorcraftApp;
const KEYS: [&str; 3] = ["rotationX", "rotationY", "rotationZ"];
const SAMPLES: usize = 96;
/// How far from a ring a press still takes it, in points.
const RING_REACH: f32 = 9.0;
/// How far from the centre a press turns X and Y together, in points.
const ORBIT_REACH: f32 = 14.0;
/// How far from the light's handle a press takes it, in points.
const LIGHT_REACH: f32 = 18.0;
pub(crate) fn active(d: &Dialog) -> bool {
d.kind == "effect" && vectorcraft_effects::is_three_d(&d.str("__effect"))
}
const RING: PartKey = PartKey::new("ring");
const CENTRE: PartKey = PartKey::new("centre");
const LIGHT: PartKey = PartKey::new("light");
const LIGHT_RING: PartKey = PartKey::new("lightRing");
const LIGHT_LABEL: PartKey = PartKey::new("lightLabel");
const AREA: PartKey = PartKey::new("area");
pub(crate) fn lighting(d: &Dialog) -> bool {
d.str("__gizmo") == "light"
}
/// The keyboard path of every part: the dialog's own rotation and light fields.
const BY_FIELDS: &str = "the rotation and light fields of the dialog";
/// Does the effect take light: Shading on, or for the classic 3D effects a Diffuse or Plastic
/// surface?
fn lit(d: &Dialog) -> bool {
let id = d.str("__effect");
if vectorcraft_effects::is_classic_three_d(&id) { matches!(d.str("surface").as_str(), "diffuse" | "plastic") } else { d.bool("shade") }
}
pub(crate) fn hint(d: &Dialog) -> &'static str {
if !d.bool("preview") || (lighting(d) && !lit(d)) {
tl!("Drag values or labels. Double-click a value to type.")
} else if lighting(d) {
tl!("Drag the light, or its rings. Shift snaps to 15°.")
/// Does the effect take light: Shading on, or for the classic 3D effects a Diffuse or Plastic surface?
pub(crate) fn lit(fields: &DialogFields) -> bool {
// PLAN: assumes the dialog's fields keep `__effect` (ef.C13 lists only `__page` and `__light`).
let id = fields.text("__effect").unwrap_or_default();
if vectorcraft_effects::is_classic_three_d(id) {
matches!(fields.text("surface"), Some("diffuse" | "plastic"))
} else {
tl!("Drag rings to rotate. Shift snaps to 15°.")
fields.bool("shade").unwrap_or(false)
}
}
/// Temp-memory key for the revolve gizmo drag state.
fn drag_id() -> Id {
Id::unique("revolve-gizmo-drag")
/// Is the dialog on its Lighting page?
fn lighting(fields: &DialogFields) -> bool {
fields.text("__page") == Some("lighting")
}
/// Is a rotation or light gesture in progress, on the artboard or on the classic 3D effects' track
/// cube?
pub(crate) fn dragging(ctx: &egui::Context) -> bool {
ctx.data(|m| m.get_temp::<Drag>(drag_id())).is_some() || super::three_d_classic::cube_dragging(ctx)
/// Does the gizmo show for these values: Preview on, and on the Lighting page only while the effect takes light.
fn shown(fields: &DialogFields) -> bool {
fields.bool("preview").unwrap_or(false) && (!lighting(fields) || lit(fields))
}
pub(super) fn clear(ctx: &egui::Context) {
ctx.data_mut(|m| m.remove::<Drag>(drag_id()));
/// The values the gizmo edits: the three rotations and the selected light's rotation and height, in degrees.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct GizmoValues {
/// The rotations about X, Y and Z, in [`KEYS`] order.
pub rotation: [f64; 3],
/// The selected light's rotation.
pub light_rotation: f64,
/// The selected light's height.
pub light_height: f64,
}
#[derive(Clone, Copy)]
impl GizmoValues {
/// The values the dialog holds; a missing rotation reads 0.
fn of(fields: &DialogFields) -> Self {
let options = light_options(fields);
GizmoValues {
rotation: KEYS.map(|key| fields.number(key).unwrap_or(0.0)),
light_rotation: options.light_rotation,
light_height: options.light_height,
}
}
}
/// What the gizmo works on: the dialog's values and the bounds of the art it turns.
struct Subject {
fields: DialogFields,
bounds: vectorcraft_geom::Rect,
}
#[derive(Clone, Copy, Debug, Default)]
struct Ring {
center: Vec2,
u: Vec2,
@@ -80,43 +127,44 @@ impl Ring {
}
}
#[derive(Clone, Copy)]
/// The sine and cosine of the view's turn: document directions on screen.
fn turn(view: &CanvasView) -> (f32, f32) {
(view.rotation.to_radians() as f32).sin_cos()
}
#[derive(Clone, Copy, Debug, Default)]
struct Geometry {
center: Pos2,
radius: f32,
rings: [Ring; 3],
xf: Xf,
bounds: vectorcraft_geom::Rect,
turn: (f32, f32),
}
impl Geometry {
fn new(app: &VectorcraftApp, d: &Dialog) -> Option<Self> {
let state = app.session.active()?;
let node = state.doc.node(*state.selection.objects.first()?)?;
let bounds = node.geometric_bounds()?;
let xf = app.canvas_xf()?;
let options = super::revolve::light_options(d);
/// The gizmo of the art in `bounds` under `view`; `None` when its centre is off the canvas.
fn new(view: &CanvasView, fields: &DialogFields, bounds: vectorcraft_geom::Rect) -> Option<Self> {
let options = light_options(fields);
// Both Revolves turn about their axis; the others about the centre of the art's bounds.
let id = d.str("__effect");
let id = fields.text("__effect").unwrap_or_default();
let origin = if id == REVOLVE || id == CLASSIC_REVOLVE { options.rotation_origin(bounds) } else { bounds.center() };
let center = xf.to_screen(origin);
if !center.x.is_finite() || !center.y.is_finite() || !xf.rect.contains(center) {
let center = view.to_screen(origin);
if !center.x.is_finite() || !center.y.is_finite() || !view.rect.contains(center) {
return None;
}
let radius = (bounds.height().abs() * xf.zoom * 0.24).clamp(76.0, 116.0) as f32;
let (s, c) = (xf.rot as f32).sin_cos();
let radius = (bounds.height().abs() * view.zoom * 0.24).clamp(76.0, 116.0) as f32;
let (s, c) = turn(view);
let screen = |p: [f64; 3], scale: f32| vec2(c * p[0] as f32 - s * p[1] as f32, s * p[0] as f32 + c * p[1] as f32) * radius * scale;
let rings = std::array::from_fn(|i| {
let [u, v] = options.rotation_planes()[i];
let scale = if i == 2 { 1.12 } else { 1.0 };
Ring { center: Vec2::ZERO, u: screen(u, scale), v: screen(v, scale), depth: [u[2] as f32, v[2] as f32] }
});
Some(Self { center, radius, rings, xf, bounds })
Some(Self { center, radius, rings, turn: (s, c) })
}
fn hit(self, p: Pos2) -> Option<(usize, f32)> {
let mut best = None;
let mut distance = 9.0;
let mut distance = RING_REACH;
for (axis, ring) in self.rings.iter().enumerate() {
for i in 0..SAMPLES {
let a = i as f32 * std::f32::consts::TAU / SAMPLES as f32;
@@ -135,7 +183,7 @@ impl Geometry {
}
fn light_rings(self, options: Revolve) -> [Ring; 2] {
let (s, c) = (self.xf.rot as f32).sin_cos();
let (s, c) = self.turn;
let screen = |p: [f64; 3]| vec2(c * p[0] as f32 - s * p[1] as f32, s * p[0] as f32 + c * p[1] as f32) * self.radius * 1.4;
options.light_orbits().map(|[center, u, v]| Ring { center: screen(center), u: screen(u), v: screen(v), depth: [u[2] as f32, v[2] as f32] })
}
@@ -152,11 +200,11 @@ impl Geometry {
return Some(axis);
}
let mut best = None;
let mut distance = 9.0;
let mut distance = RING_REACH;
for (axis, ring) in self.light_rings(options).iter().enumerate() {
let (start, span) = if axis == 0 { (0.0, std::f32::consts::TAU) } else { (0.0, std::f32::consts::FRAC_PI_2) };
let span = light_span(axis);
for i in 0..SAMPLES {
let a = start + i as f32 * span / SAMPLES as f32;
let a = i as f32 * span / SAMPLES as f32;
let (from, to) = (self.center + ring.point(a), self.center + ring.point(a + span / SAMPLES as f32));
let line = to - from;
let t = ((p - from).dot(line) / line.length_sq().max(1e-6)).clamp(0.0, 1.0);
@@ -169,23 +217,62 @@ impl Geometry {
}
best
}
/// The points of ring `ring` over `span` radians from its start, for a hit shape.
fn arc(self, ring: Ring, span: f32) -> Vec<Pos2> {
(0..=SAMPLES).map(|i| self.center + ring.point(i as f32 * span / SAMPLES as f32)).collect()
}
/// The square the gizmo takes presses in; the light page adds its labels.
fn area(self, light_mode: bool) -> Rect {
let mut rect = Rect::from_center_size(self.center, Vec2::splat(self.radius * 3.0 + 48.0));
if light_mode {
for label in self.light_labels() {
rect = rect.union(label.expand(2.0));
}
}
rect
}
}
#[derive(Clone, Copy)]
/// The angle a light ring spans: the Rotation ring is whole, the Height ring a quarter.
fn light_span(axis: usize) -> f32 {
if axis == 0 { std::f32::consts::TAU } else { std::f32::consts::FRAC_PI_2 }
}
/// What a drag turns, fixed at the press.
#[derive(Clone, Copy, Debug, Default)]
enum Mode {
Ring { axis: usize, ring: Ring, phase: f32, degrees: f64 },
Ring {
axis: usize,
ring: Ring,
phase: f32,
degrees: f64,
},
#[default]
Orbit,
Light,
LightRing { axis: usize },
LightRing {
axis: usize,
},
}
#[derive(Clone)]
struct Drag {
/// The press the gizmo is dragging, kept from the press to its release. The ring and the geometry stay as the press
/// found them, so a ring does not slide under the pointer.
#[derive(Clone, Debug, Default)]
struct Grip {
mode: Mode,
geometry: Geometry,
last: Pos2,
/// The values at the press.
start: GizmoValues,
/// The dialog's values at the press: the light moves from the options they give.
fields: DialogFields,
origin: Pos2,
fields: serde_json::Map<String, serde_json::Value>,
/// The pointer where the last step left it: a pass that sees the same position steps by nothing.
last: Pos2,
/// The values the last step proposed.
latest: GizmoValues,
began: bool,
}
pub(super) fn wrap(n: f64, snap: bool) -> f64 {
@@ -198,247 +285,496 @@ pub(super) fn snap_height(height: f64, snap: bool) -> f64 {
(if snap { (height / 15.0).round() * 15.0 } else { height }).clamp(0.0, 90.0)
}
pub(super) fn show(app: &VectorcraftApp, ctx: &egui::Context, d: &mut Dialog) {
let light_mode = lighting(d);
if !d.bool("preview") || (light_mode && !lit(d)) {
clear(ctx);
return;
}
let Some(geometry) = Geometry::new(app, d) else { return };
let geometry = ctx.data(|m| m.get_temp::<Drag>(drag_id())).map_or(geometry, |drag| drag.geometry);
let mut rect = Rect::from_center_size(geometry.center, Vec2::splat(geometry.radius * 3.0 + 48.0));
/// What a press at `origin` turns.
fn mode_at(g: Geometry, options: Revolve, light_mode: bool, origin: Pos2) -> Mode {
if light_mode {
for label in geometry.light_labels() {
rect = rect.union(label.expand(2.0));
if origin.distance(light_position(g, options)) <= LIGHT_REACH {
Mode::Light
} else if let Some(axis) = g.light_hit(origin, options) {
Mode::LightRing { axis }
} else {
Mode::Light
}
} else if origin.distance(g.center) <= ORBIT_REACH {
Mode::Orbit
} else if let Some((axis, phase)) = g.hit(origin) {
Mode::Ring { axis, ring: g.rings[axis], phase, degrees: 0.0 }
} else {
Mode::Orbit
}
egui::Area::new(Id::unique("revolve-gizmo-area")).order(egui::Order::Foreground).fixed_pos(rect.min).movable(false).show(ctx, |ui| {
ui.set_clip_rect(geometry.xf.rect);
let response = ui.allocate_rect(rect.intersect(geometry.xf.rect), Sense::drag());
let options = super::revolve::light_options(d);
let light = light_position(geometry, options);
let hovered = response
.hovered()
.then(|| response.hover_pos())
.flatten()
.and_then(|p| if light_mode { geometry.light_hit(p, options).map(|axis| (axis, 0.0)) } else { geometry.hit(p) });
if response.drag_started()
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
{
let mode = if light_mode {
if origin.distance(light) <= 18.0 {
Mode::Light
} else if let Some(axis) = geometry.light_hit(origin, options) {
Mode::LightRing { axis }
}
impl Grip {
/// The values the pointer at `pos` gives, with Shift as `snap`; moves the ring's phase on.
fn follow(&mut self, view: &CanvasView, pos: Pos2, snap: bool) -> GizmoValues {
let g = self.geometry;
let mut next = self.start;
match &mut self.mode {
Mode::Ring { axis, ring, phase, degrees } => {
let step = if let Some(now) = ring.phase(pos - g.center) {
let step = (now - *phase + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
*phase = now;
step
} else {
Mode::Light
let tangent = ring.tangent(*phase);
let step = (pos - self.last).dot(tangent) / tangent.length_sq().max(144.0);
*phase += step;
step
};
*degrees += f64::from(step.to_degrees());
let start = self.start.rotation.get(*axis).copied().unwrap_or(0.0);
if let Some(slot) = next.rotation.get_mut(*axis) {
*slot = wrap(start + *degrees, snap);
}
} else if origin.distance(geometry.center) <= 14.0 {
Mode::Orbit
} else if let Some((axis, phase)) = geometry.hit(origin) {
Mode::Ring { axis, ring: geometry.rings[axis], phase, degrees: 0.0 }
} else {
Mode::Orbit
};
ui.ctx().memory_mut(|m| m.stop_text_input());
ui.data_mut(|m| m.insert_temp(drag_id(), Drag { mode, geometry, last: origin, origin, fields: d.fields.clone() }));
}
let mut drag = ui.data(|m| m.get_temp::<Drag>(drag_id()));
if let Some(current) = &mut drag {
if ui.input_mut(|i| i.consume_key(i.modifiers, egui::Key::Escape)) {
d.fields = current.fields.clone();
d.fields.remove(super::form::PREVIEWED);
ui.data_mut(|m| m.remove::<Drag>(drag_id()));
drag = None;
} else if let Some(p) = response.interact_pointer_pos() {
let snap = ui.input(|i| i.modifiers.shift);
match &mut current.mode {
Mode::Ring { axis, ring, phase, degrees } => {
let step = if let Some(next) = ring.phase(p - geometry.center) {
let step = (next - *phase + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
*phase = next;
step
} else {
let tangent = ring.tangent(*phase);
let step = (p - current.last).dot(tangent) / tangent.length_sq().max(144.0);
*phase += step;
step
};
*degrees += f64::from(step.to_degrees());
if let Some(key) = KEYS.get(*axis) {
let start = current.fields.get(*key).and_then(|v| v.as_f64()).unwrap_or(0.0);
d.fields.insert((*key).into(), json!(wrap(start + *degrees, snap)));
}
}
Mode::Orbit => {
let delta = geometry.xf.delta_to_doc(p - current.origin) * geometry.xf.zoom;
for (key, delta) in [("rotationX", delta.y * 0.5), ("rotationY", delta.x * 0.5)] {
let start = current.fields.get(key).and_then(|v| v.as_f64()).unwrap_or(0.0);
d.fields.insert(key.into(), json!(wrap(start + delta, snap)));
}
}
Mode::Light => {
let start = super::revolve::light_options(&Dialog::new("effect", serde_json::Value::Object(current.fields.clone())));
let projected = light_position(geometry, start) + (p - current.origin);
let point = geometry.xf.delta_to_doc(projected - geometry.center) * (geometry.xf.zoom / f64::from(geometry.radius * 1.4));
let [rotation, height] = start.light_at_on_side(Point::new(point.x, point.y));
super::revolve::set_light_value(d, "lightRotation", json!(wrap(rotation, snap)));
super::revolve::set_light_value(d, "lightHeight", json!(snap_height(height, snap)));
}
Mode::LightRing { axis } => {
let delta = geometry.xf.delta_to_doc(p - current.origin) * geometry.xf.zoom;
let start = super::revolve::light_options(&Dialog::new("effect", serde_json::Value::Object(current.fields.clone())));
if *axis == 0 {
// Right turns the light counterclockwise, as along the ring's foot.
super::revolve::set_light_value(d, "lightRotation", json!(wrap(start.light_rotation + delta.x * 0.6, snap)));
} else {
super::revolve::set_light_value(d, "lightHeight", json!(snap_height(start.light_height - delta.y * 0.6, snap)));
}
}
}
Mode::Orbit => {
let delta = view.unmap_vec(pos - self.origin) * view.zoom;
let [x, y, z] = self.start.rotation;
next.rotation = [wrap(x + delta.y * 0.5, snap), wrap(y + delta.x * 0.5, snap), z];
}
Mode::Light => {
let start = light_options(&self.fields);
let projected = light_position(g, start) + (pos - self.origin);
let point = view.unmap_vec(projected - g.center) * (view.zoom / f64::from(g.radius * 1.4));
let [rotation, height] = start.light_at_on_side(Point::new(point.x, point.y));
next.light_rotation = wrap(rotation, snap);
next.light_height = snap_height(height, snap);
}
Mode::LightRing { axis } => {
let delta = view.unmap_vec(pos - self.origin) * view.zoom;
let start = light_options(&self.fields);
if *axis == 0 {
// Right turns the light counterclockwise, as along the ring's foot.
next.light_rotation = wrap(start.light_rotation + delta.x * 0.6, snap);
} else {
next.light_height = snap_height(start.light_height - delta.y * 0.6, snap);
}
current.last = p;
ui.data_mut(|m| m.insert_temp(drag_id(), current.clone()));
}
}
if response.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) {
ui.data_mut(|m| m.remove::<Drag>(drag_id()));
self.last = pos;
self.latest = next;
next
}
}
/// The style of the gizmo: the axis colours, the hot tone and the plates under its labels.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
pub(crate) struct RevolveGizmoStyle {
#[style(metrics)]
metrics: Metrics,
/// The X, Y and Z rings.
axis_x: StyleColor,
axis_y: StyleColor,
axis_z: StyleColor,
/// The hovered or dragged ring, the light and its rings.
hot: StyleColor,
/// The plate under a letter or a label, and the fill of a back light.
plate: StyleColor,
/// A hovered label's plate.
plate_hover: StyleColor,
/// The outline under the rings, so they read on any art.
halo: StyleColor,
/// Guides and the centre mark.
muted: StyleColor,
/// The readout's text.
ink: StyleColor,
}
impl RevolveGizmoStyle {
fn axis(&self, axis: usize) -> StyleColor {
[self.axis_x, self.axis_y, self.axis_z].get(axis).copied().unwrap_or(self.axis_z)
}
}
/// What the gizmo reports: the edit of the values.
#[derive(Debug)]
pub(crate) struct RevolveGizmoOutput {
/// A drag as `Begin` (at the first drag), `Update`s and `Commit` at the release; Escape cancels it, as does a
/// press that ends where it began.
pub edit: EditResponse<GizmoValues>,
}
impl Outcome for RevolveGizmoOutput {
type Value = GizmoValues;
fn response(&self) -> &Response {
&self.edit.response
}
}
#[derive(Default)]
struct Report {
/// The ring or light ring the pointer is over.
active: Option<usize>,
/// What the open press turns.
held: Option<Mode>,
}
/// The rotation rings and the light of a 3D effect's dialog, over the canvas.
///
/// - Pointer: the grab hand over the rings, the centre and the light, closed during a drag. The parts are pointer
/// only: the dialog's fields are the keyboard path.
/// - A press that is not on a ring turns X and Y together (the rotation page) or moves the light (the lighting page).
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(canvas_control, content_painter)]
pub(crate) struct RevolveGizmo<'a> {
#[common]
common: Common,
values: Bind<'a, GizmoValues>,
subject: &'a Subject,
report: Report,
}
impl<'a> RevolveGizmo<'a> {
fn new(label: &'static str, values: Bind<'a, GizmoValues>, subject: &'a Subject) -> Self {
RevolveGizmo { common: Common::new(), values, subject, report: Report::default() }.label(label)
}
fn light_mode(&self) -> bool {
lighting(&self.subject.fields)
}
/// The parts of the page in `light_mode`, each with the ring it highlights.
fn part_list(light_mode: bool) -> Vec<(PartRef, Option<usize>)> {
let mut parts = vec![(AREA.at(0), None)];
if light_mode {
parts.push((LIGHT.at(0), None));
parts.extend((0..2).flat_map(|axis| [(LIGHT_RING.at(axis as u64), Some(axis)), (LIGHT_LABEL.at(axis as u64), Some(axis))]));
} else {
parts.push((CENTRE.at(0), None));
parts.extend((0..3).map(|axis| (RING.at(axis as u64), Some(axis))));
}
if response.hovered() || drag.is_some() {
ui.ctx().set_cursor_icon(if drag.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
parts
}
fn declare(cx: &mut PartsCx<'_, Self>, part: PartRef, shape: HitShape, level: HitLevel) {
cx.part(part, shape)
.sense(Sense::DRAG | Sense::CLICK)
.priority(HitPriority::new(level, 0))
.cursor(CursorIcon::Grab)
.pointer_only(BY_FIELDS);
}
}
impl Component for RevolveGizmo<'_> {
const ROLE: Role = Role::GROUP;
const KEYS: KeyUse = KeyUse::CANVAS;
const OVERLAYS: bool = false;
type Style = RevolveGizmoStyle;
type Output = RevolveGizmoOutput;
fn style(cx: &StyleCx<'_>, _: RevolveGizmoStyleKey) -> RevolveGizmoStyle {
let colors = &cx.tokens.color;
RevolveGizmoStyle {
metrics: Metrics::new(),
axis_x: cx.color(colors.data.red),
axis_y: cx.color(colors.data.green),
axis_z: cx.color(colors.data.blue),
hot: cx.color(colors.status.warn.solid),
plate: cx.color(colors.surface.raised),
plate_hover: cx.color(colors.state.hover),
halo: cx.color(colors.overlay.halo),
muted: cx.color(colors.text.muted),
ink: cx.color(colors.text.normal),
}
let active = match drag.as_ref().map(|d| d.mode) {
Some(Mode::Ring { axis, .. }) => Some(axis),
Some(Mode::LightRing { axis }) => Some(axis),
_ => hovered.map(|h| h.0),
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::ZERO
}
fn bind(&mut self) -> Option<BindMut<'_, GizmoValues>> {
Some(self.values.reborrow())
}
/// The rings, the centre and the light as the page has them, over the gizmo's square, which takes every other
/// press of it.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(space) = canvas_space(&cx.env) else { return };
let Some(g) = Geometry::new(&space.view, &self.subject.fields, self.subject.bounds) else { return };
let light_mode = self.light_mode();
Self::declare(cx, AREA.at(0), HitShape::Rect(g.area(light_mode).intersect(rect)), HitLevel::Body);
if light_mode {
let options = light_options(&self.subject.fields);
Self::declare(cx, LIGHT.at(0), HitShape::circle(light_position(g, options), LIGHT_REACH), HitLevel::Handle);
for (axis, (ring, label)) in g.light_rings(options).into_iter().zip(g.light_labels()).enumerate() {
let points = g.arc(ring, light_span(axis));
Self::declare(cx, LIGHT_RING.at(axis as u64), HitShape::polyline_within(points, axis == 0, RING_REACH), HitLevel::Handle);
Self::declare(cx, LIGHT_LABEL.at(axis as u64), HitShape::Rect(label), HitLevel::Handle);
}
} else {
Self::declare(cx, CENTRE.at(0), HitShape::circle(g.center, ORBIT_REACH), HitLevel::Handle);
for (axis, ring) in g.rings.into_iter().enumerate() {
let points = g.arc(ring, std::f32::consts::TAU);
Self::declare(cx, RING.at(axis as u64), HitShape::polyline_within(points, true, RING_REACH), HitLevel::Handle);
}
}
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let (Some(space), Some(shown)) = (canvas_space(&cx.env), cx.value().copied()) else { return };
let Some(g) = Geometry::new(&space.view, &self.subject.fields, self.subject.bounds) else { return };
let (light_mode, options) = (self.light_mode(), light_options(&self.subject.fields));
let mut held: Option<Grip> = cx.press_slot::<Grip>().clone();
self.report.active = None;
for (reference, ring) in Self::part_list(light_mode) {
let Some(result) = cx.part_if_declared(reference) else { continue };
let press = result.press;
if result.hovered && held.is_none() && self.report.active.is_none() {
self.report.active = ring;
}
match press.phase {
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
held = Some(Grip {
mode: mode_at(g, options, light_mode, start.origin),
geometry: g,
start: shown,
fields: self.subject.fields.clone(),
origin: start.origin,
last: start.origin,
latest: shown,
began: false,
});
}
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
let Some(mut grip) = held.take() else { continue };
if matches!(press.phase, PressPhase::DragStart { .. }) && !grip.began {
cx.begin();
grip.began = true;
}
if grip.began {
cx.propose(grip.follow(&space.view, pos, press.mods.shift));
cx.cursor(CursorIcon::Grabbing, CursorPriority::Drag);
}
held = Some(grip);
}
PressPhase::Release { .. } => {
let Some(grip) = held.take() else { continue };
if grip.began && grip.latest == grip.start {
// A drag that ended where it began moved nothing: no step.
cx.cancel(CancelReason::Unchanged);
} else if grip.began {
cx.commit();
}
}
PressPhase::Cancel { .. } => held = None,
_ => {}
}
}
self.report.held = held.as_ref().map(|grip| grip.mode);
*cx.press_slot::<Grip>() = held;
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(space) = canvas_space(&cx.env) else { return };
let Some(g) = Geometry::new(&space.view, &self.subject.fields, self.subject.bounds) else { return };
let content = ui.content_painter(cx);
let paint = Paint {
painter: &content.painter,
style: cx.style,
view: &space.view,
subject: self.subject,
values: cx.value().copied().unwrap_or_default(),
g,
active: self.report.held.and_then(|mode| match mode {
Mode::Ring { axis, .. } | Mode::LightRing { axis } => Some(axis),
_ => None,
})
.or(self.report.active),
dragging: self.report.held,
};
paint(ui, d, Geometry::new(app, d).unwrap_or(geometry), active, drag.as_ref());
response.on_hover_text(hint(d));
});
if self.light_mode() {
paint.light();
} else {
paint.rotation();
}
}
fn access(&self, _: &mut Access, _: &Cx<'_, Self>) {}
fn finish(self, cx: Cx<'_, Self>) -> RevolveGizmoOutput {
RevolveGizmoOutput { edit: cx.edit_response() }
}
}
fn light_position(g: Geometry, options: Revolve) -> Pos2 {
let [x, y, _] = options.light_direction();
let (s, c) = (g.xf.rot as f32).sin_cos();
let (s, c) = g.turn;
g.center + vec2(c * x as f32 - s * y as f32, s * x as f32 + c * y as f32) * g.radius * 1.4
}
fn paint(ui: &egui::Ui, d: &Dialog, g: Geometry, active: Option<usize>, drag: Option<&Drag>) {
if lighting(d) {
paint_light(ui, d, g, active, drag);
return;
}
let t = Tokens::get(ui.ctx());
let painter = ui.painter();
let colors = [t.axis_x, t.axis_y, t.axis_z];
for (axis, ring) in g.rings.iter().enumerate() {
let color = if active == Some(axis) { t.warning } else { colors[axis] };
for i in 0..SAMPLES {
let angle = i as f32 * std::f32::consts::TAU / SAMPLES as f32;
let behind = ring.depth[0] * angle.cos() + ring.depth[1] * angle.sin() < -0.05;
if behind && i % 3 == 0 {
continue;
/// What a pass draws with.
struct Paint<'a> {
painter: &'a Painter,
style: &'a RevolveGizmoStyle,
view: &'a CanvasView,
subject: &'a Subject,
values: GizmoValues,
g: Geometry,
/// The ring or light ring shown hot.
active: Option<usize>,
/// What the open drag turns.
dragging: Option<Mode>,
}
impl Paint<'_> {
fn rotation(&self) {
let (g, s, painter) = (self.g, self.style, self.painter);
for (axis, ring) in g.rings.iter().enumerate() {
let hot = self.active == Some(axis);
let color = if hot { s.hot.egui() } else { s.axis(axis).egui() };
for i in 0..SAMPLES {
let angle = i as f32 * std::f32::consts::TAU / SAMPLES as f32;
let behind = ring.depth[0] * angle.cos() + ring.depth[1] * angle.sin() < -0.05;
if behind && i % 3 == 0 {
continue;
}
let points = [g.center + ring.point(angle), g.center + ring.point(angle + std::f32::consts::TAU / SAMPLES as f32)];
painter.line_segment(points, Stroke::new(4.0, s.halo.egui().gamma_multiply(0.55)));
painter.line_segment(points, Stroke::new(if hot { 2.5 } else { 1.75 }, color.gamma_multiply(if behind { 0.55 } else { 1.0 })));
}
let points = [g.center + ring.point(angle), g.center + ring.point(angle + std::f32::consts::TAU / SAMPLES as f32)];
painter.line_segment(points, Stroke::new(4.0, t.input.gamma_multiply(0.55)));
painter.line_segment(
points,
Stroke::new(if active == Some(axis) { 2.5 } else { 1.75 }, color.gamma_multiply(if behind { 0.55 } else { 1.0 })),
);
// Letters make the axes distinguishable without relying on colour alone.
let phase = match axis {
0 => 0.75,
1 => 2.25,
_ => 4.7,
};
let p = g.center + ring.point(phase);
painter.circle_filled(p, 9.0, s.plate.egui());
painter.text(p, Align2::CENTER_CENTER, ["X", "Y", "Z"][axis], FontId::proportional(11.0), color);
}
painter.circle(g.center, 8.0, s.plate.egui().gamma_multiply(0.8), Stroke::new(1.5, s.muted.egui()));
painter.line_segment([g.center - vec2(4.0, 0.0), g.center + vec2(4.0, 0.0)], Stroke::new(1.0, s.muted.egui()));
painter.line_segment([g.center - vec2(0.0, 4.0), g.center + vec2(0.0, 4.0)], Stroke::new(1.0, s.muted.egui()));
if self.subject.fields.bool("__showAxis").unwrap_or(false) {
let options = light_options(&self.subject.fields);
painter.line_segment(options.projected_axis(self.subject.bounds).map(|p| self.view.to_screen(p)), Stroke::new(1.0, s.hot.egui()));
}
if let Some(Mode::Ring { axis, .. }) = self.dragging {
let degrees = self.values.rotation.get(axis).copied().unwrap_or(0.0);
let text = format!("{} {degrees:.1}°", ["X", "Y", "Z"].get(axis).unwrap_or(&""));
self.readout(text, g.center + vec2(0.0, g.radius * 1.12 + 18.0), 12.0);
}
// Letters make the axes distinguishable without relying on colour alone.
let phase = match axis {
0 => 0.75,
1 => 2.25,
_ => 4.7,
};
let p = g.center + ring.point(phase);
painter.circle_filled(p, 9.0, t.panel);
painter.text(p, Align2::CENTER_CENTER, ["X", "Y", "Z"][axis], FontId::proportional(11.0), color);
}
painter.circle(g.center, 8.0, t.panel.gamma_multiply(0.8), Stroke::new(1.5, t.text_dim));
painter.line_segment([g.center - vec2(4.0, 0.0), g.center + vec2(4.0, 0.0)], Stroke::new(1.0, t.text_dim));
painter.line_segment([g.center - vec2(0.0, 4.0), g.center + vec2(0.0, 4.0)], Stroke::new(1.0, t.text_dim));
let options = super::revolve::light_options(d);
if d.bool("__showAxis") {
painter.line_segment(options.projected_axis(g.bounds).map(|p| g.xf.to_screen(p)), Stroke::new(1.0, t.warning));
fn light(&self) {
let (g, s, painter) = (self.g, self.style, self.painter);
let options = light_options(&self.subject.fields);
let radius = g.radius * 1.4;
painter.circle_stroke(g.center, radius, Stroke::new(1.0, s.muted.egui().gamma_multiply(0.3)));
let labels = g.light_labels();
for (axis, ring) in g.light_rings(options).iter().enumerate() {
let span = light_span(axis);
for i in 0..SAMPLES {
let a = i as f32 * span / SAMPLES as f32;
let behind = ring.depth[0] * a.cos() + ring.depth[1] * a.sin() < -0.05;
if behind && i % 3 == 0 {
continue;
}
let points = [g.center + ring.point(a), g.center + ring.point(a + span / SAMPLES as f32)];
painter.line_segment(points, Stroke::new(4.0, s.plate.egui().gamma_multiply(0.4)));
painter.line_segment(
points,
Stroke::new(if self.active == Some(axis) { 2.5 } else { 1.5 }, s.hot.egui().gamma_multiply(if behind { 0.45 } else { 0.85 })),
);
}
let label = labels[axis];
painter.rect_filled(label, 4.0, if self.active == Some(axis) { s.plate_hover.egui() } else { s.plate.egui() });
let text = if axis == 0 { tl!("Rotation") } else { tl!("Height") };
painter.text(label.center(), Align2::CENTER_CENTER, text, FontId::proportional(11.0), s.hot.egui());
}
let p = light_position(g, options);
let delta = g.center - p;
if delta.length() > 24.0 {
let direction = delta.normalized();
let normal = vec2(-direction.y, direction.x);
let tip = g.center - direction * 12.0;
painter.line_segment([p, tip], Stroke::new(1.25, s.hot.egui().gamma_multiply(0.6)));
painter.line_segment([tip, tip - direction * 8.0 + normal * 4.0], Stroke::new(1.25, s.hot.egui()));
painter.line_segment([tip, tip - direction * 8.0 - normal * 4.0], Stroke::new(1.25, s.hot.egui()));
}
painter.circle(g.center, 4.0, s.plate.egui(), Stroke::new(1.0, s.muted.egui()));
// An original sun handle. A back light is hollow; the guide's back half is dashed.
let front = options.light_direction()[2] >= 0.0;
let [r, green, b] = options.light_color.map(|c| (c * 255.0).round() as u8);
let color = egui::Color32::from_rgb(r, green, b);
// Keep the themed outline and rays readable even with a dark light color.
painter.circle(p, 9.0, if front { color } else { s.plate.egui() }, Stroke::new(2.0, s.hot.egui()));
if !front {
painter.circle_stroke(p, 5.0, Stroke::new(2.0, color));
}
for i in 0..8 {
let angle = i as f32 * std::f32::consts::TAU / 8.0;
let direction = vec2(angle.cos(), angle.sin());
painter.line_segment([p + direction * 13.0, p + direction * 17.0], Stroke::new(1.5, s.hot.egui()));
}
let name = crate::i18n::tr_ctx(crate::i18n::current(), "lighting", "Light");
let galley = painter.layout_no_wrap(name.to_string(), FontId::proportional(11.0), s.hot.egui());
let name_pos = p - vec2(galley.size().x * 0.5, 25.0 + galley.size().y);
painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), galley.size() + vec2(8.0, 4.0)), 3.0, s.plate.egui());
painter.galley(name_pos, galley, s.hot.egui());
if self.dragging.is_some() {
let text = format!("{} {:.1}° {} {:.1}°", tl!("Rotation"), self.values.light_rotation, tl!("Height"), self.values.light_height);
self.readout(text, g.center + vec2(0.0, radius + 56.0), 11.5);
}
}
if let Some(Drag { mode: Mode::Ring { axis, .. }, .. }) = drag
&& let Some(key) = KEYS.get(*axis)
{
let text = format!("{} {:.1}°", ["X", "Y", "Z"].get(*axis).unwrap_or(&""), d.f64(key, 0.0));
let pos = g.center + vec2(0.0, g.radius * 1.12 + 18.0);
let galley = painter.layout_no_wrap(text, FontId::proportional(12.0), t.text_strong);
painter.rect_filled(Rect::from_center_size(pos, galley.size() + vec2(14.0, 8.0)), 4.0, t.panel);
painter.galley(pos - galley.size() * 0.5, galley, t.text_strong);
/// `text` on a plate centred at `at`.
fn readout(&self, text: String, at: Pos2, size: f32) {
let (s, painter) = (self.style, self.painter);
let galley = painter.layout_no_wrap(text, FontId::proportional(size), s.ink.egui());
painter.rect_filled(Rect::from_center_size(at, galley.size() + vec2(14.0, 8.0)), 4.0, s.plate.egui());
painter.galley(at - galley.size() * 0.5, galley, s.ink.egui());
}
}
fn paint_light(ui: &egui::Ui, d: &Dialog, g: Geometry, active: Option<usize>, drag: Option<&Drag>) {
let t = Tokens::get(ui.ctx());
let painter = ui.painter();
let options = super::revolve::light_options(d);
let radius = g.radius * 1.4;
painter.circle_stroke(g.center, radius, Stroke::new(1.0, t.text_dim.gamma_multiply(0.3)));
let labels = g.light_labels();
for (axis, ring) in g.light_rings(options).iter().enumerate() {
let (start, span) = if axis == 0 { (0.0, std::f32::consts::TAU) } else { (0.0, std::f32::consts::FRAC_PI_2) };
for i in 0..SAMPLES {
let a = start + i as f32 * span / SAMPLES as f32;
let behind = ring.depth[0] * a.cos() + ring.depth[1] * a.sin() < -0.05;
if behind && i % 3 == 0 {
continue;
}
let points = [g.center + ring.point(a), g.center + ring.point(a + span / SAMPLES as f32)];
painter.line_segment(points, Stroke::new(4.0, t.panel.gamma_multiply(0.4)));
painter.line_segment(
points,
Stroke::new(if active == Some(axis) { 2.5 } else { 1.5 }, t.warning.gamma_multiply(if behind { 0.45 } else { 0.85 })),
);
/// The bounds of the first selected object, which the gizmo turns.
fn selected_bounds(app: &VectorcraftApp) -> Option<vectorcraft_geom::Rect> {
let state = app.session.active()?;
state.doc.node(*state.selection.objects.first()?)?.geometric_bounds()
}
/// Writes the values `landed` that differ from `before` into the dialog; keys that did not change are left alone.
fn write(dialog: &mut HostedParamDialog, before: GizmoValues, landed: GizmoValues) {
for (axis, key) in KEYS.iter().enumerate() {
if landed.rotation[axis] != before.rotation[axis] {
dialog.set_field(*key, FieldValue::Number(landed.rotation[axis]));
}
let label = labels[axis];
painter.rect_filled(label, 4.0, if active == Some(axis) { t.hover } else { t.panel });
let text = if axis == 0 { tl!("Rotation") } else { tl!("Height") };
painter.text(label.center(), Align2::CENTER_CENTER, text, FontId::proportional(11.0), t.warning);
}
let p = light_position(g, options);
let delta = g.center - p;
if delta.length() > 24.0 {
let direction = delta.normalized();
let normal = vec2(-direction.y, direction.x);
let tip = g.center - direction * 12.0;
painter.line_segment([p, tip], Stroke::new(1.25, t.warning.gamma_multiply(0.6)));
painter.line_segment([tip, tip - direction * 8.0 + normal * 4.0], Stroke::new(1.25, t.warning));
painter.line_segment([tip, tip - direction * 8.0 - normal * 4.0], Stroke::new(1.25, t.warning));
// The selected light's keys are the light editor's rule (`set_light_value`); only the keys it changed are written.
let mut fields = dialog.fields().clone();
for (key, was, now) in [("lightRotation", before.light_rotation, landed.light_rotation), ("lightHeight", before.light_height, landed.light_height)] {
if was != now {
set_light_value(&mut fields, key, json!(now));
}
}
painter.circle(g.center, 4.0, t.panel, Stroke::new(1.0, t.text_dim));
// An original sun handle. A back light is hollow; the guide's back half is dashed.
let front = options.light_direction()[2] >= 0.0;
let [r, green, b] = options.light_color.map(|c| (c * 255.0).round() as u8);
let color = egui::Color32::from_rgb(r, green, b);
// Keep the themed outline and rays readable even with a dark light color.
painter.circle(p, 9.0, if front { color } else { t.panel }, Stroke::new(2.0, t.warning));
if !front {
painter.circle_stroke(p, 5.0, Stroke::new(2.0, color));
for key in ["lights", "lightRotation", "lightHeight"] {
if let Some(value) = fields.get(key)
&& dialog.fields().get(key) != Some(value)
{
dialog.set_field(key, value.clone());
}
}
for i in 0..8 {
let angle = i as f32 * std::f32::consts::TAU / 8.0;
let direction = vec2(angle.cos(), angle.sin());
painter.line_segment([p + direction * 13.0, p + direction * 17.0], Stroke::new(1.5, t.warning));
}
let name = crate::i18n::tr_ctx(crate::i18n::current(), "lighting", "Light");
let galley = painter.layout_no_wrap(name.to_string(), FontId::proportional(11.0), t.warning);
let name_pos = p - vec2(galley.size().x * 0.5, 25.0 + galley.size().y);
painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), galley.size() + vec2(8.0, 4.0)), 3.0, t.panel);
painter.galley(name_pos, galley, t.warning);
if drag.is_some() {
let [rotation, height] = [("lightRotation", vectorcraft_three_d::DEFAULT_LIGHT.0), ("lightHeight", vectorcraft_three_d::DEFAULT_LIGHT.1)]
.map(|(k, v)| d.f64(k, v));
let text = format!("{} {rotation:.1}° {} {height:.1}°", tl!("Rotation"), tl!("Height"));
let galley = painter.layout_no_wrap(text, FontId::proportional(11.5), t.text_strong);
let pos = g.center + vec2(0.0, radius + 56.0);
painter.rect_filled(Rect::from_center_size(pos, galley.size() + vec2(12.0, 6.0)), 4.0, t.panel);
painter.galley(pos - galley.size() * 0.5, galley, t.text_strong);
}
/// The gizmo over the canvas while the 3D effect's dialog shows it, then the Map Art outline: each event's values go
/// to the dialog's fields, which its preview applies.
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) {
if three_d::gizmo_shown(app)
&& let Some(bounds) = selected_bounds(app)
&& let Some(fields) = three_d::with_fields(app, |dialog| dialog.fields().clone())
&& shown(&fields)
{
let before = GizmoValues::of(&fields);
let label = if lighting(&fields) { tl!("Lighting") } else { tl!("Rotation") };
let subject = Subject { fields, bounds };
let output = RevolveGizmo::new(label, Bind::given(before), &subject).show_at(ui, space.view.rect);
// The last value of the pass's events, a cancel's included: Escape writes the values back.
if let Some(landed) = output.edit.events.landed().copied() {
three_d::with_fields(app, |dialog| write(dialog, before, landed));
}
}
super::three_d_classic::show_outline(app, ui, space);
}
#[cfg(test)]
+163 -250
View File
@@ -1,104 +1,84 @@
//! Pointer gestures exercise the real artboard overlay and command preview, including rollback.
//! Pointer gestures drive the real gizmo through the 3D dialog's host: the canvas frame runs `revolve_gizmo::show`,
//! the dialog's pump previews the fields, and Escape is the edit stream's cancel.
// PLAN: assumed effects-w13's `three_d::tests_support::ThreeD`: `open(effect, build: &[(&str, Value)], preview: bool) -> ThreeD`,
// `.app`, `.frame(events, mods)`, `.settle()`, `.view() -> CanvasView`, `.fields() -> DialogFields`, `.value(key) -> f64`,
// `.set(key, Value)` (the host's `set_json_field`), `.is_open()`, `.held() -> Option<HeldOk>`, `.cancel()`.
use super::*;
use crate::{dialogs, theme};
use crate::dialogs::three_d::tests_support::ThreeD;
use craft_ui::dialog::HeldOk;
use egui::{Event, Modifiers, PointerButton};
use serde_json::Value;
use vectorcraft_effects::revolve_options;
use vectorcraft_engine::Session;
use vectorcraft_effects::EXTRUDE;
struct Harness {
app: VectorcraftApp,
ctx: egui::Context,
/// The stroke the gizmo tests turn, as the old harness built it.
fn stroke() -> Vec<(&'static str, Value)> {
vec![("path.create", json!({"d":"M150 40 L180 60 L180 140 L150 160"})), ("paint.setFill", json!({"color":"#338ad6"}))]
}
impl Harness {
fn new() -> Self {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width":300,"height":300})).unwrap();
app.run("path.create", json!({"d":"M150 40 L180 60 L180 140 L150 160"})).unwrap();
app.run("paint.setFill", json!({"color":"#338ad6"})).unwrap();
app.run("effect.dialog", json!({"effect":REVOLVE,"item":null})).unwrap();
app.canvas_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0)));
let v = app.view_mut().unwrap();
v.center = Point::new(270.0, 150.0);
v.zoom = 2.0;
v.fitted = true;
let ctx = egui::Context::default();
theme::install_fonts(&ctx);
theme::apply(&ctx, Default::default());
let mut h = Self { app, ctx };
h.settle();
h
}
fn frame(&mut self, events: Vec<Event>, modifiers: Modifiers) {
let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))), events, ..Default::default() };
let mut out = self.ctx.run_ui(input, |ui| {
crate::shortcuts::handle(&mut self.app, ui.ctx());
egui::CentralPanel::default().show(ui, |ui| crate::canvas::show(&mut self.app, ui));
dialogs::show(&mut self.app, ui.ctx());
});
out.textures_delta.clear();
}
fn settle(&mut self) {
for _ in 0..5 {
self.frame(vec![], Modifiers::NONE);
}
}
fn geometry(&self) -> Geometry {
Geometry::new(&self.app, self.app.ui.dialog.as_ref().unwrap()).unwrap()
}
fn value(&self, key: &str) -> f64 {
self.app.ui.dialog.as_ref().unwrap().f64(key, 0.0)
}
fn start(&mut self, p: Pos2, modifiers: Modifiers) {
self.frame(vec![Event::PointerMoved(p)], modifiers);
self.frame(vec![button(p, true, modifiers)], modifiers);
}
fn release(&mut self, p: Pos2, modifiers: Modifiers) {
self.frame(vec![button(p, false, modifiers)], modifiers);
self.settle();
}
fn ring_drag(&mut self, axis: usize, modifiers: Modifiers) {
let g = self.geometry();
let ring = g.rings[axis];
// Choose a visible point belonging only to this ring, away from crossings.
let phase = (0..SAMPLES)
.map(|i| i as f32 * std::f32::consts::TAU / SAMPLES as f32)
.find(|a| g.hit(g.center + ring.point(*a)).is_some_and(|h| h.0 == axis) && ring.tangent(*a).length() > 40.0)
.unwrap();
let from = g.center + ring.point(phase);
self.start(from, modifiers);
let mut p = from;
for i in 1..=8 {
p = g.center + ring.point(phase + i as f32 * 0.045);
self.frame(vec![Event::PointerMoved(p)], modifiers);
}
self.release(p, modifiers);
}
fn revolve() -> ThreeD {
ThreeD::open(REVOLVE, &stroke(), true)
}
fn button(pos: Pos2, pressed: bool, modifiers: Modifiers) -> Event {
Event::PointerButton { pos, pressed, button: PointerButton::Primary, modifiers }
}
fn escape() -> Event {
Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
}
fn geometry(h: &ThreeD) -> Geometry {
Geometry::new(&h.view(), &h.fields(), selected_bounds(&h.app).unwrap()).unwrap()
}
fn start(h: &mut ThreeD, p: Pos2, modifiers: Modifiers) {
h.frame(vec![Event::PointerMoved(p)], modifiers);
h.frame(vec![button(p, true, modifiers)], modifiers);
}
fn release(h: &mut ThreeD, p: Pos2, modifiers: Modifiers) {
h.frame(vec![button(p, false, modifiers)], modifiers);
h.settle();
}
/// Presses at `from`, drags to `to` in two frames and releases.
fn drag(h: &mut ThreeD, from: Pos2, to: Pos2, modifiers: Modifiers) {
start(h, from, modifiers);
h.frame(vec![Event::PointerMoved(from.lerp(to, 0.5))], modifiers);
h.frame(vec![Event::PointerMoved(to)], modifiers);
release(h, to, modifiers);
}
/// Drags the ring `axis` along its curve from a point that belongs to it alone, away from crossings.
fn ring_drag(h: &mut ThreeD, axis: usize, modifiers: Modifiers) {
let g = geometry(h);
let ring = g.rings[axis];
let phase = (0..SAMPLES)
.map(|i| i as f32 * std::f32::consts::TAU / SAMPLES as f32)
.find(|a| g.hit(g.center + ring.point(*a)).is_some_and(|hit| hit.0 == axis) && ring.tangent(*a).length() > 40.0)
.unwrap();
let from = g.center + ring.point(phase);
start(h, from, modifiers);
let mut p = from;
for i in 1..=8 {
p = g.center + ring.point(phase + i as f32 * 0.045);
h.frame(vec![Event::PointerMoved(p)], modifiers);
}
release(h, p, modifiers);
}
fn an_image() -> Vec<(&'static str, Value)> {
let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png());
vec![("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [150, 150]}))]
}
#[test]
fn each_ring_changes_only_its_rotation_field_and_cancel_restores_the_source() {
for (axis, key) in KEYS.iter().enumerate() {
let mut h = Harness::new();
let mut h = revolve();
let before = h.app.session.active().unwrap().interaction.as_ref().unwrap().doc.clone();
let original = KEYS.map(|key| h.value(key));
h.ring_drag(axis, Modifiers::NONE);
ring_drag(&mut h, axis, Modifiers::NONE);
for (k, key) in KEYS.iter().enumerate() {
if k == axis {
assert!(h.value(key) > original[k] + 10.0, "axis {axis}, {}", h.value(key));
@@ -110,95 +90,90 @@ fn each_ring_changes_only_its_rotation_field_and_cancel_restores_the_source() {
let node = state.doc.node(state.selection.objects[0]).unwrap();
assert_eq!(node.path_data(), before.node(node.id).unwrap().path_data(), "ring drags must not move source anchors");
assert_eq!(node.appearance.effects[0].params[*key], json!(h.value(key)));
dialogs::cancel(&mut h.app);
h.cancel();
assert_eq!(h.app.session.doc().unwrap().doc, before);
}
}
#[test]
fn ring_drag_snaps_and_confirm_is_one_undo_step() {
let mut h = Harness::new();
let before = h.app.session.active().unwrap().interaction.as_ref().unwrap().doc.clone();
h.ring_drag(2, Modifiers::SHIFT);
fn ring_drag_with_shift_snaps_to_15_degrees() {
let mut h = revolve();
ring_drag(&mut h, 2, Modifiers::SHIFT);
assert!(h.value("rotationZ") > 0.0);
assert_eq!(h.value("rotationZ") % 15.0, 0.0);
dialogs::confirm(&mut h.app).unwrap();
h.app.run("edit.undo", json!({})).unwrap();
assert_eq!(h.app.session.doc().unwrap().doc, before);
}
#[test]
fn a_press_without_a_drag_changes_nothing() {
let mut h = revolve();
let before = h.fields();
let at = geometry(&h).center;
start(&mut h, at, Modifiers::NONE);
release(&mut h, at, Modifiers::NONE);
assert_eq!(h.fields(), before);
}
#[test]
fn free_orbit_and_light_drag_update_the_canvas_and_escape_restores_only_the_gesture() {
let mut h = Harness::new();
let before = super::super::form::params(h.app.ui.dialog.as_ref().unwrap());
let center = h.geometry().center;
h.start(center, Modifiers::NONE);
let mut h = revolve();
let before = h.fields();
let center = geometry(&h).center;
start(&mut h, center, Modifiers::NONE);
let p = center + vec2(50.0, 30.0);
h.frame(vec![Event::PointerMoved(p)], Modifiers::NONE);
assert_ne!(h.value("rotationX"), before["rotationX"].as_f64().unwrap());
assert_ne!(h.value("rotationY"), before["rotationY"].as_f64().unwrap());
assert_ne!(h.value("rotationX"), before.number("rotationX").unwrap());
assert_ne!(h.value("rotationY"), before.number("rotationY").unwrap());
h.frame(vec![escape()], Modifiers::NONE);
h.frame(
vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }],
Modifiers::NONE,
);
h.release(p, Modifiers::NONE);
assert!(h.app.ui.dialog.is_some());
assert_eq!(super::super::form::params(h.app.ui.dialog.as_ref().unwrap()), before);
let state = h.app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
assert_eq!(node.appearance.effects[0].params["rotationX"], before["rotationX"]);
assert_eq!(node.appearance.effects[0].params["rotationY"], before["rotationY"]);
h.app.ui.dialog.as_mut().unwrap().fields.insert("__gizmo".into(), json!("light"));
release(&mut h, p, Modifiers::NONE);
assert!(h.is_open());
assert_eq!(h.fields(), before);
h.set("__page", json!("lighting"));
h.settle();
let light = light_position(h.geometry(), revolve_options(&before));
h.start(light, Modifiers::NONE);
let p = light + vec2(20.0, 25.0);
h.frame(vec![Event::PointerMoved(p)], Modifiers::NONE);
h.release(p, Modifiers::NONE);
assert_ne!(h.value("lightRotation"), before["lightRotation"].as_f64().unwrap());
let light = light_position(geometry(&h), light_options(&h.fields()));
drag(&mut h, light, light + vec2(20.0, 25.0), Modifiers::NONE);
assert_ne!(h.value("lightRotation"), before.number("lightRotation").unwrap());
assert_ne!(h.value("lightHeight"), 30.0);
// With no gesture open, Escape is the dialog's: the gizmo does not eat it.
h.frame(vec![escape()], Modifiers::NONE);
assert!(h.app.ui.dialog.is_none() && !h.app.session.in_interaction());
assert!(!h.is_open() && !h.app.session.in_interaction());
}
#[test]
fn preview_off_has_no_gizmo_and_edge_on_rings_remain_finite() {
let mut h = Harness::new();
let d = h.app.ui.dialog.as_mut().unwrap();
d.fields.insert("rotationX".into(), json!(0.0));
d.fields.insert("rotationY".into(), json!(0.0));
d.fields.insert("rotationZ".into(), json!(0.0));
let mut h = revolve();
for key in KEYS {
h.set(key, json!(0.0));
}
h.settle();
h.ring_drag(0, Modifiers::NONE);
ring_drag(&mut h, 0, Modifiers::NONE);
assert!(h.value("rotationX").is_finite() && h.value("rotationX").abs() > 1.0);
h.app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false));
h.set("preview", json!(false));
h.settle();
assert!(!h.app.session.in_interaction());
let before = super::super::form::params(h.app.ui.dialog.as_ref().unwrap());
h.ring_drag(2, Modifiers::NONE);
assert_eq!(super::super::form::params(h.app.ui.dialog.as_ref().unwrap()), before);
let before = h.fields();
// The gizmo has no geometry to press while Preview is off: the press point is the one Preview on had.
let center = geometry(&h).center;
drag(&mut h, center, center + vec2(40.0, 40.0), Modifiers::NONE);
assert_eq!(h.fields(), before);
}
#[test]
fn light_rings_adjust_only_their_angle_and_snap_without_rotating_the_object() {
for (axis, key) in ["lightRotation", "lightHeight"].iter().enumerate() {
let mut h = Harness::new();
h.app.ui.dialog.as_mut().unwrap().fields.insert("__gizmo".into(), json!("light"));
let mut h = revolve();
h.set("__page", json!("lighting"));
h.settle();
let before = super::super::form::params(h.app.ui.dialog.as_ref().unwrap());
let from = h.geometry().light_labels()[axis].center();
h.start(from, Modifiers::SHIFT);
let before = h.fields();
let from = geometry(&h).light_labels()[axis].center();
let delta = if axis == 0 { vec2(68.0, 0.0) } else { vec2(0.0, -43.0) };
h.frame(vec![Event::PointerMoved(from + delta)], Modifiers::SHIFT);
h.release(from + delta, Modifiers::SHIFT);
assert_ne!(h.value(key), before[*key].as_f64().unwrap());
drag(&mut h, from, from + delta, Modifiers::SHIFT);
assert_ne!(h.value(key), before.number(key).unwrap());
assert_eq!(h.value(key) % 15.0, 0.0);
for unchanged in ["rotationX", "rotationY", "rotationZ", "lightIntensity", "ambient"] {
assert_eq!(h.value(unchanged), before[unchanged].as_f64().unwrap());
assert_eq!(h.value(unchanged), before.number(unchanged).unwrap());
}
let other = if axis == 0 { "lightHeight" } else { "lightRotation" };
assert_eq!(h.value(other), before[other].as_f64().unwrap());
assert_eq!(h.value(other), before.number(other).unwrap());
let state = h.app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
assert_eq!(node.appearance.effects[0].params[*key], json!(h.value(key)));
@@ -207,168 +182,106 @@ fn light_rings_adjust_only_their_angle_and_snap_without_rotating_the_object() {
#[test]
fn light_handle_preserves_the_back_side_and_escape_cancel_and_undo_restore_changes() {
let mut h = Harness::new();
let mut h = revolve();
let original = h.app.session.active().unwrap().interaction.as_ref().unwrap().doc.clone();
let d = h.app.ui.dialog.as_mut().unwrap();
d.fields.insert("__gizmo".into(), json!("light"));
d.fields.insert("lightBehind".into(), json!(true));
h.set("__page", json!("lighting"));
h.set("lightBehind", json!(true));
h.settle();
let before = super::super::form::params(h.app.ui.dialog.as_ref().unwrap());
let light = light_position(h.geometry(), revolve_options(&before));
h.start(light, Modifiers::NONE);
let before = h.fields();
let light = light_position(geometry(&h), light_options(&before));
start(&mut h, light, Modifiers::NONE);
let to = light + vec2(-15.0, 12.0);
h.frame(vec![Event::PointerMoved(to)], Modifiers::NONE);
assert!(revolve_options(&super::super::form::params(h.app.ui.dialog.as_ref().unwrap())).light_direction()[2] < 0.0);
assert!(light_options(&h.fields()).light_direction()[2] < 0.0);
assert_ne!(h.value("lightHeight"), 30.0);
h.frame(vec![escape()], Modifiers::NONE);
h.release(to, Modifiers::NONE);
assert_eq!(super::super::form::params(h.app.ui.dialog.as_ref().unwrap()), before);
let state = h.app.session.active().unwrap();
assert_eq!(state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params["lightHeight"], before["lightHeight"]);
release(&mut h, to, Modifiers::NONE);
assert_eq!(h.fields(), before);
// A second gesture is kept by OK, and the whole dialog is one undo step.
let from = h.geometry().light_labels()[0].center();
h.start(from, Modifiers::NONE);
h.frame(vec![Event::PointerMoved(from + vec2(35.0, 0.0))], Modifiers::NONE);
h.release(from + vec2(35.0, 0.0), Modifiers::NONE);
dialogs::confirm(&mut h.app).unwrap();
let from = geometry(&h).light_labels()[0].center();
drag(&mut h, from, from + vec2(35.0, 0.0), Modifiers::NONE);
h.confirm();
h.app.run("edit.undo", json!({})).unwrap();
assert_eq!(h.app.session.doc().unwrap().doc, original);
}
#[test]
fn light_height_is_bounded_and_shading_off_disables_the_light_gizmo() {
let mut h = Harness::new();
h.app.ui.dialog.as_mut().unwrap().fields.insert("__gizmo".into(), json!("light"));
let mut h = revolve();
h.set("__page", json!("lighting"));
h.settle();
let from = h.geometry().light_labels()[1].center();
h.start(from, Modifiers::NONE);
h.frame(vec![Event::PointerMoved(from - vec2(0.0, 400.0))], Modifiers::NONE);
h.release(from - vec2(0.0, 400.0), Modifiers::NONE);
let from = geometry(&h).light_labels()[1].center();
drag(&mut h, from, from - vec2(0.0, 400.0), Modifiers::NONE);
assert_eq!(h.value("lightHeight"), 90.0);
h.app.ui.dialog.as_mut().unwrap().fields.insert("shade".into(), json!(false));
h.set("shade", json!(false));
h.settle();
let before = super::super::form::params(h.app.ui.dialog.as_ref().unwrap());
let from = h.geometry().light_labels()[0].center();
h.start(from, Modifiers::NONE);
h.frame(vec![Event::PointerMoved(from + vec2(40.0, 0.0))], Modifiers::NONE);
h.release(from + vec2(40.0, 0.0), Modifiers::NONE);
assert_eq!(super::super::form::params(h.app.ui.dialog.as_ref().unwrap()), before);
let before = h.fields();
let from = geometry(&h).light_labels()[0].center();
drag(&mut h, from, from + vec2(40.0, 0.0), Modifiers::NONE);
assert_eq!(h.fields(), before);
}
#[test]
fn selected_light_gizmo_edits_only_that_light_and_escape_restores_the_list() {
let mut h = Harness::new();
let d = h.app.ui.dialog.as_mut().unwrap();
d.fields.insert("__gizmo".into(), json!("light"));
d.fields.insert("__light".into(), json!(1));
d.fields.insert(
"lights".into(),
let mut h = revolve();
h.set("__page", json!("lighting"));
h.set("__light", json!(1));
h.set(
"lights",
json!([
{"color":"#ff0000","rotation":30,"height":45,"intensity":60},
{"color":"#0000ff","rotation":-45,"height":30,"intensity":50}
]),
);
h.settle();
let before = h.app.ui.dialog.as_ref().unwrap().fields["lights"].clone();
let g = h.geometry();
let p = g.light_labels()[0].center();
h.start(p, Modifiers::NONE);
let before = h.fields().list("lights").unwrap().into_owned();
let p = geometry(&h).light_labels()[0].center();
start(&mut h, p, Modifiers::NONE);
h.frame(vec![Event::PointerMoved(p + vec2(60.0, 0.0))], Modifiers::NONE);
h.frame(vec![Event::PointerMoved(p + vec2(80.0, 0.0))], Modifiers::NONE);
let d = h.app.ui.dialog.as_ref().unwrap();
assert_eq!(d.fields["lights"][0], before[0]);
assert_ne!(d.fields["lights"][1]["rotation"], before[1]["rotation"]);
h.frame(
vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }],
Modifiers::NONE,
);
h.release(p + vec2(80.0, 0.0), Modifiers::NONE);
assert_eq!(h.app.ui.dialog.as_ref().unwrap().fields["lights"], before);
let now = h.fields().list("lights").unwrap().into_owned();
assert_eq!(now[0], before[0]);
assert_ne!(now[1], before[1]);
h.frame(vec![escape()], Modifiers::NONE);
release(&mut h, p + vec2(80.0, 0.0), Modifiers::NONE);
assert_eq!(h.fields().list("lights").unwrap().into_owned(), before);
}
impl Harness {
/// A fresh document where `build` runs and Extrude & Bevel's dialog opens, its Preview `on`.
fn extrude_dialog(build: &[(&str, Value)], on: bool) -> Self {
let mut h = Self::new();
dialogs::cancel(&mut h.app);
h.app.run("file.new", json!({"width":300,"height":300})).unwrap();
for (id, p) in build {
h.app.run(id, p.clone()).unwrap();
}
h.app.run("effect.dialog", json!({"effect": vectorcraft_effects::EXTRUDE})).unwrap();
h.app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(on));
h.settle();
h
}
fn ok_is_on(&self) -> bool {
let d = self.app.ui.dialog.as_ref().unwrap();
dialogs::spec(&d.kind).ok_enabled.is_none_or(|f| f(&self.app, d))
}
/// Does the next frame of the dialog draw a text holding `text`?
fn shows(&mut self, text: &str) -> bool {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))), ..Default::default() };
let mut out = self.ctx.run_ui(input, |ui| dialogs::show(&mut self.app, ui.ctx()));
out.textures_delta.clear();
out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.job.text.contains(text)))
}
}
fn an_image() -> Vec<(&'static str, Value)> {
let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png());
vec![("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [150, 150]}))]
}
/// #6140: on an object a 3D effect can't take, the dialog says why in its own words, and OK, which
/// could only fail, is off, where it used to look as if OK did nothing.
/// #6140: on an object a 3D effect can't take, the dialog says why, and OK, which could only fail, is off.
#[test]
fn a_refused_3d_effect_says_why_and_turns_ok_off() {
let mut h = Harness::extrude_dialog(&an_image(), true);
assert!(!h.ok_is_on());
assert!(h.shows("can't build a solid from an image"));
assert!(!h.shows("effect.apply"), "the reason is written without the command's id");
let mut h = ThreeD::open(EXTRUDE, &an_image(), true);
let Some(HeldOk::Refused(reason)) = h.held() else { panic!("the dialog is not refused") };
assert!(!reason.as_str().is_empty());
assert!(!reason.as_str().contains("effect.apply"), "the reason is written without the command's id");
let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
h.frame(vec![enter], Modifiers::NONE);
assert!(h.app.ui.dialog.is_some());
assert!(h.is_open());
}
/// With Preview off from the start, nothing has tried the effect: the dialog still finds out,
/// and trying it leaves no preview open.
/// With Preview off from the start, nothing has tried the effect: the pump still finds the refusal, and trying it
/// leaves no preview open.
#[test]
fn a_refused_3d_effect_is_found_with_preview_off() {
let mut h = Harness::extrude_dialog(&an_image(), false);
assert!(!h.ok_is_on());
assert!(h.shows("can't build a solid from an image"));
let h = ThreeD::open(EXTRUDE, &an_image(), false);
assert!(matches!(h.held(), Some(HeldOk::Refused(_))));
assert!(!h.app.session.in_interaction());
}
/// With Preview off, trying the values waits for another interaction to end: trying them during
/// one would replace its preview and cancel it.
/// With Preview off, trying the values waits for another interaction to end: trying them during one would replace
/// its preview and cancel it.
#[test]
fn a_3d_effect_with_preview_off_leaves_another_interaction_alone() {
let mut h = Harness::extrude_dialog(&an_image(), false);
let mut h = ThreeD::open(EXTRUDE, &an_image(), false);
h.app.session.begin_interaction("Drag").unwrap();
let d = h.app.ui.dialog.as_mut().unwrap();
d.fields.remove("__tried");
d.fields.remove(dialogs::form::REFUSED);
if let Some(session) = h.app.three_d_dialog.as_mut() {
session.tried = None;
}
h.settle();
assert!(h.app.session.in_interaction(), "the other interaction goes on");
assert!(h.ok_is_on(), "nothing has tried the values yet");
assert!(!matches!(h.held(), Some(HeldOk::Refused(_))), "nothing has tried the values yet");
h.app.session.cancel_interaction().unwrap();
assert!(h.shows("can't build a solid from an image"));
assert!(!h.ok_is_on());
h.settle();
assert!(matches!(h.held(), Some(HeldOk::Refused(_))));
assert!(!h.app.session.in_interaction());
}
/// An object the effect can take keeps OK on, with Preview on or off, and shows no reason.
#[test]
fn an_accepted_3d_effect_keeps_ok_on() {
let build = [("shape.rectangle", json!({"x":60,"y":60,"width":100,"height":100}))];
for on in [true, false] {
let mut h = Harness::extrude_dialog(&build, on);
assert!(h.ok_is_on(), "Preview {on}");
assert!(!h.shows("requires a path"), "Preview {on}");
assert_eq!(h.app.session.in_interaction(), on);
}
}