mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
ps(write): add line style, smooth shading, and image stream helpers (#2500)
This commit is contained in:
+199
-2
@@ -297,6 +297,137 @@ pub fn clip_op(rule: FillRule, ops: PaintOps) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Line cap style for PostScript `setlinecap`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LineCap {
|
||||
Butt = 0,
|
||||
Round = 1,
|
||||
Square = 2,
|
||||
}
|
||||
|
||||
/// Line join style for PostScript `setlinejoin`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LineJoin {
|
||||
Miter = 0,
|
||||
Round = 1,
|
||||
Bevel = 2,
|
||||
}
|
||||
|
||||
/// Append `width w cap J join j miter M [dashes] offset d\n`.
|
||||
/// Non-finite miter limits default to `10.0`; finite ones below `1.0` clamp to `1.0`.
|
||||
pub fn push_line_style(s: &mut String, width: f64, cap: LineCap, join: LineJoin, miter_limit: f64, dashes: Option<(&[f64], f64)>) {
|
||||
push_num(s, width);
|
||||
let _ = write!(s, " w {} J {} j ", cap as u8, join as u8);
|
||||
push_num(s, if miter_limit.is_finite() { miter_limit.max(1.0) } else { 10.0 });
|
||||
s.push_str(" M [");
|
||||
if let Some((pattern, _)) = dashes
|
||||
&& !pattern.is_empty()
|
||||
{
|
||||
push_nums(s, pattern);
|
||||
s.pop();
|
||||
}
|
||||
s.push_str("] ");
|
||||
push_num(s, dashes.map_or(0.0, |(_, offset)| offset));
|
||||
s.push_str(" d\n");
|
||||
}
|
||||
|
||||
/// PostScript Level 3 smooth shading type.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ShadingKind {
|
||||
/// Axial (linear) shading (`/ShadingType 2`).
|
||||
Axial = 2,
|
||||
/// Radial shading (`/ShadingType 3`).
|
||||
Radial = 3,
|
||||
}
|
||||
|
||||
/// Decimals of a smooth shading's stitching function bounds (stop offsets, 0 to 1).
|
||||
const SHADING_BOUNDS_PLACES: u32 = 7;
|
||||
|
||||
/// Append a PostScript Level 3 smooth shading dictionary and `shfill` operator.
|
||||
///
|
||||
/// `stops` are `(offset, components)` pairs; consecutive pairs with strictly increasing offsets
|
||||
/// become `FunctionType 2` linear segments (wrapped in a `FunctionType 3` stitching function when
|
||||
/// there are two or more). Each stop's `components` are clamped to the first `components_len`
|
||||
/// values.
|
||||
pub fn push_shading(s: &mut String, kind: ShadingKind, color_space: &str, coords: &[f64], components_len: usize, stops: &[(f64, Vec<f32>)]) {
|
||||
let comps = |c: &[f32]| -> String {
|
||||
let mut out = String::from("[");
|
||||
for v in c.iter().take(components_len) {
|
||||
push_num(&mut out, f64::from(*v));
|
||||
out.push(' ');
|
||||
}
|
||||
if out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out.push(']');
|
||||
out
|
||||
};
|
||||
let segments: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect();
|
||||
let interp = |w: &&[(f64, Vec<f32>)]| format!("<< /FunctionType 2 /Domain [0 1] /C0 {} /C1 {} /N 1 >>", comps(&w[0].1), comps(&w[1].1));
|
||||
let function = match segments.as_slice() {
|
||||
[one] => interp(one),
|
||||
many => {
|
||||
let mut f = String::from("<< /FunctionType 3 /Domain [0 1] /Functions [\n");
|
||||
for w in many {
|
||||
f.push_str(&interp(w));
|
||||
f.push('\n');
|
||||
}
|
||||
f.push_str("] /Bounds [");
|
||||
for w in many.iter().skip(1) {
|
||||
push_num_places(&mut f, w[0].0, SHADING_BOUNDS_PLACES);
|
||||
f.push(' ');
|
||||
}
|
||||
f.push_str("] /Encode [");
|
||||
f.push_str(&"0 1 ".repeat(many.len()));
|
||||
f.push_str("] >>");
|
||||
f
|
||||
}
|
||||
};
|
||||
let _ = write!(s, "<< /ShadingType {} /ColorSpace {color_space} /Coords [", kind as u8);
|
||||
push_nums(s, coords);
|
||||
let _ = writeln!(s, "] /Extend [true true]\n/Function {function} >> shfill");
|
||||
}
|
||||
|
||||
/// Append an inline image procedure that reads its ASCII85-encoded samples from `currentfile`
|
||||
/// through `filter` (for example `/FlateDecode` or `/RunLengthDecode`) and flushes `src_name`
|
||||
/// afterwards so the interpreter resumes after the `~>` end-of-data marker.
|
||||
pub fn push_inline_image(s: &mut String, src_name: &str, prelude: &str, dict: &str, filter: &str, op: &str, ascii85: &str) {
|
||||
s.push_str(prelude);
|
||||
let _ = writeln!(s, "{{ /{src_name} currentfile /ASCII85Decode filter def");
|
||||
s.push_str(dict);
|
||||
let _ = writeln!(s, "\n/DataSource {src_name} {filter} filter >> {op}\n{src_name} flushfile }} exec");
|
||||
s.push_str(ascii85);
|
||||
}
|
||||
|
||||
/// Append a PostScript Level 3 `/ReusableStreamDecode` resource definition for `resource_name`
|
||||
/// reading its ASCII85-encoded samples from `currentfile`.
|
||||
pub fn push_reusable_image_resource(s: &mut String, src_name: &str, resource_name: &str, intent: u8, ascii85: &str) {
|
||||
let _ = writeln!(
|
||||
s,
|
||||
"{{ /{src_name} currentfile /ASCII85Decode filter def\n/{resource_name} {src_name} << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\n{src_name} flushfile }} exec"
|
||||
);
|
||||
s.push_str(ascii85);
|
||||
}
|
||||
|
||||
/// Append a PostScript Level 3 image draw referencing a `/ReusableStreamDecode` `resource_name`.
|
||||
pub fn push_reusable_image_ref(s: &mut String, resource_name: &str, prelude: &str, dict: &str, filter: &str, op: &str) {
|
||||
s.push_str(prelude);
|
||||
let _ = writeln!(s, "{resource_name} resetfile");
|
||||
s.push_str(dict);
|
||||
let _ = writeln!(s, "\n/DataSource {resource_name} {filter} filter >> {op}");
|
||||
}
|
||||
|
||||
/// Append a PostScript Level 2 image draw reading chunks from `array_name` using `index_name`.
|
||||
pub fn push_image_array_ref(s: &mut String, index_name: &str, array_name: &str, prelude: &str, dict: &str, filter: &str, op: &str) {
|
||||
s.push_str(prelude);
|
||||
let _ = writeln!(s, "/{index_name} 0 def");
|
||||
s.push_str(dict);
|
||||
let _ = writeln!(
|
||||
s,
|
||||
"\n/DataSource {{{index_name} {array_name} length lt {{{array_name} {index_name} get /{index_name} {index_name} 1 add def}} {{()}} ifelse}} {filter} filter >> {op}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `data` compressed for `FlateDecode` (zlib).
|
||||
pub fn deflate(data: &[u8]) -> Vec<u8> {
|
||||
let mut encoder = flate2::write::ZlibEncoder::new(Vec::with_capacity(data.len() / 2), flate2::Compression::default());
|
||||
@@ -315,8 +446,9 @@ pub fn inflate(data: &[u8], max: u64) -> Option<Vec<u8>> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
FillRule, PaintOps, PathOps, bytes, clip_op, deflate, fill_op, inflate, matrix, num, push_num, push_num_places, push_num_scaled, push_nums,
|
||||
push_path, string, written,
|
||||
FillRule, LineCap, LineJoin, PaintOps, PathOps, ShadingKind, bytes, clip_op, deflate, fill_op, inflate, matrix, num, push_image_array_ref,
|
||||
push_inline_image, push_line_style, push_num, push_num_places, push_num_scaled, push_nums, push_path, push_reusable_image_ref,
|
||||
push_reusable_image_resource, push_shading, string, written,
|
||||
};
|
||||
use kurbo::{Affine, BezPath};
|
||||
|
||||
@@ -624,4 +756,69 @@ mod tests {
|
||||
let hello = deflate(b"hello");
|
||||
assert_eq!(inflate(&hello, u64::MAX).as_deref(), Some(&b"hello"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_style_formats_caps_joins_miter_and_dashes() {
|
||||
let mut s = String::new();
|
||||
push_line_style(&mut s, 2.5, LineCap::Round, LineJoin::Bevel, 0.5, Some((&[6.0, 2.0], 1.0)));
|
||||
assert_eq!(s, "2.5 w 1 J 2 j 1 M [6 2] 1 d\n");
|
||||
let mut solid = String::new();
|
||||
push_line_style(&mut solid, 1.0, LineCap::Butt, LineJoin::Miter, f64::NAN, None);
|
||||
assert_eq!(solid, "1 w 0 J 0 j 10 M [] 0 d\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shading_writes_single_and_stitching_functions() {
|
||||
let mut single = String::new();
|
||||
push_shading(
|
||||
&mut single,
|
||||
ShadingKind::Axial,
|
||||
"/DeviceRGB",
|
||||
&[0.0, 0.0, 10.0, 0.0],
|
||||
3,
|
||||
&[(0.0, vec![1.0, 0.0, 0.0]), (1.0, vec![0.0, 0.0, 1.0])],
|
||||
);
|
||||
assert!(single.contains("/ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 10 0 ]"));
|
||||
assert!(single.contains("/FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1"));
|
||||
assert!(single.ends_with("shfill\n"));
|
||||
|
||||
let mut multi = String::new();
|
||||
push_shading(
|
||||
&mut multi,
|
||||
ShadingKind::Radial,
|
||||
"/DeviceGray",
|
||||
&[0.0, 0.0, 0.0, 0.0, 0.0, 5.0],
|
||||
1,
|
||||
&[(0.0, vec![0.0]), (0.123_456_7, vec![0.5]), (1.0, vec![1.0])],
|
||||
);
|
||||
assert!(multi.contains("/ShadingType 3 /ColorSpace /DeviceGray"));
|
||||
assert!(multi.contains("/FunctionType 3 /Domain [0 1] /Functions ["));
|
||||
assert!(multi.contains("/Bounds [0.1234567 ] /Encode [0 1 0 1 ]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_stream_helpers_preserve_currentfile_and_reuse_syntax() {
|
||||
let mut inline = String::new();
|
||||
push_inline_image(&mut inline, "VCsrc", "q\n", "<< /ImageType 1", "/FlateDecode", "image", "9jqo^~>\n");
|
||||
assert_eq!(
|
||||
inline,
|
||||
"q\n{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType 1\n/DataSource VCsrc /FlateDecode filter >> image\nVCsrc flushfile } exec\n9jqo^~>\n"
|
||||
);
|
||||
|
||||
let mut res = String::new();
|
||||
push_reusable_image_resource(&mut res, "VCsrc", "VCim0", 1, "9jqo^~>\n");
|
||||
assert!(res.contains("/VCim0 VCsrc << /Intent 1 /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def"));
|
||||
assert!(res.ends_with("VCsrc flushfile } exec\n9jqo^~>\n"));
|
||||
|
||||
let mut l3 = String::new();
|
||||
push_reusable_image_ref(&mut l3, "VCim0", "", "<< /ImageType 1", "/FlateDecode", "image");
|
||||
assert_eq!(l3, "VCim0 resetfile\n<< /ImageType 1\n/DataSource VCim0 /FlateDecode filter >> image\n");
|
||||
|
||||
let mut l2 = String::new();
|
||||
push_image_array_ref(&mut l2, "VCi", "VCim0", "", "<< /ImageType 1", "/RunLengthDecode", "imagemask");
|
||||
assert_eq!(
|
||||
l2,
|
||||
"/VCi 0 def\n<< /ImageType 1\n/DataSource {VCi VCim0 length lt {VCim0 VCi get /VCi VCi 1 add def} {()} ifelse} /RunLengthDecode filter >> imagemask\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user