work on raster tools
This commit is contained in:
@@ -34,6 +34,7 @@ pub mod group_layers;
|
||||
pub mod raster_stroke;
|
||||
pub mod raster_fill;
|
||||
pub mod move_layer;
|
||||
pub mod set_fill_paint;
|
||||
|
||||
pub use add_clip_instance::AddClipInstanceAction;
|
||||
pub use add_effect::AddEffectAction;
|
||||
@@ -66,3 +67,4 @@ pub use group_layers::GroupLayersAction;
|
||||
pub use raster_stroke::RasterStrokeAction;
|
||||
pub use raster_fill::RasterFillAction;
|
||||
pub use move_layer::MoveLayerAction;
|
||||
pub use set_fill_paint::SetFillPaintAction;
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Action that changes the fill of one or more DCEL faces.
|
||||
//!
|
||||
//! Handles both solid-colour and gradient fills, clearing the other type so they
|
||||
//! don't coexist on a face.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::dcel::FaceId;
|
||||
use crate::document::Document;
|
||||
use crate::gradient::ShapeGradient;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::shape::ShapeColor;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Snapshot of one face's fill state (both types) for undo.
|
||||
#[derive(Clone)]
|
||||
struct OldFill {
|
||||
face_id: FaceId,
|
||||
color: Option<ShapeColor>,
|
||||
gradient: Option<ShapeGradient>,
|
||||
}
|
||||
|
||||
/// Action that sets a solid-colour *or* gradient fill on a set of faces,
|
||||
/// clearing the other fill type.
|
||||
pub struct SetFillPaintAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
new_color: Option<ShapeColor>,
|
||||
new_gradient: Option<ShapeGradient>,
|
||||
old_fills: Vec<OldFill>,
|
||||
description: &'static str,
|
||||
}
|
||||
|
||||
impl SetFillPaintAction {
|
||||
/// Set a solid fill (clears any gradient on the same faces).
|
||||
pub fn solid(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
color: Option<ShapeColor>,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
face_ids,
|
||||
new_color: color,
|
||||
new_gradient: None,
|
||||
old_fills: Vec::new(),
|
||||
description: "Set fill colour",
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a gradient fill (clears any solid colour on the same faces).
|
||||
pub fn gradient(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
gradient: Option<ShapeGradient>,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
face_ids,
|
||||
new_color: None,
|
||||
new_gradient: gradient,
|
||||
old_fills: Vec::new(),
|
||||
description: "Set gradient fill",
|
||||
}
|
||||
}
|
||||
|
||||
fn get_dcel_mut<'a>(
|
||||
document: &'a mut Document,
|
||||
layer_id: &Uuid,
|
||||
time: f64,
|
||||
) -> Result<&'a mut crate::dcel::Dcel, String> {
|
||||
let layer = document
|
||||
.get_layer_mut(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => vl
|
||||
.dcel_at_time_mut(time)
|
||||
.ok_or_else(|| format!("No keyframe at time {}", time)),
|
||||
_ => Err("Not a vector layer".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetFillPaintAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let dcel = Self::get_dcel_mut(document, &self.layer_id, self.time)?;
|
||||
self.old_fills.clear();
|
||||
|
||||
for &fid in &self.face_ids {
|
||||
let face = dcel.face(fid);
|
||||
self.old_fills.push(OldFill {
|
||||
face_id: fid,
|
||||
color: face.fill_color,
|
||||
gradient: face.gradient_fill.clone(),
|
||||
});
|
||||
|
||||
let face_mut = dcel.face_mut(fid);
|
||||
// Setting a gradient clears solid colour and vice-versa.
|
||||
if self.new_gradient.is_some() || self.new_color.is_none() {
|
||||
face_mut.fill_color = self.new_color;
|
||||
face_mut.gradient_fill = self.new_gradient.clone();
|
||||
} else {
|
||||
face_mut.fill_color = self.new_color;
|
||||
face_mut.gradient_fill = None;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let dcel = Self::get_dcel_mut(document, &self.layer_id, self.time)?;
|
||||
for old in &self.old_fills {
|
||||
let face = dcel.face_mut(old.face_id);
|
||||
face.fill_color = old.color;
|
||||
face.gradient_fill = old.gradient.clone();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
self.description.to_string()
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,8 @@ pub struct Face {
|
||||
pub image_fill: Option<uuid::Uuid>,
|
||||
pub fill_rule: FillRule,
|
||||
#[serde(default)]
|
||||
pub gradient_fill: Option<crate::gradient::ShapeGradient>,
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
@@ -241,6 +243,7 @@ impl Dcel {
|
||||
fill_color: None,
|
||||
image_fill: None,
|
||||
fill_rule: FillRule::NonZero,
|
||||
gradient_fill: None,
|
||||
deleted: false,
|
||||
};
|
||||
let debug_recorder = if std::env::var("DAW_DCEL_RECORD").is_ok() {
|
||||
@@ -372,6 +375,7 @@ impl Dcel {
|
||||
fill_color: None,
|
||||
image_fill: None,
|
||||
fill_rule: FillRule::NonZero,
|
||||
gradient_fill: None,
|
||||
deleted: false,
|
||||
};
|
||||
if let Some(idx) = self.free_faces.pop() {
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Gradient types for vector and raster fills.
|
||||
|
||||
use crate::shape::ShapeColor;
|
||||
use kurbo::Point;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vello::peniko::{self, Brush, Extend, Gradient};
|
||||
|
||||
// ── Stop ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// One colour stop in a gradient.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientStop {
|
||||
/// Normalised position in [0.0, 1.0].
|
||||
pub position: f32,
|
||||
pub color: ShapeColor,
|
||||
}
|
||||
|
||||
// ── Kind / Extend ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Whether the gradient transitions along a line or radiates from a point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum GradientType {
|
||||
#[default]
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// Behaviour outside the gradient's natural [0, 1] range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum GradientExtend {
|
||||
/// Clamp to edge colour (default).
|
||||
#[default]
|
||||
Pad,
|
||||
/// Mirror the gradient.
|
||||
Reflect,
|
||||
/// Repeat the gradient.
|
||||
Repeat,
|
||||
}
|
||||
|
||||
impl From<GradientExtend> for Extend {
|
||||
fn from(e: GradientExtend) -> Self {
|
||||
match e {
|
||||
GradientExtend::Pad => Extend::Pad,
|
||||
GradientExtend::Reflect => Extend::Reflect,
|
||||
GradientExtend::Repeat => Extend::Repeat,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── ShapeGradient ────────────────────────────────────────────────────────────
|
||||
|
||||
/// A serialisable gradient description.
|
||||
///
|
||||
/// Stops are kept sorted by position (ascending). There are always ≥ 2 stops.
|
||||
///
|
||||
/// *Rendering*: call [`to_peniko_brush`](ShapeGradient::to_peniko_brush) with
|
||||
/// explicit start/end canvas-space points. For vector faces the caller derives
|
||||
/// the points from the bounding box + `angle`; for the raster tool the caller
|
||||
/// uses the drag start/end directly.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ShapeGradient {
|
||||
pub kind: GradientType,
|
||||
/// Colour stops, sorted by position.
|
||||
pub stops: Vec<GradientStop>,
|
||||
/// Angle in degrees for Linear (0 = left→right, 90 = top→bottom).
|
||||
/// Ignored for Radial.
|
||||
pub angle: f32,
|
||||
pub extend: GradientExtend,
|
||||
}
|
||||
|
||||
impl Default for ShapeGradient {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: GradientType::Linear,
|
||||
stops: vec![
|
||||
GradientStop { position: 0.0, color: ShapeColor::rgba(0, 0, 0, 255) },
|
||||
GradientStop { position: 1.0, color: ShapeColor::rgba(0, 0, 0, 0) },
|
||||
],
|
||||
angle: 0.0,
|
||||
extend: GradientExtend::Pad,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ShapeGradient {
|
||||
// ── CPU evaluation ───────────────────────────────────────────────────────
|
||||
|
||||
/// Sample RGBA at `t ∈ [0,1]` by linear interpolation between adjacent stops.
|
||||
/// Stops must be sorted ascending by position.
|
||||
pub fn eval(&self, t: f32) -> [u8; 4] {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if self.stops.is_empty() {
|
||||
return [0, 0, 0, 0];
|
||||
}
|
||||
if self.stops.len() == 1 {
|
||||
let c = self.stops[0].color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
// Find first stop with position > t
|
||||
let i = self.stops.partition_point(|s| s.position <= t);
|
||||
if i == 0 {
|
||||
let c = self.stops[0].color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
if i >= self.stops.len() {
|
||||
let c = self.stops.last().unwrap().color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
let s0 = self.stops[i - 1];
|
||||
let s1 = self.stops[i];
|
||||
let span = s1.position - s0.position;
|
||||
let f = if span <= 0.0 { 0.0 } else { (t - s0.position) / span };
|
||||
fn lerp(a: u8, b: u8, f: f32) -> u8 {
|
||||
(a as f32 + (b as f32 - a as f32) * f).round().clamp(0.0, 255.0) as u8
|
||||
}
|
||||
[
|
||||
lerp(s0.color.r, s1.color.r, f),
|
||||
lerp(s0.color.g, s1.color.g, f),
|
||||
lerp(s0.color.b, s1.color.b, f),
|
||||
lerp(s0.color.a, s1.color.a, f),
|
||||
]
|
||||
}
|
||||
|
||||
/// Apply `extend` mode to a raw t value, returning t ∈ [0,1].
|
||||
pub fn apply_extend(&self, t_raw: f32) -> f32 {
|
||||
match self.extend {
|
||||
GradientExtend::Pad => t_raw.clamp(0.0, 1.0),
|
||||
GradientExtend::Repeat => {
|
||||
let t = t_raw.rem_euclid(1.0);
|
||||
if t < 0.0 { t + 1.0 } else { t }
|
||||
}
|
||||
GradientExtend::Reflect => {
|
||||
let t = t_raw.rem_euclid(2.0).abs();
|
||||
if t > 1.0 { 2.0 - t } else { t }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── GPU / peniko rendering ───────────────────────────────────────────────
|
||||
|
||||
/// Build a `peniko::Brush` from explicit start/end canvas-coordinate points.
|
||||
///
|
||||
/// `opacity` in [0,1] is multiplied into all stop alphas.
|
||||
pub fn to_peniko_brush(&self, start: Point, end: Point, opacity: f32) -> Brush {
|
||||
// Convert stops to peniko tuples.
|
||||
let peniko_stops: Vec<(f32, peniko::Color)> = self.stops.iter().map(|s| {
|
||||
let a_scaled = (s.color.a as f32 * opacity).round().clamp(0.0, 255.0) as u8;
|
||||
let col = peniko::Color::from_rgba8(s.color.r, s.color.g, s.color.b, a_scaled);
|
||||
(s.position, col)
|
||||
}).collect();
|
||||
|
||||
let extend: Extend = self.extend.into();
|
||||
|
||||
match self.kind {
|
||||
GradientType::Linear => {
|
||||
Brush::Gradient(
|
||||
Gradient::new_linear(start, end)
|
||||
.with_extend(extend)
|
||||
.with_stops(peniko_stops.as_slice()),
|
||||
)
|
||||
}
|
||||
GradientType::Radial => {
|
||||
let mid = Point::new(
|
||||
(start.x + end.x) * 0.5,
|
||||
(start.y + end.y) * 0.5,
|
||||
);
|
||||
let dx = end.x - start.x;
|
||||
let dy = end.y - start.y;
|
||||
let radius = ((dx * dx + dy * dy).sqrt() * 0.5) as f32;
|
||||
Brush::Gradient(
|
||||
Gradient::new_radial(mid, radius)
|
||||
.with_extend(extend)
|
||||
.with_stops(peniko_stops.as_slice()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ pub mod raster_layer;
|
||||
pub mod brush_settings;
|
||||
pub mod brush_engine;
|
||||
pub mod raster_draw;
|
||||
pub mod gradient;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub mod test_mode;
|
||||
|
||||
@@ -113,8 +113,14 @@ pub struct RasterKeyframe {
|
||||
/// and encoded back to PNG on save. An empty Vec means the canvas is blank (transparent).
|
||||
#[serde(skip)]
|
||||
pub raw_pixels: Vec<u8>,
|
||||
/// Set to `true` whenever `raw_pixels` changes so the GPU texture cache can re-upload.
|
||||
/// Always `true` after load; cleared by the renderer after uploading.
|
||||
#[serde(skip, default = "default_true")]
|
||||
pub texture_dirty: bool,
|
||||
}
|
||||
|
||||
fn default_true() -> bool { true }
|
||||
|
||||
impl RasterKeyframe {
|
||||
/// Returns true when the pixel buffer has been initialised (non-blank).
|
||||
pub fn has_pixels(&self) -> bool {
|
||||
|
||||
@@ -923,7 +923,25 @@ fn render_video_layer(
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a vector layer with all its clip instances and shape instances
|
||||
/// Compute start/end canvas points for a linear gradient across a bounding box.
|
||||
///
|
||||
/// The axis is centred on the bbox midpoint and oriented at `angle_deg` degrees
|
||||
/// (0 = left→right, 90 = top→bottom). The axis extends ± half the bbox diagonal
|
||||
/// so the gradient covers the entire shape regardless of angle.
|
||||
fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
let cx = bbox.center().x;
|
||||
let cy = bbox.center().y;
|
||||
let dx = bbox.width();
|
||||
let dy = bbox.height();
|
||||
// Use half the diagonal so the full gradient fits at any angle.
|
||||
let half_len = (dx * dx + dy * dy).sqrt() * 0.5;
|
||||
let rad = (angle_deg as f64).to_radians();
|
||||
let (sin, cos) = (rad.sin(), rad.cos());
|
||||
let start = kurbo::Point::new(cx - cos * half_len, cy - sin * half_len);
|
||||
let end = kurbo::Point::new(cx + cos * half_len, cy + sin * half_len);
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// Render a DCEL to a Vello scene.
|
||||
///
|
||||
/// Walks faces for fills and edges for strokes.
|
||||
@@ -942,7 +960,7 @@ pub fn render_dcel(
|
||||
if face.deleted || i == 0 {
|
||||
continue; // Skip unbounded face and deleted faces
|
||||
}
|
||||
if face.fill_color.is_none() && face.image_fill.is_none() {
|
||||
if face.fill_color.is_none() && face.image_fill.is_none() && face.gradient_fill.is_none() {
|
||||
continue; // No fill to render
|
||||
}
|
||||
|
||||
@@ -963,7 +981,19 @@ pub fn render_dcel(
|
||||
}
|
||||
}
|
||||
|
||||
// Color fill
|
||||
// Gradient fill (takes priority over solid colour fill)
|
||||
if !filled {
|
||||
if let Some(ref grad) = face.gradient_fill {
|
||||
use kurbo::{Point, Rect};
|
||||
let bbox: Rect = vello::kurbo::Shape::bounding_box(&path);
|
||||
let (start, end) = gradient_bbox_endpoints(grad.angle, bbox);
|
||||
let brush = grad.to_peniko_brush(start, end, opacity_f32);
|
||||
scene.fill(fill_rule, base_transform, &brush, None, &path);
|
||||
filled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Solid colour fill
|
||||
if !filled {
|
||||
if let Some(fill_color) = &face.fill_color {
|
||||
let alpha = ((fill_color.a as f32 / 255.0) * opacity_f32 * 255.0) as u8;
|
||||
|
||||
Reference in New Issue
Block a user