mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Implement opt-in pixel-aligned shape strokes
Align isolated integer-axis 1px stroke runs at render time while preserving stored paths, dash lengths/offsets, and curve/diagonal antialiasing. Handle filled live Line/ArrowLine geometry separately and retain rectangle corners through reversed traversal and quarter-turn transforms. Quantize eligible dash caps consistently, including fractional periods and negative offsets. Round and square caps retain their extra pixel of extent. Add model/native/PSD flag roundtrips, command validation and undo coverage, selected-shape controls, custom-shape presets, and tool preset/reset support. Document conservative fallback for unsupported widths, alignments and paths. Validation: desktop build with two jobs in standard target; cargo fmt check; cargo check --workspace; touched-crate clippy; 112 vector tests; command, selected-shape/preset/reset, native roundtrip and PSD flag tests; adversarial command panic hunt; layering checks. Manual 24MP vector render also passes. Known validation limits: the broader workspace run is not completely green (Windows junction permissions, automation cancellation, GPU timing, and font-selection tests). Targeted font-input reruns resolve localization cases. WASM std/core target is not installed. Full IO corpus and release perf checks were attempted but not completed. No blanket Photoshop rendering-parity claim.
This commit is contained in:
1 parent
8f7d916ba5
commit
194d9d4fbb
24 files changed
+1342
-29
No files matched your search
+11
-1
@@ -50,6 +50,16 @@ impl Frame {
|
||||
}
|
||||
pub fn stroke_shape(&self) -> Option<ShapeLayer> {
|
||||
let stroke = self.stroke.clone()?;
|
||||
Some(ShapeLayer { path: self.outline(), fill: None, stroke: Some(stroke), cache: None, psd_raw: None, live: None, density: 1.0, feather: 0.0 })
|
||||
Some(ShapeLayer {
|
||||
path: self.outline(),
|
||||
fill: None,
|
||||
stroke: Some(stroke),
|
||||
pixel_align_stroke: false,
|
||||
cache: None,
|
||||
psd_raw: None,
|
||||
live: None,
|
||||
density: 1.0,
|
||||
feather: 0.0,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -338,6 +338,8 @@ pub struct ShapeLayer {
|
||||
/// `None` = no fill (Photoshop's fill "none").
|
||||
pub fill: Option<Fill>,
|
||||
pub stroke: Option<ShapeStroke>,
|
||||
/// Opt-in pixel alignment; false preserves legacy stroke rendering.
|
||||
pub pixel_align_stroke: bool,
|
||||
pub live: Option<LiveShape>,
|
||||
/// Rasterized appearance (from PSD or `photocraft-vector`).
|
||||
pub cache: Option<Surface>,
|
||||
@@ -353,7 +355,17 @@ pub struct ShapeLayer {
|
||||
|
||||
impl Default for ShapeLayer {
|
||||
fn default() -> Self {
|
||||
ShapeLayer { path: Path::default(), fill: None, stroke: None, live: None, cache: None, psd_raw: None, density: 1.0, feather: 0.0 }
|
||||
ShapeLayer {
|
||||
path: Path::default(),
|
||||
fill: None,
|
||||
stroke: None,
|
||||
pixel_align_stroke: false,
|
||||
live: None,
|
||||
cache: None,
|
||||
psd_raw: None,
|
||||
density: 1.0,
|
||||
feather: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Shape Layer",
|
||||
["Layer", "New"],
|
||||
leak(format!(
|
||||
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
|
||||
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"pixelAlignStroke":bool=false,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
|
||||
)),
|
||||
has_doc,
|
||||
shape_create
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Shape",
|
||||
[],
|
||||
leak(format!(
|
||||
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
|
||||
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"pixelAlignStroke":bool?,"name":str?}} → shape.info"##
|
||||
)),
|
||||
has_layer,
|
||||
shape_edit
|
||||
|
||||
@@ -379,6 +379,7 @@ pub(super) fn shape_info(s: &Session, id: LayerId) -> Result<Value> {
|
||||
"path": path_json(&sh.path),
|
||||
"fill": sh.fill.as_ref().map(fill_json),
|
||||
"stroke": sh.stroke.as_ref().map(stroke_json),
|
||||
"pixelAlignStroke": sh.pixel_align_stroke,
|
||||
"live": sh.live.as_ref().map(live_json),
|
||||
"kind": sh.live.as_ref().map_or("path", live_kind),
|
||||
"bounds": bounds,
|
||||
@@ -443,6 +444,11 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
let pixel_align_stroke = match p.get("pixelAlignStroke") {
|
||||
None => false,
|
||||
Some(Value::Bool(enabled)) => *enabled,
|
||||
Some(_) => return Err(bad(CMD, "`pixelAlignStroke` must be a boolean")),
|
||||
};
|
||||
// Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).
|
||||
if let Some(target) = p.get("addTo").and_then(Value::as_u64) {
|
||||
let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?;
|
||||
@@ -460,7 +466,7 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return shape_info(s, id);
|
||||
}
|
||||
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
|
||||
let mut sh = ShapeLayer { path, fill, stroke, live, ..Default::default() };
|
||||
let mut sh = ShapeLayer { path, fill, stroke, live, pixel_align_stroke, ..Default::default() };
|
||||
let id = s.edit("New Shape Layer", |doc, active| {
|
||||
refresh_shape(doc, &mut sh);
|
||||
let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind)));
|
||||
@@ -539,6 +545,9 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("stroke") {
|
||||
sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?;
|
||||
}
|
||||
if let Some(value) = p.get("pixelAlignStroke") {
|
||||
sh.pixel_align_stroke = value.as_bool().ok_or_else(|| bad(CMD, "`pixelAlignStroke` must be a boolean"))?;
|
||||
}
|
||||
if let Some(n) = name {
|
||||
layer.name = n;
|
||||
}
|
||||
|
||||
@@ -383,7 +383,7 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let path = fit(&shape.path, rect, keep);
|
||||
let mut q = json!({"kind": "path", "path": path_json(&path), "name": str_param(p, "name").unwrap_or(&shape.name)});
|
||||
for k in ["fill", "stroke", "addTo", "op"] {
|
||||
for k in ["fill", "stroke", "pixelAlignStroke", "addTo", "op"] {
|
||||
if let Some(v) = p.get(k) {
|
||||
q[k] = v.clone();
|
||||
}
|
||||
@@ -485,7 +485,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Place Custom Shape",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"preset":name,"group":name?,"rect":[x,y,w,h]? (default: centred, half the canvas),"keepAspect":bool=true,"fill":…?=foreground,"stroke":…?,"name":str?,"addTo":layerId?,"op":"combine|subtract|intersect|exclude"?} → shape.info (Custom Shape tool / Shapes panel; fill and stroke as in shape.create)"##,
|
||||
params: r##"{"preset":name,"group":name?,"rect":[x,y,w,h]? (default: centred, half the canvas),"keepAspect":bool=true,"fill":…?=foreground,"stroke":…?,"pixelAlignStroke":bool=false,"name":str?,"addTo":layerId?,"op":"combine|subtract|intersect|exclude"?} → shape.info (Custom Shape tool / Shapes panel; fill and stroke as in shape.create)"##,
|
||||
enabled: has_doc,
|
||||
run: place,
|
||||
journal: true,
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn pixel_align_shape_commands_preserve_path_and_undo_and_validate_bool() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100,"background":"transparent"})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60],"stroke":{"width":1}})).unwrap();
|
||||
let legacy = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(legacy["pixelAlignStroke"], false);
|
||||
let path = legacy["path"].clone();
|
||||
let on = s.execute("shape.edit", json!({"pixelAlignStroke":true})).unwrap();
|
||||
assert_eq!(on["pixelAlignStroke"], true);
|
||||
assert_eq!(on["path"], path);
|
||||
assert!(s.execute("shape.edit", json!({"pixelAlignStroke":"true"})).is_err());
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["pixelAlignStroke"], true);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["pixelAlignStroke"], false);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["pixelAlignStroke"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_shape_presets_forward_pixel_alignment_without_changing_preset_geometry() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60]})).unwrap();
|
||||
let preset = s.execute("shape.presets.new", json!({"name":"Pixel Alignment Regression"})).unwrap();
|
||||
for value in [true, false] {
|
||||
s.execute("shape.presets.place", json!({"preset":preset["name"],"rect":[10,10,60,60],"pixelAlignStroke":value,"stroke":{"width":1}})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["pixelAlignStroke"], value);
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
|
||||
psd_raw: opt_blob(&s.psd_raw, sink),
|
||||
path: s.path.clone(),
|
||||
stroke: s.stroke.clone(),
|
||||
pixel_align_stroke: s.pixel_align_stroke,
|
||||
// Older PhotoCraft versions cannot deserialize ArrowLine.
|
||||
// The saved path preserves the arrow's visual appearance.
|
||||
live: match &s.live {
|
||||
@@ -491,10 +492,11 @@ impl Loader<'_> {
|
||||
warp: warp.clone(),
|
||||
})
|
||||
}
|
||||
ContentM::Shape { fill, cache, psd_raw, path, stroke, live, arrow_live, density, feather } => LayerContent::Shape(ShapeLayer {
|
||||
ContentM::Shape { fill, cache, psd_raw, path, stroke, pixel_align_stroke, live, arrow_live, density, feather } => LayerContent::Shape(ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: fill.clone(),
|
||||
stroke: stroke.clone(),
|
||||
pixel_align_stroke: *pixel_align_stroke,
|
||||
live: arrow_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. })).cloned().or_else(|| live.clone()),
|
||||
cache: self.opt_surface(cache)?,
|
||||
psd_raw: self.opt_blob(psd_raw)?,
|
||||
|
||||
@@ -282,6 +282,9 @@ pub enum ContentM {
|
||||
path: Path,
|
||||
#[serde(default)]
|
||||
stroke: Option<ShapeStroke>,
|
||||
/// Optional pixel alignment; absent in legacy files.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pixel_align_stroke: bool,
|
||||
#[serde(default)]
|
||||
live: Option<LiveShape>,
|
||||
/// Arrow parameters stored separately for backward compatibility.
|
||||
|
||||
@@ -156,6 +156,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
|
||||
dashes: vec![2.0, 1.0],
|
||||
dash_offset: 0.5,
|
||||
}),
|
||||
pixel_align_stroke: false,
|
||||
live: Some(LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [4.0, 0.0, 4.0, 0.0] }),
|
||||
cache: Some(cache.clone()),
|
||||
psd_raw: Some(blob(10, 30)),
|
||||
|
||||
@@ -1091,3 +1091,47 @@ fn arrow_document_is_backward_compatible() {
|
||||
let loaded = load_from_bytes(&bytes).unwrap();
|
||||
assert_eq!(loaded, doc);
|
||||
}
|
||||
#[test]
|
||||
fn pixel_align_stroke_roundtrips_and_defaults_for_legacy_files() {
|
||||
use photocraft_doc::{ShapeLayer, ShapeStroke};
|
||||
use photocraft_format::manifest::ContentM;
|
||||
|
||||
let mut doc = rich_doc(ColorMode::Rgb, SampleType::U8);
|
||||
|
||||
doc.layers.push(Layer::new(
|
||||
"Pixel aligned rectangle",
|
||||
LayerContent::Shape(ShapeLayer {
|
||||
path: photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(10.0, 10.0), (70.0, 10.0), (70.0, 70.0), (10.0, 70.0)])]),
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
pixel_align_stroke: true,
|
||||
..Default::default()
|
||||
}),
|
||||
));
|
||||
|
||||
// The enabled option survives a complete save/load cycle.
|
||||
let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
|
||||
let reopened = load_from_bytes(&bytes).unwrap();
|
||||
assert_eq!(reopened, doc);
|
||||
|
||||
let manifest = read_manifest(&bytes).unwrap();
|
||||
let layer = manifest.document.layers.iter().find(|l| l.name == "Pixel aligned rectangle").unwrap();
|
||||
|
||||
let stored = serde_json::to_value(&layer.content).unwrap();
|
||||
assert_eq!(stored["pixel_align_stroke"], true);
|
||||
|
||||
// A legacy manifest without the new property defaults to false.
|
||||
let mut legacy = stored.clone();
|
||||
legacy.as_object_mut().unwrap().remove("pixel_align_stroke");
|
||||
|
||||
let old_content: ContentM = serde_json::from_value(legacy).unwrap();
|
||||
assert!(matches!(old_content, ContentM::Shape { pixel_align_stroke: false, .. }));
|
||||
|
||||
// Disabled alignment must not add a new field to legacy-style manifests.
|
||||
let mut disabled = layer.content.clone();
|
||||
if let ContentM::Shape { pixel_align_stroke, .. } = &mut disabled {
|
||||
*pixel_align_stroke = false;
|
||||
}
|
||||
|
||||
let disabled_json = serde_json::to_value(disabled).unwrap();
|
||||
assert!(disabled_json.get("pixel_align_stroke").is_none());
|
||||
}
|
||||
@@ -209,6 +209,7 @@ pub fn vscg_bytes(f: &Fill) -> Vec<u8> {
|
||||
pub struct VstkInfo {
|
||||
pub stroke: Option<ShapeStroke>,
|
||||
pub fill_enabled: bool,
|
||||
pub pixel_align_stroke: bool,
|
||||
}
|
||||
|
||||
fn content_fill(d: &Descriptor) -> Option<Fill> {
|
||||
@@ -233,9 +234,10 @@ fn unit_px(v: Option<&Value>, dpi: f32) -> Option<f64> {
|
||||
|
||||
pub fn parse_vstk(data: &[u8], dpi: f32) -> Option<VstkInfo> {
|
||||
let d = parse_prefix_versioned(data)?;
|
||||
let pixel_align_stroke = bool_of(&d, "strokeStyleStrokeAdjust");
|
||||
let fill_enabled = !matches!(d.get("fillEnabled"), Some(Value::Boolean(false)));
|
||||
if !bool_of(&d, "strokeEnabled") {
|
||||
return Some(VstkInfo { stroke: None, fill_enabled });
|
||||
return Some(VstkInfo { stroke: None, fill_enabled, pixel_align_stroke });
|
||||
}
|
||||
let e = |k: &str| enum_of(&d, k).map(<[u8]>::to_vec).unwrap_or_default();
|
||||
let cap = match &e("strokeStyleLineCapType")[..] {
|
||||
@@ -279,7 +281,7 @@ pub fn parse_vstk(data: &[u8], dpi: f32) -> Option<VstkInfo> {
|
||||
dashes,
|
||||
dash_offset: num(d.get("strokeStyleLineDashOffset")).unwrap_or(0.0) as f32,
|
||||
};
|
||||
Some(VstkInfo { stroke: Some(stroke), fill_enabled })
|
||||
Some(VstkInfo { stroke: Some(stroke), fill_enabled, pixel_align_stroke })
|
||||
}
|
||||
|
||||
fn en(ty: &str, v: &str) -> Value {
|
||||
@@ -301,6 +303,10 @@ fn fold_stroke_color_alpha(s: &ShapeStroke) -> ShapeStroke {
|
||||
}
|
||||
|
||||
pub fn vstk_bytes(stroke: Option<&ShapeStroke>, fill_enabled: bool, dpi: f32) -> Vec<u8> {
|
||||
vstk_bytes_aligned(stroke, fill_enabled, dpi, false)
|
||||
}
|
||||
|
||||
fn vstk_bytes_aligned(stroke: Option<&ShapeStroke>, fill_enabled: bool, dpi: f32, pixel_align_stroke: bool) -> Vec<u8> {
|
||||
let default = ShapeStroke::default();
|
||||
let folded = stroke.map(fold_stroke_color_alpha);
|
||||
let s = folded.as_ref().unwrap_or(&default);
|
||||
@@ -355,7 +361,7 @@ pub fn vstk_bytes(stroke: Option<&ShapeStroke>, fill_enabled: bool, dpi: f32) ->
|
||||
),
|
||||
)
|
||||
.with("strokeStyleScaleLock", Value::Boolean(false))
|
||||
.with("strokeStyleStrokeAdjust", Value::Boolean(false))
|
||||
.with("strokeStyleStrokeAdjust", Value::Boolean(pixel_align_stroke))
|
||||
.with("strokeStyleLineDashSet", Value::List(s.dashes.iter().map(|v| Value::UnitFloat { unit: *b"#Nne", value: f64::from(*v) }).collect()))
|
||||
.with("strokeStyleBlendMode", en("BlnM", "Nrml"))
|
||||
.with("strokeStyleOpacity", Value::UnitFloat { unit: *b"#Prc", value: f64::from(s.opacity * 100.0) })
|
||||
@@ -516,6 +522,7 @@ pub fn shape_from_blocks(sh: &mut ShapeLayer, block: &dyn Fn(&[u8; 4]) -> Option
|
||||
}
|
||||
if let Some(v) = block(b"vstk").and_then(|d| parse_vstk(&d, dpi)) {
|
||||
sh.stroke = v.stroke;
|
||||
sh.pixel_align_stroke = v.pixel_align_stroke;
|
||||
if !v.fill_enabled {
|
||||
sh.fill = None;
|
||||
}
|
||||
@@ -568,13 +575,22 @@ pub fn shape_blocks(sh: &ShapeLayer, raw: &mut Vec<([u8; 4], Vec<u8>)>, w: u32,
|
||||
}
|
||||
// Stroke (+ fill enabled flag). A fill we could not decode counts as unchanged.
|
||||
let undecodable_fill = sh.fill.is_none() && present && !has_fill_block(raw);
|
||||
let same = |v: &VstkInfo| v.stroke == sh.stroke && (v.fill_enabled == sh.fill.is_some() || (v.fill_enabled && undecodable_fill));
|
||||
let same_appearance = |v: &VstkInfo| v.stroke == sh.stroke && (v.fill_enabled == sh.fill.is_some() || (v.fill_enabled && undecodable_fill));
|
||||
match find(raw, b"vstk") {
|
||||
Some(i) if parse_vstk(&raw[i].1, dpi).as_ref().is_some_and(same) => {}
|
||||
Some(i) => raw[i].1 = vstk_bytes(sh.stroke.as_ref(), sh.fill.is_some(), dpi),
|
||||
Some(i) if parse_vstk(&raw[i].1, dpi).as_ref().is_some_and(same_appearance) => {
|
||||
if let Some(mut d) = parse_prefix_versioned(&raw[i].1)
|
||||
&& bool_of(&d, "strokeStyleStrokeAdjust") != sh.pixel_align_stroke
|
||||
{
|
||||
// Toggling alignment must retain unknown stroke descriptor entries.
|
||||
d.items.retain(|(k, _)| !k.is("strokeStyleStrokeAdjust"));
|
||||
d.items.push((Id::new("strokeStyleStrokeAdjust"), Value::Boolean(sh.pixel_align_stroke)));
|
||||
raw[i].1 = VersionedDescriptor::new(d).to_bytes();
|
||||
}
|
||||
}
|
||||
Some(i) => raw[i].1 = vstk_bytes_aligned(sh.stroke.as_ref(), sh.fill.is_some(), dpi, sh.pixel_align_stroke),
|
||||
// "No fill" needs a vstk only when a fill block would otherwise paint.
|
||||
None if sh.stroke.is_some() || (sh.fill.is_none() && has_fill_block(raw)) => {
|
||||
raw.push((*b"vstk", vstk_bytes(sh.stroke.as_ref(), sh.fill.is_some(), dpi)));
|
||||
None if sh.pixel_align_stroke || sh.stroke.is_some() || (sh.fill.is_none() && has_fill_block(raw)) => {
|
||||
raw.push((*b"vstk", vstk_bytes_aligned(sh.stroke.as_ref(), sh.fill.is_some(), dpi, sh.pixel_align_stroke)));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
@@ -779,3 +795,37 @@ mod tests {
|
||||
assert_eq!(p, edited.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pixel_align_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn pixel_alignment_psd_roundtrip_including_disabled_stroke_and_unknown_entries() {
|
||||
for enabled in [false, true] {
|
||||
let mut sh = ShapeLayer { pixel_align_stroke: enabled, ..Default::default() };
|
||||
// Use a locally built path below; the stroke-disabled case matters for Line Tool.
|
||||
sh.path = Path::new(vec![Subpath::polygon(&[(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)])]);
|
||||
let mut raw = Vec::new();
|
||||
shape_blocks(&sh, &mut raw, 100, 100, 72.0);
|
||||
let mut loaded = ShapeLayer::default();
|
||||
shape_from_blocks(&mut loaded, &|key| raw.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()), 100, 100, 72.0);
|
||||
assert_eq!(loaded.pixel_align_stroke, enabled);
|
||||
let at = raw.iter().position(|(k, _)| k == b"vstk").expect("stroke settings block");
|
||||
{
|
||||
let d = parse_prefix_versioned(&raw[at].1).unwrap().with("futureStrokeKey", Value::Integer(73));
|
||||
raw[at].1 = VersionedDescriptor::new(d).to_bytes();
|
||||
sh.pixel_align_stroke = !enabled;
|
||||
shape_blocks(&sh, &mut raw, 100, 100, 72.0);
|
||||
let d = parse_prefix_versioned(&raw[at].1).unwrap();
|
||||
assert_eq!(d.get("futureStrokeKey"), Some(&Value::Integer(73)));
|
||||
assert_eq!(bool_of(&d, "strokeStyleStrokeAdjust"), !enabled);
|
||||
let unchanged = raw.clone();
|
||||
shape_blocks(&sh, &mut raw, 100, 100, 72.0);
|
||||
assert_eq!(raw, unchanged);
|
||||
}
|
||||
}
|
||||
let mut d = parse_prefix_versioned(&vstk_bytes(None, true, 72.0)).unwrap();
|
||||
d.items.retain(|(k, _)| !k.is("strokeStyleStrokeAdjust"));
|
||||
assert!(!parse_vstk(&VersionedDescriptor::new(d).to_bytes(), 72.0).unwrap().pixel_align_stroke);
|
||||
}
|
||||
}
|
||||
@@ -769,6 +769,34 @@ mod tests {
|
||||
assert_eq!(app.ui.crop_rect, Some([8.0, 0.0, 56.0, 48.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_tool_presets_roundtrip_and_reset_for_shape_and_pen_tools() {
|
||||
for tool in [
|
||||
Tool::Rectangle,
|
||||
Tool::EllipseShape,
|
||||
Tool::Triangle,
|
||||
Tool::Polygon,
|
||||
Tool::CustomShape,
|
||||
Tool::Line,
|
||||
Tool::Pen,
|
||||
Tool::CurvaturePen,
|
||||
Tool::FreeformPen,
|
||||
] {
|
||||
let (mut app, _) = app();
|
||||
app.ui.tool = tool;
|
||||
app.ui.tool_options.pixel_align_stroke = true;
|
||||
let params = new_tool_preset_params(&app, tool);
|
||||
assert_eq!(params["options"]["toolOptions"]["pixel_align_stroke"], true, "{tool:?}");
|
||||
let name = app.run("tool.presets.new", params).unwrap()["name"].as_str().unwrap().to_string();
|
||||
crate::tool_reset::reset_options(&mut app.ui.tool_options, tool);
|
||||
assert!(!app.ui.tool_options.pixel_align_stroke, "{tool:?}");
|
||||
app.ui.tool_options.feather = 11.0;
|
||||
select_tool_preset(&mut app, &name);
|
||||
assert_eq!(app.ui.tool, tool);
|
||||
assert!(app.ui.tool_options.pixel_align_stroke, "{tool:?}");
|
||||
assert_eq!(app.ui.tool_options.feather, 11.0);
|
||||
}
|
||||
}
|
||||
/// #7356: a preset made with + keeps only its own tool's options, so choosing it doesn't
|
||||
/// reset the Crop tool's Delete Cropped Pixels or the Move tool's Auto-Select.
|
||||
#[test]
|
||||
|
||||
@@ -392,7 +392,12 @@ pub fn shape_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
/// Custom Shape tool drag: places the selected shape in the dragged rect (⇧ keeps proportions).
|
||||
pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, fill: Value, stroke: Value) {
|
||||
let name = app.ui.presets_ui.shape().to_string();
|
||||
let r = run(app, "shape.presets.place", json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke}));
|
||||
let pixel_align_stroke = app.ui.tool_options.pixel_align_stroke;
|
||||
let r = run(
|
||||
app,
|
||||
"shape.presets.place",
|
||||
json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke, "pixelAlignStroke": pixel_align_stroke}),
|
||||
);
|
||||
if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) {
|
||||
let template = "No custom shape \"{name}\": pick one in the options bar or Window › Shapes";
|
||||
app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]);
|
||||
|
||||
@@ -100,6 +100,9 @@ pub struct ToolOptions {
|
||||
/// radius, polygon sides, line weight.
|
||||
pub shape_fill: bool,
|
||||
pub stroke_width: f32,
|
||||
/// Opt-in pixel alignment for new rectangle strokes.
|
||||
#[serde(default)]
|
||||
pub pixel_align_stroke: bool,
|
||||
#[serde(default)]
|
||||
pub shape_stroke: crate::shape_stroke_ui::StrokeOptions,
|
||||
/// Shape tools: the gradient the next shape's fill / stroke takes (the swatches' Gradient
|
||||
@@ -436,6 +439,7 @@ impl Default for ToolOptions {
|
||||
pen_path_op: default_pen_path_op(),
|
||||
shape_fill: true,
|
||||
stroke_width: 0.0,
|
||||
pixel_align_stroke: false,
|
||||
shape_stroke: Default::default(),
|
||||
shape_fill_gradient: None,
|
||||
shape_stroke_gradient: None,
|
||||
|
||||
@@ -21,13 +21,21 @@ struct SelectedShape {
|
||||
fill: Option<photocraft_doc::Fill>,
|
||||
stroke: Option<photocraft_doc::ShapeStroke>,
|
||||
live: Option<photocraft_doc::LiveShape>,
|
||||
pixel_align_stroke: bool,
|
||||
}
|
||||
|
||||
fn selected_shape(session: &photocraft_engine::Session) -> Option<SelectedShape> {
|
||||
let st = session.active()?;
|
||||
let layer = st.active_layer?;
|
||||
match &st.doc.layer(layer)?.content {
|
||||
LayerContent::Shape(sh) => Some(SelectedShape { doc: st.doc.id, layer, fill: sh.fill.clone(), stroke: sh.stroke.clone(), live: sh.live.clone() }),
|
||||
LayerContent::Shape(sh) => Some(SelectedShape {
|
||||
doc: st.doc.id,
|
||||
layer,
|
||||
fill: sh.fill.clone(),
|
||||
stroke: sh.stroke.clone(),
|
||||
live: sh.live.clone(),
|
||||
pixel_align_stroke: sh.pixel_align_stroke,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -95,6 +103,14 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
|
||||
o.shape_stroke = change.options;
|
||||
o.stroke_width = enabled_stroke_width(o.stroke_width);
|
||||
}
|
||||
crate::widgets::vline(ui, 22.0);
|
||||
let mut pixel_align = target.as_ref().map_or(o.pixel_align_stroke, |s| s.pixel_align_stroke);
|
||||
|
||||
if crate::widgets::checkbox(ui, &mut pixel_align, tl!("Pixel Align Stroke")).changed() {
|
||||
o.pixel_align_stroke = pixel_align;
|
||||
edit = Some(json!({"pixelAlignStroke": pixel_align}));
|
||||
}
|
||||
|
||||
match tool {
|
||||
Tool::Rectangle => {
|
||||
crate::widgets::vline(ui, 22.0);
|
||||
|
||||
@@ -214,12 +214,13 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones),
|
||||
Tool::Sponge => reset!(sponge_mode, vibrance),
|
||||
Tool::Slice => reset!(slice_style, slice_width, slice_height),
|
||||
Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete),
|
||||
Tool::CurvaturePen => reset!(vector_mode, pen_path_op),
|
||||
Tool::FreeformPen => reset!(vector_mode, pen_path_op, curve_fit),
|
||||
Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete, pixel_align_stroke),
|
||||
Tool::CurvaturePen => reset!(vector_mode, pen_path_op, pixel_align_stroke),
|
||||
Tool::FreeformPen => reset!(vector_mode, pen_path_op, curve_fit, pixel_align_stroke),
|
||||
Tool::Line => reset!(
|
||||
vector_mode,
|
||||
shape_fill,
|
||||
pixel_align_stroke,
|
||||
stroke_width,
|
||||
shape_stroke,
|
||||
shape_fill_gradient,
|
||||
@@ -234,7 +235,18 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
arrow_concavity,
|
||||
),
|
||||
Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::CustomShape => {
|
||||
reset!(vector_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight)
|
||||
reset!(
|
||||
vector_mode,
|
||||
shape_fill,
|
||||
pixel_align_stroke,
|
||||
stroke_width,
|
||||
shape_stroke,
|
||||
shape_fill_gradient,
|
||||
shape_stroke_gradient,
|
||||
corner_radius,
|
||||
polygon_sides,
|
||||
line_weight
|
||||
)
|
||||
}
|
||||
Tool::ColorSampler
|
||||
| Tool::Ruler
|
||||
|
||||
@@ -65,6 +65,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
|
||||
o.shape_stroke = change.options;
|
||||
o.stroke_width = enabled_stroke_width(o.stroke_width);
|
||||
}
|
||||
crate::widgets::vline(ui, 22.0);
|
||||
crate::widgets::checkbox(ui, &mut o.pixel_align_stroke, tl!("Pixel Align Stroke"));
|
||||
}
|
||||
crate::widgets::vline(ui, 22.0);
|
||||
path_operations_menu(app, ui);
|
||||
@@ -259,6 +261,14 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
|
||||
edit = Some(json!({"stroke": {"width": w}, "coalesce": coalesce("stroke-w")}));
|
||||
}
|
||||
});
|
||||
let mut pixel_align_stroke = sh.pixel_align_stroke;
|
||||
if crate::widgets::checkbox(ui, &mut pixel_align_stroke, tl!("Pixel Align Stroke")).changed() {
|
||||
edit = Some(json!({
|
||||
"pixelAlignStroke": pixel_align_stroke,
|
||||
"coalesce": coalesce("pixel-align-stroke")
|
||||
}));
|
||||
}
|
||||
|
||||
let style = sh.stroke.as_ref().map(crate::shape_stroke_ui::StrokeOptions::from).unwrap_or_default();
|
||||
let stroke_enabled = sh.stroke.as_ref().is_some_and(|stroke| stroke.width > 0.0);
|
||||
if let Some(change) = crate::shape_stroke_ui::button(
|
||||
|
||||
@@ -423,7 +423,17 @@ fn commit_path_current(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) ->
|
||||
stroke["color"] = json!(app.session.tools.foreground);
|
||||
stroke
|
||||
};
|
||||
app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke}))
|
||||
let pixel_align_stroke = app.ui.tool_options.pixel_align_stroke;
|
||||
app.run(
|
||||
"shape.create",
|
||||
json!({
|
||||
"kind": "path",
|
||||
"path": path,
|
||||
"fill": fill,
|
||||
"stroke": stroke,
|
||||
"pixelAlignStroke": pixel_align_stroke
|
||||
}),
|
||||
)
|
||||
} else if let Some((name, p)) =
|
||||
pen.resumes.as_ref().and_then(|r| app.session.active().and_then(|st| with_resumed_subpath(&st.doc, r, &path)).map(|p| (r.path.clone(), p)))
|
||||
{
|
||||
|
||||
@@ -124,6 +124,7 @@ pub(super) fn fill_param(app: &PhotocraftApp) -> Value {
|
||||
pub fn create_shape(app: &mut PhotocraftApp, mut geometry: Value) -> Result<Value, String> {
|
||||
geometry["fill"] = fill_param(app);
|
||||
geometry["stroke"] = stroke_param(app);
|
||||
geometry["pixelAlignStroke"] = json!(app.ui.tool_options.pixel_align_stroke);
|
||||
app.run("shape.create", geometry)
|
||||
}
|
||||
|
||||
@@ -143,6 +144,7 @@ pub(super) fn shape_preview(app: &PhotocraftApp, tool: Tool, start: [f64; 2], en
|
||||
path,
|
||||
fill: o.shape_fill.then(|| tool_paint(app, false)),
|
||||
stroke: (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, tool_paint(app, true))),
|
||||
pixel_align_stroke: o.pixel_align_stroke,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1481,3 +1481,33 @@ fn path_rows_dragged_onto_the_trash_are_deleted() {
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
assert_eq!((doc.layers.len(), doc.paths.len()), (layers, 1), "nothing is deleted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_checkbox_edits_selected_shape_and_undo_restores_its_value() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = app();
|
||||
finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [120.0, 100.0], Default::default());
|
||||
// The selected layer, rather than the next-shape preference, supplies the checkbox.
|
||||
app.ui.tool_options.pixel_align_stroke = true;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1600.0, 48.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
ui.horizontal_centered(|ui| options_bar(app, ui, Tool::Rectangle));
|
||||
}
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);
|
||||
h.run_steps(4);
|
||||
|
||||
h.get_by_label("Pixel Align Stroke").click();
|
||||
h.run_steps(3);
|
||||
let st = h.state().session.active().unwrap();
|
||||
let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
assert!(shape.pixel_align_stroke);
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
let st = h.state().session.active().unwrap();
|
||||
let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
assert!(!shape.pixel_align_stroke);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ pub mod edit;
|
||||
pub mod feather;
|
||||
pub mod flatten;
|
||||
pub mod map;
|
||||
mod pixel_align;
|
||||
pub mod raster;
|
||||
pub mod shapes;
|
||||
pub mod stroke;
|
||||
@@ -571,10 +572,13 @@ impl FillCoverage {
|
||||
|
||||
/// Everything needed to render a shape layer, compiled once.
|
||||
pub struct CompiledShape {
|
||||
pixel_stroke: pixel_align::PixelRuns,
|
||||
pixel_dash_caps: pixel_align::PixelRuns,
|
||||
pixel_dash_threshold: f32,
|
||||
fill: Option<(FillCoverage, Paint)>,
|
||||
stroke: Option<(Rasterizer, Paint, f32)>,
|
||||
/// Fill area used to clip inside/outside strokes.
|
||||
align: Option<(Rasterizer, bool)>,
|
||||
align: Option<(Rasterizer, bool, f32)>,
|
||||
bounds: Option<Rect>,
|
||||
}
|
||||
|
||||
@@ -594,18 +598,39 @@ impl CompiledShape {
|
||||
let area = fill_rasterizer(&shape.path, tol);
|
||||
let mut bounds = None;
|
||||
let fill = shape.fill.as_ref().map(|f| {
|
||||
let coverage = FillCoverage::new(shape, &area, coverage);
|
||||
let aligned = pixel_align::line_fill_path(shape).map(|p| fill_rasterizer(&p, tol));
|
||||
let coverage = FillCoverage::new(shape, aligned.as_ref().unwrap_or(&area), coverage);
|
||||
bounds = coverage.bounds();
|
||||
(coverage, Paint::from_fill(f, pb, cb))
|
||||
});
|
||||
let all_closed = shape.path.subpaths.iter().all(|s| s.closed);
|
||||
let mut align = None;
|
||||
let mut pixel_stroke = pixel_align::PixelRuns::stroke(shape, tol);
|
||||
// The stroker's round caps preserve circular area. Their half-circle
|
||||
// outside an integer dash boundary has area pi/8 at width 1. Use that
|
||||
// tie instead of 1/2, retaining the caps' extra pixel of raster length.
|
||||
let pixel_dash_threshold =
|
||||
if shape.stroke.as_ref().is_some_and(|s| s.cap == photocraft_doc::LineCap::Round) { std::f32::consts::PI / 8.0 } else { 0.5 };
|
||||
let pixel_dash_caps = if shape.stroke.as_ref().is_some_and(|s| !s.dashes.is_empty()) {
|
||||
pixel_align::PixelRuns::stroke(shape, tol)
|
||||
} else {
|
||||
pixel_align::PixelRuns::default()
|
||||
};
|
||||
let stroke = shape.stroke.as_ref().filter(|s| s.width > 0.0 && s.opacity > 0.0).map(|s| {
|
||||
let mut st = stroke_style(s);
|
||||
let pixel_aligned_center =
|
||||
shape.pixel_align_stroke && s.align == StrokeAlign::Center && s.width == 1.0 && pixel_align::integer_rectangle(&shape.path);
|
||||
|
||||
if all_closed && s.align != StrokeAlign::Center {
|
||||
// Inside/outside strokes: a centred stroke twice as wide, clipped by the fill area.
|
||||
st.width *= 2.0;
|
||||
align = Some((area.clone(), s.align == StrokeAlign::Inside));
|
||||
align = Some((area.clone(), s.align == StrokeAlign::Inside, 1.0));
|
||||
}
|
||||
if pixel_aligned_center {
|
||||
pixel_stroke = pixel_align::PixelRuns::default();
|
||||
// Preserve dash positions from the original vector path.
|
||||
// Select the interior pixel row for crisp 1px strokes.
|
||||
align = Some((area.clone(), true, 2.0));
|
||||
}
|
||||
let r = stroke_rasterizer(&shape.path, &st, tol);
|
||||
let sb = r.pixel_bounds();
|
||||
@@ -618,7 +643,7 @@ impl CompiledShape {
|
||||
if shape.path.inverted && shape.fill.is_some() {
|
||||
bounds = Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4));
|
||||
}
|
||||
CompiledShape { fill, stroke, align, bounds }
|
||||
CompiledShape { fill, stroke, align, bounds, pixel_stroke, pixel_dash_caps, pixel_dash_threshold }
|
||||
}
|
||||
|
||||
/// Pixel bounds of the rendering (`None` = nothing visible).
|
||||
@@ -644,12 +669,15 @@ impl CompiledShape {
|
||||
}
|
||||
if let Some((r, paint, opacity)) = &self.stroke {
|
||||
let mut cov = r.render(rect);
|
||||
if let Some((area, inside)) = &self.align {
|
||||
self.pixel_stroke.apply(rect, &mut cov, |region| r.render(region));
|
||||
if let Some((area, inside, scale)) = &self.align {
|
||||
let a = area.render(rect);
|
||||
for (c, f) in cov.iter_mut().zip(&a) {
|
||||
*c *= if *inside { *f } else { 1.0 - *f };
|
||||
let clip = if *inside { *f } else { 1.0 - *f };
|
||||
*c = (*c * clip * *scale).min(1.0);
|
||||
}
|
||||
}
|
||||
self.pixel_dash_caps.sharpen_dash_caps(rect, &mut cov, self.pixel_dash_threshold, |region| r.render(region));
|
||||
for (i, (o, c)) in out.iter_mut().zip(&cov).enumerate() {
|
||||
if *c <= 0.0 {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Coverage-only alignment of one-pixel straight runs. Geometry and dash arc lengths are
|
||||
//! never rounded. Curve tangencies and joins retain their original area antialiasing.
|
||||
use photocraft_doc::{LiveShape, Path, ShapeLayer, StrokeAlign};
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
// Trigonometric live shapes and quarter-turn transforms carry tiny rounding errors.
|
||||
const ALIGN_EPSILON: f64 = 1e-7;
|
||||
type CleanLine = (Vec<(f64, f64)>, Vec<bool>);
|
||||
fn same(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() <= ALIGN_EPSILON
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PixelRuns(Vec<Run>);
|
||||
struct Run {
|
||||
horizontal: bool,
|
||||
coordinate: i32,
|
||||
start: f64,
|
||||
end: f64,
|
||||
}
|
||||
impl PixelRuns {
|
||||
/// Quantize only dash cap coverage on isolated axis runs. Sampling neighbors
|
||||
/// resolves an exact half-pixel tie consistently: round both boundaries toward
|
||||
/// increasing document coordinates. A 9px dash therefore stays 9 opaque pixels,
|
||||
/// including when its phase alternates between integer and half-integer starts.
|
||||
pub(crate) fn sharpen_dash_caps(&self, rect: Rect, coverage: &mut [f32], threshold: f32, sample: impl Fn(Rect) -> Vec<f32>) {
|
||||
let width = rect.width() as usize;
|
||||
for run in &self.0 {
|
||||
let lo = run.start.ceil() as i32;
|
||||
let hi = run.end.floor() as i32;
|
||||
let c = run.coordinate;
|
||||
let strip = if run.horizontal { Rect::new(lo, c - 1, hi, c + 1) } else { Rect::new(c - 1, lo, c + 1, hi) };
|
||||
let visible = strip.intersect(&rect);
|
||||
if visible.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let source = if run.horizontal {
|
||||
Rect::new(visible.x0.saturating_sub(1), c - 1, visible.x1.saturating_add(1), c + 1)
|
||||
} else {
|
||||
Rect::new(c - 1, visible.y0.saturating_sub(1), c + 1, visible.y1.saturating_add(1))
|
||||
};
|
||||
let values = sample(source);
|
||||
let sw = source.width() as usize;
|
||||
let sum = |p: i32| {
|
||||
let k = if run.horizontal { (p - source.x0) as usize } else { (p - source.y0) as usize * sw };
|
||||
let adjacent = if run.horizontal { k + sw } else { k + 1 };
|
||||
values.get(k).copied().unwrap_or(0.0) + values.get(adjacent).copied().unwrap_or(0.0)
|
||||
};
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = (y - rect.y0) as usize * width + (x - rect.x0) as usize;
|
||||
let Some(out) = coverage.get_mut(index) else {
|
||||
continue;
|
||||
};
|
||||
// The normal alignment / rectangle clip already selects the row.
|
||||
if *out <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let p = if run.horizontal { x } else { y };
|
||||
let value = sum(p);
|
||||
*out = if (value - threshold).abs() <= 1e-5 {
|
||||
f32::from(sum(p.saturating_sub(1)) > sum(p.saturating_add(1)))
|
||||
} else {
|
||||
f32::from(value > threshold)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn stroke(shape: &ShapeLayer, tol: f64) -> Self {
|
||||
if !shape.pixel_align_stroke || !shape.stroke.as_ref().is_some_and(|s| s.width == 1.0 && s.align == StrokeAlign::Center) {
|
||||
return Self::default();
|
||||
}
|
||||
let mut runs = Self::path(&shape.path);
|
||||
if runs.0.is_empty() {
|
||||
return runs;
|
||||
}
|
||||
let Some(joins) = join_bounds(shape, tol) else {
|
||||
return Self::default();
|
||||
};
|
||||
runs.0.retain(|run| {
|
||||
joins.iter().all(|(p, radius)| {
|
||||
let (along, normal) = if run.horizontal { (p.0, p.1) } else { (p.1, p.0) };
|
||||
along + radius <= run.start
|
||||
|| along - radius >= run.end
|
||||
|| normal + radius <= f64::from(run.coordinate) - 1.0
|
||||
|| normal - radius >= f64::from(run.coordinate) + 1.0
|
||||
})
|
||||
});
|
||||
runs
|
||||
}
|
||||
fn segment(a: (f64, f64), b: (f64, f64)) -> Self {
|
||||
let horizontal = same(a.1, b.1);
|
||||
if !horizontal && !same(a.0, b.0) {
|
||||
return Self::default();
|
||||
}
|
||||
let (coordinate, start, end) = if horizontal { (a.1, a.0.min(b.0), a.0.max(b.0)) } else { (a.0, a.1.min(b.1), a.1.max(b.1)) };
|
||||
if !coordinate.is_finite()
|
||||
|| !same(coordinate, coordinate.round())
|
||||
|| coordinate <= f64::from(i32::MIN)
|
||||
|| coordinate >= f64::from(i32::MAX)
|
||||
|| !start.is_finite()
|
||||
|| !end.is_finite()
|
||||
|| end - start < 5.0
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
Self(vec![Run { horizontal, coordinate: coordinate.round() as i32, start: start + 2.0, end: end - 2.0 }])
|
||||
}
|
||||
fn path(path: &Path) -> Self {
|
||||
// Alignment is optional. Complex artwork retains its normal bounded renderer;
|
||||
// do not add quadratic compilation work to arbitrary imported paths.
|
||||
if path.subpaths.iter().map(|s| s.knots.len()).sum::<usize>() > 256 {
|
||||
return Self::default();
|
||||
}
|
||||
let segments: Vec<_> = path.subpaths.iter().flat_map(|s| s.segments()).collect();
|
||||
let mut runs = Self::default();
|
||||
for (i, [a, c1, c2, b]) in segments.iter().enumerate() {
|
||||
if !((same(a.x, b.x) && same(c1.x, a.x) && same(c2.x, a.x)) || (same(a.y, b.y) && same(c1.y, a.y) && same(c2.y, a.y))) {
|
||||
continue;
|
||||
}
|
||||
let candidate = Self::segment((a.x, a.y), (b.x, b.y));
|
||||
for run in candidate.0 {
|
||||
// Coverage belongs to the entire stroke. Leave crossing/overlapping
|
||||
// geometry alone rather than moving another segment's antialiasing.
|
||||
let isolated = segments.iter().enumerate().all(|(j, points)| i == j || isolated(&run, points, 0.75));
|
||||
if isolated {
|
||||
runs.0.push(run);
|
||||
}
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
pub(crate) fn apply(&self, rect: Rect, coverage: &mut [f32], sample: impl Fn(Rect) -> Vec<f32>) {
|
||||
let width = rect.width() as usize;
|
||||
for run in &self.0 {
|
||||
let lo = run.start.ceil() as i32;
|
||||
let hi = run.end.floor() as i32;
|
||||
let c = run.coordinate;
|
||||
let strip = if run.horizontal { Rect::new(lo, c - 1, hi, c + 1) } else { Rect::new(c - 1, lo, c + 1, hi) };
|
||||
// Sample both rows even when the caller renders tiles/bands split at the run.
|
||||
let visible = strip.intersect(&rect);
|
||||
if visible.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let source = if run.horizontal { Rect::new(visible.x0, c - 1, visible.x1, c + 1) } else { Rect::new(c - 1, visible.y0, c + 1, visible.y1) };
|
||||
let values = sample(source);
|
||||
let sw = source.width() as usize;
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = (y - rect.y0) as usize * width + (x - rect.x0) as usize;
|
||||
let k = if run.horizontal { (x - source.x0) as usize } else { (y - source.y0) as usize * sw };
|
||||
let adjacent = if run.horizontal { k + sw } else { k + 1 };
|
||||
if let (Some(out), Some(a), Some(b)) = (coverage.get_mut(index), values.get(k), values.get(adjacent)) {
|
||||
*out = if (if run.horizontal { y } else { x }) == c { (*a + *b).min(1.0) } else { 0.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Line Tool bar is a fill, so translate its render-only copy by half a pixel.
|
||||
/// Moving the whole arrow also retains antialiasing and the proportions of its heads.
|
||||
pub(crate) fn line_fill_path(shape: &ShapeLayer) -> Option<Path> {
|
||||
if !shape.pixel_align_stroke || shape.has_soft_mask() || shape.stroke.as_ref().is_some_and(|s| s.width > 0.0 && s.opacity > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let live = shape.live.as_ref()?;
|
||||
let (from, to, weight) = match live {
|
||||
LiveShape::Line { from, to, weight } | LiveShape::ArrowLine { from, to, weight, .. } => (from, to, weight),
|
||||
_ => return None,
|
||||
};
|
||||
if *weight != 1.0 || crate::shapes::live_path(live) != shape.path {
|
||||
return None;
|
||||
}
|
||||
let horizontal = same(from[1], to[1]) && !same(from[0], to[0]);
|
||||
let vertical = same(from[0], to[0]) && !same(from[1], to[1]);
|
||||
let coordinate = if horizontal { from[1] } else { from[0] };
|
||||
if (!horizontal && !vertical) || !coordinate.is_finite() || !same(coordinate, coordinate.round()) {
|
||||
return None;
|
||||
}
|
||||
Some(shape.path.transform(&photocraft_geom::Affine::translate(if vertical { 0.5 } else { 0.0 }, if horizontal { 0.5 } else { 0.0 })))
|
||||
}
|
||||
|
||||
fn isolated(run: &Run, points: &[photocraft_geom::Point; 4], padding: f64) -> bool {
|
||||
let c = f64::from(run.coordinate);
|
||||
let [a, c1, c2, b] = points;
|
||||
if a == c1 && b == c2 {
|
||||
let (n0, n1, t0, t1) = if run.horizontal { (a.y, b.y, a.x, b.x) } else { (a.x, b.x, a.y, b.y) };
|
||||
let delta = n1 - n0;
|
||||
if delta != 0.0 {
|
||||
let u = (c - 1.0 - padding - n0) / delta;
|
||||
let v = (c + 1.0 + padding - n0) / delta;
|
||||
let lo = u.min(v).max(0.0);
|
||||
let hi = u.max(v).min(1.0);
|
||||
if lo > hi {
|
||||
return true;
|
||||
}
|
||||
let p = t0 + (t1 - t0) * lo;
|
||||
let q = t0 + (t1 - t0) * hi;
|
||||
return p.max(q) + padding <= run.start || p.min(q) - padding >= run.end;
|
||||
}
|
||||
}
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in points {
|
||||
x0 = x0.min(p.x);
|
||||
y0 = y0.min(p.y);
|
||||
x1 = x1.max(p.x);
|
||||
y1 = y1.max(p.y);
|
||||
}
|
||||
if run.horizontal {
|
||||
x1 + padding <= run.start || x0 - padding >= run.end || y1 + padding <= c - 1.0 || y0 - padding >= c + 1.0
|
||||
} else {
|
||||
y1 + padding <= run.start || y0 - padding >= run.end || x1 + padding <= c - 1.0 || x0 - padding >= c + 1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognize the same rectangle after a reversed traversal or quarter-turn transform.
|
||||
/// The original path is still used for dashing and clipping.
|
||||
pub(crate) fn integer_rectangle(path: &Path) -> bool {
|
||||
if path.inverted || path.subpaths.len() != 1 {
|
||||
return false;
|
||||
}
|
||||
let Some(s) = path.subpaths.first() else {
|
||||
return false;
|
||||
};
|
||||
if !s.closed || s.knots.len() != 4 {
|
||||
return false;
|
||||
}
|
||||
let Some((x0, y0, x1, y1)) = path.control_bounds() else {
|
||||
return false;
|
||||
};
|
||||
if x1 - x0 < 2.0 || y1 - y0 < 2.0 || ![x0, y0, x1, y1].iter().all(|x| x.is_finite() && same(*x, x.round())) {
|
||||
return false;
|
||||
}
|
||||
let mut corners = 0u8;
|
||||
for k in &s.knots {
|
||||
corners |= 1 << (u8::from(same(k.anchor.x, x1)) + 2 * u8::from(same(k.anchor.y, y1)));
|
||||
if !(same(k.anchor.x, x0) || same(k.anchor.x, x1)) || !(same(k.anchor.y, y0) || same(k.anchor.y, y1)) || k.in_ctrl != k.anchor || k.out_ctrl != k.anchor
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
corners == 15 && s.segments().iter().all(|[a, _, _, b]| (same(a.x, b.x) && !same(a.y, b.y)) || (same(a.y, b.y) && !same(a.x, b.x)))
|
||||
}
|
||||
|
||||
/// Bound actual tessellated joins, including sharp interior cusps. Source control
|
||||
/// bounds alone do not contain a long miter. Use the stroker's flattening tolerance
|
||||
/// and duplicate-point policy, without modifying its path or dash calculations.
|
||||
fn join_bounds(shape: &ShapeLayer, tol: f64) -> Option<Vec<((f64, f64), f64)>> {
|
||||
let style = crate::stroke_style(shape.stroke.as_ref()?);
|
||||
if !style.miter_limit.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let flatten_tol = if tol.is_nan() { 0.1 } else { (tol * 4.0).clamp(1e-3, 0.1) };
|
||||
let lines = crate::flatten_path(&shape.path, flatten_tol);
|
||||
if lines.iter().map(|l| l.pts.len()).sum::<usize>() > 8192 {
|
||||
return None;
|
||||
}
|
||||
let mut bounds = Vec::new();
|
||||
for line in lines {
|
||||
let (points, knots) = clean_line(&line)?;
|
||||
let n = points.len();
|
||||
if n < 3 {
|
||||
bounds.extend(points.into_iter().map(|p| (p, 0.75)));
|
||||
continue;
|
||||
}
|
||||
let closed = line.closed;
|
||||
let range = if closed { 0..n } else { 1..n - 1 };
|
||||
for i in range {
|
||||
let a = *points.get((i + n - 1) % n)?;
|
||||
let b = *points.get(i)?;
|
||||
let c = *points.get((i + 1) % n)?;
|
||||
let unit = |x: f64, y: f64| {
|
||||
let length = x.hypot(y);
|
||||
(length > 0.0 && length.is_finite()).then(|| (x / length, y / length))
|
||||
};
|
||||
let u = unit(b.0 - a.0, b.1 - a.1)?;
|
||||
let v = unit(c.0 - b.0, c.1 - b.1)?;
|
||||
let cosine = ((1.0 + u.0 * v.0 + u.1 * v.1).clamp(0.0, 2.0) * 0.5).sqrt();
|
||||
let limit = if knots.get(i).copied().unwrap_or(true) { style.miter_limit.min(500.0) } else { f64::INFINITY };
|
||||
// Bevel/round joins may be smaller; this conservative envelope also
|
||||
// bounds the miter vertices of continuous curve ribbons.
|
||||
let radius = if cosine >= 1e-9 && 1.0 / cosine <= limit { (0.5 / cosine).max(0.75) } else { 0.75 };
|
||||
bounds.push((b, radius));
|
||||
}
|
||||
}
|
||||
Some(bounds)
|
||||
}
|
||||
fn clean_line(line: &crate::Polyline) -> Option<CleanLine> {
|
||||
let mut points: Vec<(f64, f64)> = Vec::new();
|
||||
let mut knots = Vec::new();
|
||||
for (i, p) in line.pts.iter().enumerate() {
|
||||
if !p.0.is_finite() || !p.1.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if points.last().is_some_and(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9) {
|
||||
continue;
|
||||
}
|
||||
points.push(*p);
|
||||
knots.push(line.knot.get(i).copied().unwrap_or(true));
|
||||
}
|
||||
if line.closed && points.len() > 1 && points.first().zip(points.last()).is_some_and(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1) < 1e-9) {
|
||||
points.pop();
|
||||
knots.pop();
|
||||
}
|
||||
Some((points, knots))
|
||||
}
|
||||
@@ -678,3 +678,626 @@ fn flatten_interrupt_stops_during_preparation() {
|
||||
assert_eq!(polls.load(Ordering::Relaxed), 6);
|
||||
assert_eq!(flatten::flatten_path_with(&path, DEFAULT_TOLERANCE, &Interrupt::NONE), Some(flatten_path(&path, DEFAULT_TOLERANCE)));
|
||||
}
|
||||
#[test]
|
||||
fn centered_one_pixel_rectangle_strokes_are_pixel_aligned() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let path = shapes::rect(10.0, 10.0, 60.0, 60.0);
|
||||
|
||||
for dashes in [vec![], vec![4.0, 2.0]] {
|
||||
let shape = ShapeLayer {
|
||||
pixel_align_stroke: true,
|
||||
path: path.clone(),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke {
|
||||
width: 1.0,
|
||||
paint: Fill::Solid(Color::BLACK),
|
||||
opacity: 1.0,
|
||||
align: StrokeAlign::Center,
|
||||
dashes: dashes.clone(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let pixels = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
let alpha = |x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
assert!(alpha(12, 10) > 0.99, "1px centered stroke should cover one full pixel row; dashes={dashes:?}, alpha={}", alpha(12, 10));
|
||||
|
||||
assert!(alpha(12, 9) < 0.01, "1px centered stroke should not bleed into the adjacent row; dashes={dashes:?}, alpha={}", alpha(12, 9));
|
||||
|
||||
if !dashes.is_empty() {
|
||||
assert!(alpha(15, 10) < 0.01, "Dash gaps must remain transparent");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn one_pixel_rectangle_alignment_preserves_other_geometry() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
|
||||
let render = |path, width| {
|
||||
let shape = ShapeLayer {
|
||||
pixel_align_stroke: true,
|
||||
path,
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke { width, paint: Fill::Solid(Color::BLACK), opacity: 1.0, align: StrokeAlign::Center, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip)
|
||||
};
|
||||
|
||||
let alpha = |pixels: &Vec<[f32; 4]>, x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
let aligned = render(shapes::rect(10.0, 10.0, 60.0, 60.0), 1.0);
|
||||
|
||||
// All four sides must occupy one fully opaque pixel row or column.
|
||||
for (x, y) in [(12, 10), (12, 69), (10, 12), (69, 12)] {
|
||||
assert!(alpha(&aligned, x, y) > 0.99, "side pixel ({x}, {y})");
|
||||
}
|
||||
|
||||
// No unwanted coverage outside the rectangle.
|
||||
for (x, y) in [(12, 9), (12, 70), (9, 12), (70, 12)] {
|
||||
assert!(alpha(&aligned, x, y) < 0.01, "outside pixel ({x}, {y})");
|
||||
}
|
||||
|
||||
// Fractional coordinates must retain their normal antialiasing.
|
||||
let fractional = render(shapes::rect(10.25, 10.25, 60.0, 60.0), 1.0);
|
||||
assert!(alpha(&fractional, 12, 9) > 0.01);
|
||||
assert!(alpha(&fractional, 12, 9) < 0.99);
|
||||
|
||||
// Even-width centered strokes must retain their existing coverage.
|
||||
let two_px = render(shapes::rect(10.0, 10.0, 60.0, 60.0), 2.0);
|
||||
assert!(alpha(&two_px, 12, 9) > 0.99);
|
||||
assert!(alpha(&two_px, 12, 10) > 0.99);
|
||||
}
|
||||
#[test]
|
||||
fn pixel_alignment_is_opt_in_and_preserves_original_path() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let original_path = shapes::rect(10.0, 10.0, 60.0, 60.0);
|
||||
|
||||
let mut shape = ShapeLayer {
|
||||
path: original_path.clone(),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke { width: 1.0, paint: Fill::Solid(Color::BLACK), opacity: 1.0, align: StrokeAlign::Center, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let render = |shape: &ShapeLayer| CompiledShape::new(shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
let alpha = |pixels: &Vec<[f32; 4]>, x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
// Legacy: original centered stroke covers two rows at 50%.
|
||||
assert!(!shape.pixel_align_stroke);
|
||||
let legacy = render(&shape);
|
||||
|
||||
assert!((alpha(&legacy, 12, 9) - 0.5).abs() < 0.01);
|
||||
assert!((alpha(&legacy, 12, 10) - 0.5).abs() < 0.01);
|
||||
|
||||
// Opt-in: one fully opaque row.
|
||||
shape.pixel_align_stroke = true;
|
||||
let aligned = render(&shape);
|
||||
|
||||
assert!(alpha(&aligned, 12, 9) < 0.01);
|
||||
assert!(alpha(&aligned, 12, 10) > 0.99);
|
||||
|
||||
// The stored vector geometry must never change.
|
||||
assert_eq!(shape.path, original_path);
|
||||
|
||||
// Disabling the option must restore the exact legacy pixels.
|
||||
shape.pixel_align_stroke = false;
|
||||
assert_eq!(render(&shape), legacy);
|
||||
}
|
||||
#[test]
|
||||
fn pixel_aligned_dashed_rectangle_has_crisp_edges_on_all_sides() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let path = shapes::rect(10.0, 10.0, 60.0, 60.0);
|
||||
|
||||
let shape = ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke {
|
||||
width: 1.0,
|
||||
paint: Fill::Solid(Color::BLACK),
|
||||
opacity: 1.0,
|
||||
align: StrokeAlign::Center,
|
||||
dashes: vec![4.0, 2.0],
|
||||
..Default::default()
|
||||
}),
|
||||
pixel_align_stroke: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let pixels = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
let alpha = |x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
let sides = [("top", 0), ("bottom", 1), ("left", 2), ("right", 3)];
|
||||
|
||||
for (name, side) in sides {
|
||||
let mut opaque = 0;
|
||||
let mut transparent = 0;
|
||||
|
||||
for p in 16..64 {
|
||||
let (x, y, ox, oy) = match side {
|
||||
0 => (p, 10, p, 9),
|
||||
1 => (p, 69, p, 70),
|
||||
2 => (10, p, 9, p),
|
||||
_ => (69, p, 70, p),
|
||||
};
|
||||
|
||||
let a = alpha(x, y);
|
||||
|
||||
assert!(a < 0.01 || a > 0.99, "{name}: partial alpha at ({x}, {y}) = {a}");
|
||||
|
||||
assert!(alpha(ox, oy) < 0.01, "{name}: stroke bleeds outside at ({ox}, {oy})");
|
||||
|
||||
if a > 0.99 {
|
||||
opaque += 1;
|
||||
} else {
|
||||
transparent += 1;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(opaque > 0, "{name}: no opaque dash segments");
|
||||
assert!(transparent > 0, "{name}: no transparent dash gaps");
|
||||
}
|
||||
|
||||
assert_eq!(shape.path, path);
|
||||
}
|
||||
#[test]
|
||||
fn pixel_aligned_dashes_round_cap_phase_but_preserve_corner_coverage() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
|
||||
for offset in [0.0, 0.5, 1.25] {
|
||||
let mut shape = ShapeLayer {
|
||||
path: shapes::rect(10.0, 10.0, 60.0, 60.0),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke {
|
||||
width: 1.0,
|
||||
paint: Fill::Solid(Color::BLACK),
|
||||
opacity: 1.0,
|
||||
align: StrokeAlign::Center,
|
||||
dashes: vec![4.0, 2.0],
|
||||
dash_offset: offset,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
shape.pixel_align_stroke = true;
|
||||
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
let alpha = |pixels: &Vec<[f32; 4]>, x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
for p in 10..70 {
|
||||
for (x, y, ox, oy) in [(p, 10, p, 9), (p, 69, p, 70), (10, p, 9, p), (69, p, 70, p)] {
|
||||
let original = alpha(&legacy, x, y);
|
||||
let actual = alpha(&aligned, x, y);
|
||||
let value = (original * 2.0).min(1.0);
|
||||
let expected = if (12..68).contains(&p) {
|
||||
let (dx, dy) = if y == 10 || y == 69 { (1, 0) } else { (0, 1) };
|
||||
let previous = alpha(&legacy, x - dx, y - dy);
|
||||
let next = alpha(&legacy, x + dx, y + dy);
|
||||
if (value - 0.5).abs() < 1e-5 {
|
||||
if previous > next { 1.0 } else { 0.0 }
|
||||
} else if value > 0.5 {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
} else {
|
||||
value
|
||||
};
|
||||
|
||||
assert!((actual - expected).abs() < 0.02, "Incorrect cap rounding at ({x}, {y}), offset={offset}: expected={expected}, actual={actual}");
|
||||
|
||||
assert!(alpha(&aligned, ox, oy) < 0.01, "Outside coverage at ({ox}, {oy}), offset={offset}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_one_pixel_live_line_is_crisp() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let path = shapes::line((10.0, 10.0), (70.0, 10.0), 1.0);
|
||||
|
||||
let mut shape = ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
stroke: None,
|
||||
live: Some(photocraft_doc::LiveShape::Line { from: [10.0, 10.0], to: [70.0, 10.0], weight: 1.0 }),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
let alpha = |pixels: &Vec<[f32; 4]>, x: usize, y: usize| pixels[y * 100 + x][3];
|
||||
|
||||
assert!((alpha(&legacy, 25, 9) - 0.5).abs() < 0.02);
|
||||
assert!((alpha(&legacy, 25, 10) - 0.5).abs() < 0.02);
|
||||
|
||||
shape.pixel_align_stroke = true;
|
||||
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
|
||||
assert!(alpha(&aligned, 25, 9) < 0.01, "Pixel alignment must remove coverage from the upper row");
|
||||
|
||||
assert!(alpha(&aligned, 25, 10) > 0.99, "The aligned line must be fully opaque");
|
||||
|
||||
assert_eq!(shape.path, path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_straight_pen_runs_preserve_fractional_dash_phase_and_tiles() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
for vertical in [false, true] {
|
||||
for offset in [-2.25, 0.0, 0.5, 1.25] {
|
||||
let pts = if vertical { vec![(20.0, 10.0), (20.0, 80.0)] } else { vec![(10.0, 20.0), (80.0, 20.0)] };
|
||||
let mut shape = ShapeLayer {
|
||||
path: Path { subpaths: vec![Subpath::polyline(&pts)], ..Default::default() },
|
||||
stroke: Some(ShapeStroke { width: 1.0, dashes: vec![4.0, 2.0], dash_offset: offset, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
let compiled = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip);
|
||||
let aligned = compiled.render_rgba(clip);
|
||||
for p in 12..78 {
|
||||
let (x, y, ox, oy) = if vertical { (20, p, 19, p) } else { (p, 20, p, 19) };
|
||||
// Independent point-sampling oracle: keep the original dash phase,
|
||||
// selecting the pixel center (ties at a start are excluded).
|
||||
let phase = (p as f64 + 0.5 - 10.0 + f64::from(offset) - 1e-7).rem_euclid(6.0);
|
||||
let expected = if phase < 4.0 { 1.0 } else { 0.0 };
|
||||
assert_eq!(aligned[y * 100 + x][3], expected, "offset={offset}, p={p}, vertical={vertical}");
|
||||
assert!(legacy[y * 100 + x][3] <= 0.5 + 1e-5);
|
||||
assert_eq!(aligned[oy * 100 + ox][3], 0.0);
|
||||
}
|
||||
for region in [Rect::new(0, 0, 20, 20), Rect::new(20, 0, 100, 20), Rect::new(0, 20, 100, 100)] {
|
||||
let tile = compiled.render_rgba(region);
|
||||
for y in region.y0..region.y1 {
|
||||
for x in region.x0..region.x1 {
|
||||
assert_eq!(tile[((y - region.y0) * region.width() as i32 + x - region.x0) as usize], aligned[(y * 100 + x) as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_keeps_curves_diagonals_and_fractional_transforms_antialiased() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
for path in [
|
||||
shapes::ellipse(10.0, 10.0, 60.0, 50.0),
|
||||
shapes::polygon(10.0, 10.0, 60.0, 60.0, 5, 0.5),
|
||||
Path { subpaths: vec![Subpath::polyline(&[(10.0, 10.0), (70.0, 60.0)])], ..Default::default() },
|
||||
shapes::rect(10.25, 10.25, 60.0, 60.0),
|
||||
] {
|
||||
let mut shape = ShapeLayer { path: path.clone(), stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }), ..Default::default() };
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert_eq!(legacy, aligned);
|
||||
assert!(aligned.iter().any(|p| p[3] > 0.01 && p[3] < 0.99));
|
||||
assert_eq!(shape.path, path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_rounded_rectangle_retains_curved_corners() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let mut shape = ShapeLayer {
|
||||
path: shapes::rounded_rect(10.0, 10.0, 60.0, 60.0, [10.0; 4]),
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert_eq!(aligned[10 * 100 + 40][3], 1.0);
|
||||
assert_eq!(aligned[9 * 100 + 40][3], 0.0);
|
||||
for y in 8..20 {
|
||||
for x in 8..20 {
|
||||
assert_eq!(aligned[y * 100 + x], legacy[y * 100 + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_crossing_custom_subpaths_keep_diagonal_coverage() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let mut shape = ShapeLayer {
|
||||
path: Path { subpaths: vec![Subpath::polyline(&[(10.0, 20.0), (80.0, 20.0)]), Subpath::polyline(&[(10.0, 10.0), (70.0, 50.0)])], ..Default::default() },
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
assert_eq!(legacy, CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_live_arrow_keeps_head_antialiasing_and_stale_metadata_is_ignored() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
for vertical in [false, true] {
|
||||
let live = photocraft_doc::LiveShape::ArrowLine {
|
||||
from: [20.0, 20.0],
|
||||
to: if vertical { [20.0, 80.0] } else { [80.0, 20.0] },
|
||||
weight: 1.0,
|
||||
start: false,
|
||||
end: true,
|
||||
width: 8.0,
|
||||
length: 10.0,
|
||||
concavity: 0.0,
|
||||
};
|
||||
let path = shapes::live_path(&live);
|
||||
let mut shape =
|
||||
ShapeLayer { path: path.clone(), live: Some(live), fill: Some(Fill::Solid(Color::BLACK)), pixel_align_stroke: true, ..Default::default() };
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
let (x, y, ox, oy) = if vertical { (20, 40, 19, 40) } else { (40, 20, 40, 19) };
|
||||
assert!(aligned[y * 100 + x][3] > 0.99);
|
||||
assert_eq!(aligned[oy * 100 + ox][3], 0.0);
|
||||
assert!(aligned.iter().any(|p| p[3] > 0.01 && p[3] < 0.99));
|
||||
assert_eq!(shape.path, path);
|
||||
shape.path = shape.path.transform(&photocraft_geom::Affine::translate(0.25, 0.25));
|
||||
let stale = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = false;
|
||||
assert_eq!(stale, CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_triangle_and_polygon_axis_edges_preserve_diagonal_antialiasing() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
for pts in [vec![(10.0, 20.0), (80.0, 20.0), (50.0, 80.0)], vec![(10.0, 20.0), (80.0, 20.0), (85.0, 60.0), (20.0, 70.0)]] {
|
||||
let mut shape =
|
||||
ShapeLayer { path: Path::new(vec![Subpath::polygon(&pts)]), stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }), ..Default::default() };
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert_eq!(aligned[20 * 100 + 40][3], 1.0);
|
||||
assert_eq!(aligned[19 * 100 + 40][3], 0.0);
|
||||
for y in 24..85 {
|
||||
for x in 0..100 {
|
||||
assert_eq!(legacy[y * 100 + x], aligned[y * 100 + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_integer_translation_and_rotation_use_document_pixel_axes() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let path = Path::new(vec![Subpath::polyline(&[(10.0, 20.0), (70.0, 20.0)])]);
|
||||
let shape = |path| ShapeLayer { path, pixel_align_stroke: true, stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }), ..Default::default() };
|
||||
let original = CompiledShape::new(&shape(path.clone()), DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
let moved = CompiledShape::new(&shape(path.transform(&photocraft_geom::Affine::translate(3.0, 4.0))), DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
for y in 0..90 {
|
||||
for x in 0..90 {
|
||||
assert_eq!(original[y * 100 + x], moved[(y + 4) * 100 + x + 3]);
|
||||
}
|
||||
}
|
||||
let rotated = path.transform(&photocraft_geom::Affine::rotate(std::f64::consts::FRAC_PI_4));
|
||||
let mut sh = shape(rotated);
|
||||
let aligned = CompiledShape::new(&sh, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
sh.pixel_align_stroke = false;
|
||||
assert_eq!(aligned, CompiledShape::new(&sh, DEFAULT_TOLERANCE, clip).render_rgba(clip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual 24 MP pixel alignment timing"]
|
||||
fn pixel_alignment_perf_24mp() {
|
||||
let clip = Rect::new(0, 0, 6000, 4000);
|
||||
let mut shape = ShapeLayer {
|
||||
path: shapes::rounded_rect(10.0, 10.0, 5980.0, 3980.0, [30.0; 4]),
|
||||
stroke: Some(ShapeStroke { width: 1.0, dashes: vec![4.0, 2.0], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
for enabled in [false, true] {
|
||||
shape.pixel_align_stroke = enabled;
|
||||
let start = std::time::Instant::now();
|
||||
let surface = render_shape(&shape, PixelFormat::RGBA8, clip);
|
||||
std::hint::black_box(surface);
|
||||
eprintln!("24 MP rounded dashed rectangle, pixel alignment={enabled}: {:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_surfaces_keep_all_depths_and_colour_models() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let shape = ShapeLayer {
|
||||
path: Path::new(vec![Subpath::polyline(&[(10.0, 20.0), (70.0, 20.0)])]),
|
||||
pixel_align_stroke: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
for sample in SampleType::ALL {
|
||||
for mode in [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Grayscale, photocraft_color::ColorMode::Cmyk] {
|
||||
let format = PixelFormat::new(mode, sample, true);
|
||||
let surface = render_shape(&shape, format, clip);
|
||||
assert_eq!(photocraft_raster::to_rgba(&format, &surface.pixel(40, 20))[3], 1.0);
|
||||
assert_eq!(photocraft_raster::to_rgba(&format, &surface.pixel(40, 19))[3], 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_live_triangle_tolerates_trigonometric_roundoff() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let live = photocraft_doc::LiveShape::Polygon { rect: [10.0, 10.0, 60.0, 60.0], sides: 3, star_ratio: 1.0, corner_radius: 0.0 };
|
||||
let shape = ShapeLayer {
|
||||
path: shapes::live_path(&live),
|
||||
live: Some(live),
|
||||
pixel_align_stroke: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let pixels = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert!(pixels[55 * 100 + 40][3] > 0.99);
|
||||
assert!(pixels[54 * 100 + 40][3] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_rectangle_corners_survive_reversed_traversal_and_quarter_turns() {
|
||||
let clip = Rect::new(-100, -100, 100, 100);
|
||||
let original = shapes::rect(10.0, 10.0, 60.0, 50.0);
|
||||
let mut reversed = original.clone();
|
||||
reversed.subpaths[0].knots.reverse();
|
||||
let rotated = original.transform(&photocraft_geom::Affine::rotate(std::f64::consts::FRAC_PI_2));
|
||||
for path in [original, reversed, rotated] {
|
||||
assert!(crate::pixel_align::integer_rectangle(&path));
|
||||
let shape =
|
||||
ShapeLayer { path: path.clone(), pixel_align_stroke: true, stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }), ..Default::default() };
|
||||
let pixels = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert!(pixels.iter().all(|p| p[3] < 0.001 || p[3] > 0.999));
|
||||
assert_eq!(shape.path, path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_alignment_does_not_sharpen_a_nearby_acute_miter() {
|
||||
let clip = Rect::new(0, 0, 100, 100);
|
||||
let path = Path::new(vec![Subpath::polyline(&[(10.0, 20.0), (80.0, 20.0)]), Subpath::polyline(&[(44.0, 50.0), (45.0, 30.0), (46.0, 50.0)])]);
|
||||
let mut shape = ShapeLayer { path, stroke: Some(ShapeStroke { width: 1.0, miter_limit: 100.0, ..Default::default() }), ..Default::default() };
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
assert_eq!(legacy, CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_dashes_have_uniform_opaque_lengths_with_half_pixel_periods() {
|
||||
let clip = Rect::new(0, 0, 256, 256);
|
||||
for length in [4.0, 9.0] {
|
||||
for gap in [12.5, 17.0] {
|
||||
for offset in [-2.25, 0.0, 0.5, 1.25] {
|
||||
for rectangle in [false, true] {
|
||||
for vertical in [false, true] {
|
||||
for reversed in [false, true] {
|
||||
let mut points = if vertical { vec![(20.0, 10.0), (20.0, 230.0)] } else { vec![(10.0, 20.0), (230.0, 20.0)] };
|
||||
if reversed {
|
||||
points.reverse();
|
||||
}
|
||||
let path = if rectangle { shapes::rect(10.0, 10.0, 220.0, 220.0) } else { Path::new(vec![Subpath::polyline(&points)]) };
|
||||
let shape = ShapeLayer {
|
||||
path: path.clone(),
|
||||
pixel_align_stroke: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, dashes: vec![length, gap], dash_offset: offset, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let compiled = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip);
|
||||
let pixels = compiled.render_rgba(clip);
|
||||
let mut runs = Vec::new();
|
||||
let mut count = 0;
|
||||
for p in 14..226 {
|
||||
let (x, y) = if rectangle {
|
||||
if vertical { (229, p) } else { (p, 10) }
|
||||
} else if vertical {
|
||||
(20, p)
|
||||
} else {
|
||||
(p, 20)
|
||||
};
|
||||
let alpha = pixels[y * 256 + x][3];
|
||||
assert!(
|
||||
alpha == 0.0 || alpha == 1.0,
|
||||
"partial dash cap: {alpha}, length={length}, gap={gap}, offset={offset}, rectangle={rectangle}, vertical={vertical}, p={p}"
|
||||
);
|
||||
if alpha == 1.0 {
|
||||
count += 1;
|
||||
} else if count > 0 {
|
||||
runs.push(count);
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
// The first scanned dash can be clipped by the scan boundary.
|
||||
assert!(runs.len() >= 5);
|
||||
for count in runs.into_iter().skip(1) {
|
||||
assert_eq!(
|
||||
count, length as usize,
|
||||
"length={length}, gap={gap}, offset={offset}, rectangle={rectangle}, vertical={vertical}, reversed={reversed}"
|
||||
);
|
||||
}
|
||||
assert_eq!(shape.path, path);
|
||||
assert_eq!(shape.stroke.as_ref().unwrap().dash_offset, offset);
|
||||
let band = Rect::new(19, 19, 232, 232);
|
||||
let tile = compiled.render_rgba(band);
|
||||
for y in band.y0..band.y1 {
|
||||
for x in band.x0..band.x1 {
|
||||
assert_eq!(tile[((y - band.y0) * band.width() as i32 + x - band.x0) as usize], pixels[(y * 256 + x) as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_round_and_square_dash_caps_have_uniform_lengths() {
|
||||
let clip = Rect::new(0, 0, 256, 256);
|
||||
for cap in [LineCap::Round, LineCap::Square] {
|
||||
for length in [4.0, 9.0] {
|
||||
for vertical in [false, true] {
|
||||
for tol in [0.001, DEFAULT_TOLERANCE, 0.015, 0.1] {
|
||||
for offset in [-2.25, 0.0, 0.001, 0.5, 1.25] {
|
||||
let points = if vertical { [(20.0, 10.0), (20.0, 240.0)] } else { [(10.0, 20.0), (240.0, 20.0)] };
|
||||
let shape = ShapeLayer {
|
||||
path: Path::new(vec![Subpath::polyline(&points)]),
|
||||
pixel_align_stroke: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, cap, dashes: vec![length, 12.5], dash_offset: offset, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let pixels = CompiledShape::new(&shape, tol, clip).render_rgba(clip);
|
||||
let mut runs = Vec::new();
|
||||
let mut count = 0;
|
||||
for p in 20..225 {
|
||||
let alpha = pixels[if vertical { p * 256 + 20 } else { 20 * 256 + p }][3];
|
||||
assert!(alpha == 0.0 || alpha == 1.0);
|
||||
if alpha == 1.0 {
|
||||
count += 1;
|
||||
} else if count > 0 {
|
||||
runs.push(count);
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
assert!(runs.len() > 5);
|
||||
for count in runs.into_iter().skip(1) {
|
||||
assert_eq!(count, length as usize + 1, "{cap:?}, offset={offset}, length={length}, tol={tol}, vertical={vertical}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aligned_rotated_dashes_preserve_legacy_antialiasing() {
|
||||
let clip = Rect::new(0, 0, 320, 320);
|
||||
for angle in [0.1, 0.37, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2 + 0.1] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
for offset in [-2.25, 0.5] {
|
||||
let path = shapes::rect(70.0, 20.0, 120.0, 80.0)
|
||||
.transform(&photocraft_geom::Affine::rotate(angle))
|
||||
.transform(&photocraft_geom::Affine::translate(110.0, 20.0));
|
||||
let mut shape = ShapeLayer {
|
||||
path: path.clone(),
|
||||
stroke: Some(ShapeStroke { width: 1.0, cap, dashes: vec![9.0, 12.5], dash_offset: offset, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let legacy = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
shape.pixel_align_stroke = true;
|
||||
let aligned = CompiledShape::new(&shape, DEFAULT_TOLERANCE, clip).render_rgba(clip);
|
||||
assert_eq!(aligned, legacy, "angle={angle}, cap={cap:?}, offset={offset}");
|
||||
assert!(aligned.iter().any(|p| p[3] > 0.0 && p[3] < 1.0));
|
||||
assert_eq!(shape.path, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# Pixel Align Stroke
|
||||
|
||||
`shape.create`, `shape.edit`, `shape.info` and `shape.presets.place` expose
|
||||
`pixelAlignStroke`. It defaults to `false`. The Shape Tools options bar and
|
||||
Properties edit the selected shape; the tool preference also controls new shapes,
|
||||
Custom Shape placement and Pen shape creation. Tool presets keep the option;
|
||||
Reset Tool restores its default for Shape Tools and all three Pen tools.
|
||||
|
||||
Alignment is a rendering option. Stored knots, control handles, live parameters,
|
||||
stroke width, dash lengths and dash offset are unchanged. Turning it off restores
|
||||
the legacy renderer. Native projects serialize the option only when enabled.
|
||||
PSD shapes map it to the `vstk` descriptor's `strokeStyleStrokeAdjust` boolean
|
||||
([Adobe Generator documentation](https://github.com/adobe-photoshop/generator-core/wiki/JSON-event-format/6a7f39780beb75b0f9988779975201f44e6978f2));
|
||||
a missing field defaults to false. Changing only this flag preserves unknown
|
||||
stroke descriptor entries. This mapping does not claim pixel-for-pixel Photoshop
|
||||
rendering parity.
|
||||
|
||||
## Rendering policy
|
||||
|
||||
- Integer-bounded, centered 1 px rectangles retain the existing interior-row
|
||||
policy, including all four sides, corners and fractional dash offsets.
|
||||
- Other centered 1 px strokes align isolated, straight horizontal/vertical runs
|
||||
whose centerline lies at an integer document coordinate. Coverage from the two
|
||||
half-covered rows/columns is combined into the positive-side pixel. On eligible
|
||||
straight runs, dashed cap coverage is selected at pixel centers; exact half-pixel
|
||||
boundary ties round toward increasing document coordinates. Integer-length
|
||||
dashes therefore have equal opaque pixel counts even with fractional dash gaps
|
||||
or offsets. Round and square caps retain their extension: a centered 1px
|
||||
stroke with a 9px dash body occupies 10 opaque pixels with these caps, versus
|
||||
9 pixels with butt caps. Round-cap selection uses the stroker's area-exact
|
||||
semicircle coverage rather than the butt-cap threshold. No semitransparent
|
||||
cap pixels remain on these runs. Stored dash
|
||||
lengths and phase are unchanged; their rasterized boundaries move by at most
|
||||
half a pixel. Fractional dash lengths can occupy adjacent integer pixel counts,
|
||||
and gaps shorter than a pixel can disappear at document resolution.
|
||||
- The same path-based rule handles Rounded Rectangle, Polygon, Triangle, Star,
|
||||
Custom Shape and Pen paths. Pure curves and diagonals keep their original
|
||||
antialiasing, including Ellipse. Flattened curve chords are never mistaken for
|
||||
straight source segments.
|
||||
- Line Tool and ArrowLine bodies are filled vector geometry. An axis-aligned live
|
||||
1 px line uses a half-pixel translation of a render-only copy of its fill path.
|
||||
Arrowheads move with the shaft and retain antialiasing and proportions. Paint
|
||||
coordinates and the stored vector geometry stay unchanged.
|
||||
- Alignment is evaluated in document pixels after geometry transforms. Fractional
|
||||
centerlines and rotated diagonals retain their original coverage. Tiled/banded
|
||||
rendering samples both neighboring rows so tile boundaries do not alter results.
|
||||
|
||||
## Deliberate limits
|
||||
|
||||
The general path rule retains legacy coverage within two pixels of source
|
||||
segment endpoints/joins, on runs shorter than five pixels, at intersecting or
|
||||
nearby geometry, on paths with more than 256 knots, and when stroke tessellation
|
||||
exceeds 8192 points. It does not force sharp
|
||||
corners on arbitrary paths. Integer rectangles use their existing corner rule.
|
||||
|
||||
Widths other than 1 px and inside/outside stroke alignment keep legacy rendering.
|
||||
Fractional-coordinate strokes are not rounded. Curves, including ellipses, are
|
||||
not snapped or thresholded. They remain antialiased.
|
||||
|
||||
Filled Line/ArrowLine alignment requires live parameters matching the current
|
||||
path, and is disabled for density/feather masks. A point edit or transform that
|
||||
drops live line metadata leaves the filled path on the legacy renderer. A Line
|
||||
Tool shape with an additional visible outline retains legacy fill placement, so
|
||||
the fill and outline remain registered. Imported PSD path quantization can also
|
||||
prevent an exact live/path match.
|
||||
|
||||
Tests cover the pending live-line regression, rectangle dash phases and corners,
|
||||
Pen dashes and tile boundaries, curved corners, polygons/triangles, curve and
|
||||
star antialiasing, crossing custom subpaths, transforms, arrowheads, stale live
|
||||
metadata, command validation/undo/redo, preset placement, tool presets/reset,
|
||||
selected-shape UI,
|
||||
native round-trip/defaults, and PSD flags/unknown entries.
|
||||
Reference in new issue
Block a user