1use pltrs_core::{Affine2D, Bbox, Path, Point, Rgba};
9
10use super::object::Obj;
11use super::writer::PdfWriter;
12use super::{image, path_ops};
13use crate::gc::{CapStyle, JoinStyle};
14use crate::image::RgbaImage;
15use crate::vector::VectorError;
16
17pub(super) const fn cap_code(cap: CapStyle) -> i64 {
19 match cap {
20 CapStyle::Butt => 0,
21 CapStyle::Round => 1,
22 CapStyle::Projecting => 2,
23 }
24}
25
26pub(super) const fn join_code(join: JoinStyle) -> i64 {
28 match join {
29 JoinStyle::Miter => 0,
30 JoinStyle::Round => 1,
31 JoinStyle::Bevel => 2,
32 }
33}
34
35pub(super) const fn paint_op(fill: bool, stroke: bool) -> &'static str {
37 match (fill, stroke) {
38 (true, true) => "B",
39 (false, true) => "S",
40 (true, false) => "f",
41 (false, false) => "n",
42 }
43}
44
45#[derive(Clone, Debug, PartialEq)]
47pub(super) struct HatchStyle {
48 pub(super) edge: Option<Rgba>,
49 pub(super) face: Option<Rgba>,
50 pub(super) pattern: String,
51 pub(super) linewidth: f64,
52}
53
54#[derive(Clone, Debug, PartialEq)]
57pub enum ShadingColors {
58 Rgb(Vec<[Rgba; 3]>),
61 Gray(Vec<[f64; 3]>),
63}
64
65#[derive(Clone, Debug)]
67struct Shading {
68 name: String,
69 id: u32,
70 points: Vec<[Point; 3]>,
71 colors: ShadingColors,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct MarkerPaint {
78 pub fill: bool,
80 pub stroke: bool,
82 pub join: JoinStyle,
84 pub cap: CapStyle,
86 pub linewidth: f64,
88}
89
90#[derive(Clone, Debug)]
92struct Marker {
93 ops: Vec<u8>,
94 fill: bool,
95 stroke: bool,
96 join: JoinStyle,
97 cap: CapStyle,
98 name: String,
99 id: u32,
100 bbox: Bbox,
101 linewidth: f64,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct TemplatePaint {
108 pub join: JoinStyle,
110 pub cap: CapStyle,
112 pub padding: f64,
114 pub filled: bool,
116 pub stroked: bool,
118}
119
120#[derive(Clone, Debug)]
122struct PathTemplate {
123 name: String,
124 path: Path,
125 transform: Affine2D,
126 id: u32,
127 paint: TemplatePaint,
128}
129
130#[derive(Clone, Copy, Debug)]
132pub(super) struct ResourceIds {
133 pub(super) fonts: u32,
134 pub(super) ext_gstates: u32,
135 pub(super) patterns: u32,
136 pub(super) shadings: u32,
137 pub(super) xobjects: u32,
138}
139
140#[derive(Debug, Default)]
142pub(super) struct Resources {
143 alpha_states: Vec<((f64, f64), String)>,
144 soft_masks: Vec<(u32, String, u32)>,
145 hatches: Vec<(HatchStyle, String)>,
146 shadings: Vec<Shading>,
147 images: Vec<(RgbaImage, String, u32)>,
148 markers: Vec<Marker>,
149 paths: Vec<PathTemplate>,
150}
151
152pub(super) fn extents(path: &Path, transform: Affine2D) -> Bbox {
154 path.transformed(&transform).extents()
155}
156
157impl Resources {
158 pub(super) fn alpha_state(&mut self, alphas: (f64, f64)) -> String {
160 if let Some((_, name)) = self.alpha_states.iter().find(|(a, _)| *a == alphas) {
161 return name.clone();
162 }
163 self.new_alpha_state(alphas)
164 }
165
166 pub(super) fn new_alpha_state(&mut self, alphas: (f64, f64)) -> String {
169 let name = format!("A{}", self.alpha_states.len() + 1);
170 self.alpha_states.push((alphas, name.clone()));
171 name
172 }
173
174 pub(super) fn soft_mask_state(&mut self, writer: &mut PdfWriter, smask: u32) -> String {
177 if let Some((_, name, _)) = self.soft_masks.iter().find(|(s, _, _)| *s == smask) {
178 return name.clone();
179 }
180 let name = format!("SM{}", self.soft_masks.len() + 1);
181 let group = writer.reserve();
182 self.soft_masks.push((smask, name.clone(), group));
183 name
184 }
185
186 pub(super) fn hatch_pattern(&mut self, style: HatchStyle) -> String {
188 if let Some((_, name)) = self.hatches.iter().find(|(s, _)| *s == style) {
189 return name.clone();
190 }
191 self.new_hatch_pattern(style)
192 }
193
194 pub(super) fn new_hatch_pattern(&mut self, style: HatchStyle) -> String {
196 let name = format!("H{}", self.hatches.len() + 1);
197 self.hatches.push((style, name.clone()));
198 name
199 }
200
201 pub(super) fn hatch_styles(&self) -> impl Iterator<Item = (&HatchStyle, &str)> {
203 self.hatches
204 .iter()
205 .map(|(style, name)| (style, name.as_str()))
206 }
207
208 pub(super) fn gouraud(
211 &mut self,
212 writer: &mut PdfWriter,
213 points: Vec<[Point; 3]>,
214 colors: ShadingColors,
215 ) -> (String, u32) {
216 let name = format!("GT{}", self.shadings.len());
217 let id = writer.reserve();
218 self.shadings.push(Shading {
219 name: name.clone(),
220 id,
221 points,
222 colors,
223 });
224 (name, id)
225 }
226
227 pub(super) fn image_names(&self) -> impl Iterator<Item = &str> {
229 self.images.iter().map(|(_, name, _)| name.as_str())
230 }
231
232 pub(super) fn image(&mut self, writer: &mut PdfWriter, image: &RgbaImage) -> String {
234 let name = format!("I{}", self.images.len() + 1);
235 let id = writer.reserve();
236 self.images.push((image.clone(), name.clone(), id));
237 name
238 }
239
240 pub(super) fn marker(
245 &mut self,
246 writer: &mut PdfWriter,
247 path: &Path,
248 transform: Affine2D,
249 paint: MarkerPaint,
250 ) -> String {
251 let ops = path_ops(path, transform, None, None, None);
252 let MarkerPaint {
253 fill,
254 stroke,
255 join,
256 cap,
257 linewidth,
258 } = paint;
259 let name = format!("M{}", self.markers.len());
260 let id = writer.reserve();
261 self.markers.push(Marker {
262 ops,
263 fill,
264 stroke,
265 join,
266 cap,
267 name: name.clone(),
268 id,
269 bbox: extents(path, transform),
270 linewidth,
271 });
272 name
273 }
274
275 pub(super) fn path_template(
277 &mut self,
278 writer: &mut PdfWriter,
279 path: &Path,
280 transform: Affine2D,
281 paint: TemplatePaint,
282 ) -> String {
283 let name = format!("P{}", self.paths.len());
284 self.paths.push(PathTemplate {
285 name: name.clone(),
286 path: path.clone(),
287 transform,
288 id: writer.reserve(),
289 paint,
290 });
291 name
292 }
293
294 pub(super) fn write(
297 &self,
298 writer: &mut PdfWriter,
299 ids: ResourceIds,
300 page_height: f64,
301 compressed: bool,
302 ) -> Result<(), VectorError> {
303 self.write_ext_gstates(writer, ids.ext_gstates)?;
304 self.write_soft_mask_groups(writer)?;
305 self.write_hatches(writer, ids.patterns, page_height)?;
306 self.write_shadings(writer, ids.shadings)?;
307 self.write_xobjects(writer, ids.xobjects)?;
308 self.write_images(writer, compressed)?;
309 self.write_markers(writer)?;
310 self.write_path_templates(writer)
311 }
312
313 pub(super) fn write_ext_gstates(
316 &self,
317 writer: &mut PdfWriter,
318 dictionary: u32,
319 ) -> Result<(), VectorError> {
320 let mut states: Vec<(String, Obj)> = self
321 .alpha_states
322 .iter()
323 .map(|((stroke, fill), name)| {
324 let state = Obj::dict([
325 ("Type", Obj::name("ExtGState")),
326 ("CA", Obj::Real(*stroke)),
327 ("ca", Obj::Real(*fill)),
328 ]);
329 (name.clone(), state)
330 })
331 .collect();
332 for (_, name, group) in &self.soft_masks {
333 let mask = Obj::dict([
334 ("Type", Obj::name("Mask")),
335 ("S", Obj::name("Luminosity")),
336 ("BC", Obj::Array(vec![Obj::Int(1)])),
337 ("G", Obj::Ref(*group)),
338 ]);
339 let state = Obj::dict([
340 ("Type", Obj::name("ExtGState")),
341 ("AIS", Obj::Bool(false)),
342 ("SMask", mask),
343 ]);
344 states.push((name.clone(), state));
345 }
346 writer.write_object(dictionary, &Obj::Dict(states))
347 }
348
349 pub(super) fn write_soft_mask_groups(&self, writer: &mut PdfWriter) -> Result<(), VectorError> {
352 for (smask, _, group) in &self.soft_masks {
353 let form = vec![
354 ("Type".to_owned(), Obj::name("XObject")),
355 ("Subtype".to_owned(), Obj::name("Form")),
356 ("FormType".to_owned(), Obj::Int(1)),
357 (
358 "Group".to_owned(),
359 Obj::dict([
360 ("S", Obj::name("Transparency")),
361 ("CS", Obj::name("DeviceGray")),
362 ]),
363 ),
364 (
365 "Matrix".to_owned(),
366 Obj::reals([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
367 ),
368 (
369 "Resources".to_owned(),
370 Obj::dict([("Shading", Obj::dict([("S", Obj::Ref(*smask))]))]),
371 ),
372 ("BBox".to_owned(), Obj::reals([0.0, 0.0, 1.0, 1.0])),
373 ];
374 writer.begin_stream(*group, None, form, None);
375 writer.output(&[Obj::name("S"), Obj::op("sh")])?;
376 writer.end_stream()?;
377 }
378 Ok(())
379 }
380
381 pub(super) fn write_xobjects(
384 &self,
385 writer: &mut PdfWriter,
386 dictionary: u32,
387 ) -> Result<(), VectorError> {
388 let mut xobjects: Vec<(String, Obj)> = Vec::new();
389 xobjects.extend(
390 self.images
391 .iter()
392 .map(|(_, n, id)| (n.clone(), Obj::Ref(*id))),
393 );
394 xobjects.extend(
395 self.markers
396 .iter()
397 .map(|m| (m.name.clone(), Obj::Ref(m.id))),
398 );
399 xobjects.extend(self.paths.iter().map(|p| (p.name.clone(), Obj::Ref(p.id))));
400 writer.write_object(dictionary, &Obj::Dict(xobjects))
401 }
402
403 pub(super) fn write_images(
406 &self,
407 writer: &mut PdfWriter,
408 compressed: bool,
409 ) -> Result<(), VectorError> {
410 for (image, _, id) in &self.images {
411 image::write_image(writer, image, *id, compressed)?;
412 }
413 Ok(())
414 }
415
416 pub(super) fn write_hatches(
418 &self,
419 writer: &mut PdfWriter,
420 dictionary: u32,
421 page_height: f64,
422 ) -> Result<(), VectorError> {
423 const SIDE: f64 = 72.0;
424 let mut patterns = Vec::new();
425 for (style, name) in &self.hatches {
426 let id = writer.reserve();
427 patterns.push((name.clone(), Obj::Ref(id)));
428 let procsets = ["PDF", "Text", "ImageB", "ImageC", "ImageI"]
429 .map(Obj::name)
430 .to_vec();
431 let dict = vec![
432 ("Type".to_owned(), Obj::name("Pattern")),
433 ("PatternType".to_owned(), Obj::Int(1)),
434 ("PaintType".to_owned(), Obj::Int(1)),
435 ("TilingType".to_owned(), Obj::Int(1)),
436 ("BBox".to_owned(), Obj::reals([0.0, 0.0, SIDE, SIDE])),
437 ("XStep".to_owned(), Obj::Real(SIDE)),
438 ("YStep".to_owned(), Obj::Real(SIDE)),
439 (
440 "Resources".to_owned(),
441 Obj::dict([("Procsets", Obj::Array(procsets))]),
442 ),
443 (
444 "Matrix".to_owned(),
445 Obj::reals([1.0, 0.0, 0.0, 1.0, 0.0, page_height * 72.0]),
446 ),
447 ];
448 writer.begin_stream(id, None, dict, None);
449 let edge = style.edge.unwrap_or(Rgba::BLACK);
450 let rgb = |c: Rgba| [Obj::Real(c.r), Obj::Real(c.g), Obj::Real(c.b)];
451 writer.output(&[rgb(edge).as_slice(), &[Obj::op("RG")]].concat())?;
452 if let Some(face) = style.face {
453 let square = [
454 Obj::op("rg"),
455 Obj::Int(0),
456 Obj::Int(0),
457 Obj::Real(SIDE),
458 Obj::Real(SIDE),
459 Obj::op("re"),
460 Obj::op("f"),
461 ];
462 writer.output(&[rgb(face).as_slice(), &square].concat())?;
463 }
464 writer.output(&[rgb(edge).as_slice(), &[Obj::op("rg")]].concat())?;
465 writer.output(&[Obj::Real(style.linewidth), Obj::op("w")])?;
466 let tile =
467 pltrs_core::hatch::pattern_path(&style.pattern, pltrs_core::hatch::DEFAULT_DENSITY)
468 .unwrap_or_default();
469 let ops = path_ops(&tile, Affine2D::scaling(SIDE, SIDE), None, None, None);
470 writer.output(&[Obj::Raw(ops)])?;
471 writer.output(&[Obj::op("B")])?;
472 writer.end_stream()?;
473 }
474 writer.write_object(dictionary, &Obj::Dict(patterns))
475 }
476
477 pub(super) fn write_shadings(
480 &self,
481 writer: &mut PdfWriter,
482 dictionary: u32,
483 ) -> Result<(), VectorError> {
484 let mut entries = Vec::new();
485 for shading in &self.shadings {
486 entries.push((shading.name.clone(), Obj::Ref(shading.id)));
487 let points: Vec<Point> = shading.points.iter().flatten().copied().collect();
488 let min = points
489 .iter()
490 .fold(Point::new(f64::INFINITY, f64::INFINITY), |a, &p| a.min(p));
491 let max = points
492 .iter()
493 .fold(Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |a, &p| {
494 a.max(p)
495 });
496 let (min, max) = (
497 Point::new(min.x - 256.0, min.y - 256.0),
498 Point::new(max.x + 256.0, max.y + 256.0),
499 );
500 let factor = Point::new(
501 f64::from(u32::MAX) / (max.x - min.x),
502 f64::from(u32::MAX) / (max.y - min.y),
503 );
504 let colors: Vec<Vec<f64>> = match &shading.colors {
505 ShadingColors::Rgb(colors) => colors
506 .iter()
507 .flatten()
508 .map(|c| vec![c.r, c.g, c.b])
509 .collect(),
510 ShadingColors::Gray(levels) => levels.iter().flatten().map(|&g| vec![g]).collect(),
511 };
512 let channels = colors.first().map_or(3, Vec::len);
513 let mut decode = vec![min.x, max.x, min.y, max.y];
514 for _ in 0..channels {
515 decode.extend([0.0, 1.0]);
516 }
517 let space = if channels == 3 {
518 "DeviceRGB"
519 } else {
520 "DeviceGray"
521 };
522 let dict = vec![
523 ("ShadingType".to_owned(), Obj::Int(4)),
524 ("BitsPerCoordinate".to_owned(), Obj::Int(32)),
525 ("BitsPerComponent".to_owned(), Obj::Int(8)),
526 ("BitsPerFlag".to_owned(), Obj::Int(8)),
527 ("ColorSpace".to_owned(), Obj::name(space)),
528 ("AntiAlias".to_owned(), Obj::Bool(false)),
529 ("Decode".to_owned(), Obj::reals(decode)),
530 ];
531 let mut data = Vec::with_capacity(points.len() * (9 + channels));
532 for (point, color) in points.iter().zip(&colors) {
533 data.push(0);
534 data.extend_from_slice(&(((point.x - min.x) * factor.x) as u32).to_be_bytes());
535 data.extend_from_slice(&(((point.y - min.y) * factor.y) as u32).to_be_bytes());
536 data.extend(color.iter().map(|&c| (c * 255.0) as u8));
537 }
538 writer.begin_stream(shading.id, None, dict, None);
539 writer.write(&data);
540 writer.end_stream()?;
541 }
542 writer.write_object(dictionary, &Obj::Dict(entries))
543 }
544
545 pub(super) fn write_markers(&self, writer: &mut PdfWriter) -> Result<(), VectorError> {
548 for marker in &self.markers {
549 let bbox = marker
551 .bbox
552 .padded(marker.linewidth * 5.0, marker.linewidth * 5.0);
553 let (x0, y0, x1, y1) = bbox.extents();
554 write_form(
555 writer,
556 marker.id,
557 [x0, y0, x1, y1],
558 (marker.join, marker.cap),
559 &marker.ops,
560 paint_op(marker.fill, marker.stroke),
561 )?;
562 }
563 Ok(())
564 }
565
566 pub(super) fn write_path_templates(&self, writer: &mut PdfWriter) -> Result<(), VectorError> {
569 for template in &self.paths {
570 let ops = path_ops(&template.path, template.transform, None, None, None);
571 let bbox = extents(&template.path, template.transform);
572 let paint = template.paint;
573 let extents = if bbox.is_finite() {
574 let (x0, y0, x1, y1) = bbox.padded(paint.padding, paint.padding).extents();
575 [x0, y0, x1, y1]
576 } else {
577 [0.0; 4]
578 };
579 write_form(
580 writer,
581 template.id,
582 extents,
583 (paint.join, paint.cap),
584 &ops,
585 paint_op(paint.filled, paint.stroked),
586 )?;
587 }
588 Ok(())
589 }
590}
591
592fn write_form(
594 writer: &mut PdfWriter,
595 id: u32,
596 bbox: [f64; 4],
597 (join, cap): (JoinStyle, CapStyle),
598 ops: &[u8],
599 paint: &str,
600) -> Result<(), VectorError> {
601 let dict = vec![
602 ("Type".to_owned(), Obj::name("XObject")),
603 ("Subtype".to_owned(), Obj::name("Form")),
604 ("BBox".to_owned(), Obj::reals(bbox)),
605 ];
606 writer.begin_stream(id, None, dict, None);
607 writer.output(&[Obj::Int(join_code(join)), Obj::op("j")])?;
608 writer.output(&[Obj::Int(cap_code(cap)), Obj::op("J")])?;
609 writer.output(&[Obj::Raw(ops.to_vec())])?;
610 writer.output(&[Obj::op(paint)])?;
611 writer.end_stream()
612}