1use brep_kernel::{
40 pmi_present, PmiAnnotationReport, PmiCamera, PmiGeometry, PmiLayoutStyle, PmiPlane, PmiPose, PmiProjection,
41 PmiReport, PmiState, PmiStatus, PmiView,
42};
43
44use super::pdf::{string_literal, PT_PER_MM};
45use super::u3d::{self, Geometry, Lines, Material, Mesh, Model, Scene};
46
47pub const CAMERA_Y_UP: bool = true;
50
51use crate::engine_state::pmi_overlay::{ARROW_PX, TEXT_PX_AT_12PT};
52
53pub fn world_per_pixel(camera: &PmiCamera) -> f64 {
56 let height = camera.viewport[1].max(1.0);
57 match camera.projection {
58 PmiProjection::Orthographic { half_height } => 2.0 * half_height / height,
59 PmiProjection::Perspective { fov_y_deg } => {
60 let d = sub(camera.target, camera.eye);
61 2.0 * (fov_y_deg.to_radians() * 0.5).tan() * dot(d, d).sqrt() / height
62 }
63 }
64}
65
66const EDGE_RGB: [u8; 3] = [0x20, 0x20, 0x24];
68const PMI_RGB: [u8; 3] = [0xD9, 0x68, 0x00];
72
73#[derive(Debug, Clone)]
75pub struct Body {
76 pub name: String,
77 pub positions: Vec<[f32; 3]>,
78 pub normals: Vec<[f32; 3]>,
79 pub indices: Vec<u32>,
81 pub triangle_colors: Vec<[u8; 3]>,
83 pub edges: Vec<Vec<[f32; 3]>>,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq)]
89pub enum Projection3d {
90 Orthographic { scale: f64 },
92 Perspective { fov_y_deg: f64 },
94}
95
96#[derive(Debug, Clone, PartialEq)]
98pub struct View3d {
99 pub id: String,
101 pub name: String,
103 pub camera: PmiCamera,
104 pub wireframe: bool,
105 pub visible: Vec<bool>,
107 pub poses: Vec<Option<[f64; 12]>>,
111 pub section: Option<([f64; 3], [f64; 3])>,
116}
117
118#[derive(Debug, Clone, PartialEq)]
121pub struct Model3d {
122 pub u3d: Vec<u8>,
123 pub nodes: Vec<String>,
124 pub views: Vec<View3d>,
125 pub annotations: usize,
127}
128
129impl Model3d {
130 pub fn view(&self, id: &str) -> Option<&View3d> {
131 self.views.iter().find(|view| view.id == id)
132 }
133}
134
135fn node_name(wanted: &str, taken: &mut std::collections::HashSet<String>) -> String {
137 let base: String = wanted
138 .chars()
139 .map(|c| if (' '..='~').contains(&c) { c } else { '_' })
140 .collect::<String>()
141 .trim()
142 .to_string();
143 let base = if base.is_empty() { "node".to_string() } else { base };
144 let mut name = base.clone();
145 let mut n = 2;
146 while !taken.insert(name.clone()) {
147 name = format!("{base} #{n}");
148 n += 1;
149 }
150 name
151}
152
153fn material_for(rgb: [u8; 3], lit_line: bool) -> Material {
154 let c = rgb.map(|v| f32::from(v) / 255.0);
155 Material {
156 name: format!("C{:02X}{:02X}{:02X}{}", rgb[0], rgb[1], rgb[2], if lit_line { "L" } else { "" }),
157 ambient: c.map(|v| v * 0.3),
158 diffuse: c,
159 specular: [0.15; 3],
160 emissive: if lit_line { c } else { [0.0; 3] },
162 reflectivity: 0.1,
163 opacity: 1.0,
164 }
165}
166
167fn material_index(scene: &mut Scene, rgb: [u8; 3], line: bool) -> usize {
169 let wanted = material_for(rgb, line);
170 if let Some(index) = scene.materials.iter().position(|m| m.name == wanted.name) {
171 return index;
172 }
173 scene.materials.push(wanted);
174 scene.materials.len() - 1
175}
176
177fn to_f32(p: [f64; 3]) -> [f32; 3] {
178 [p[0] as f32, p[1] as f32, p[2] as f32]
179}
180
181fn line_set(polylines: &[Vec<[f32; 3]>]) -> Option<Lines> {
184 let mut lines = Lines::default();
185 for polyline in polylines {
186 let mut previous: Option<u32> = None;
187 for p in polyline {
188 if !p.iter().all(|c| c.is_finite()) {
189 previous = None;
190 continue;
191 }
192 if let Some(prev) = previous {
193 if lines.positions[prev as usize] == *p {
194 continue;
195 }
196 }
197 let index = lines.positions.len() as u32;
198 lines.positions.push(*p);
199 if let Some(prev) = previous {
200 lines.segments.push(([prev, index], 0));
201 }
202 previous = Some(index);
203 }
204 }
205 (!lines.segments.is_empty()).then_some(lines)
206}
207
208fn triangle_mesh(triangles: &[[[f64; 3]; 3]]) -> Option<Mesh> {
211 let mut mesh = Mesh::default();
212 for t in triangles {
213 let u = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]];
214 let v = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
215 let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
216 let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
217 if !(len > 1e-12) {
218 continue;
219 }
220 let normal = to_f32([n[0] / len, n[1] / len, n[2] / len]);
221 let base = mesh.positions.len() as u32;
222 for corner in t {
223 mesh.positions.push(to_f32(*corner));
224 mesh.normals.push(normal);
225 }
226 mesh.triangles.push(([base, base + 1, base + 2], 0));
227 }
228 (!mesh.triangles.is_empty()).then_some(mesh)
229}
230
231use crate::geometry3d::sub3 as sub;
232use crate::geometry3d::cross3 as cross;
233use crate::geometry3d::dot3 as dot;
234use crate::geometry3d::normalize3 as unit;
235
236pub fn camera_frame(camera: &PmiCamera) -> Option<([f64; 3], [f64; 3], [f64; 3])> {
239 let forward = unit(sub(camera.target, camera.eye))?;
240 let right = unit(cross(forward, camera.up))?;
241 let up = cross(right, forward);
242 Some((right, up, forward))
243}
244
245pub fn build(bodies: &[Body], pmi: &PmiState, report: Option<&PmiReport>) -> Result<Model3d, String> {
247 let mut scene = Scene::default();
248 let mut taken = std::collections::HashSet::new();
249 enum Owner {
252 Solid(String),
253 View(String),
254 }
255 let mut owners: Vec<Owner> = Vec::new();
256
257 for body in bodies {
258 if body.indices.len() < 3 || body.positions.is_empty() {
259 continue;
260 }
261 let mut shaders: Vec<usize> = Vec::new();
262 let mut mesh = Mesh { positions: body.positions.clone(), normals: body.normals.clone(), triangles: Vec::new() };
263 for (index, corners) in body.indices.chunks_exact(3).enumerate() {
264 let rgb = body.triangle_colors.get(index).copied().unwrap_or([0xB0, 0xB4, 0xBC]);
265 let material = material_index(&mut scene, rgb, false);
266 let shading = match shaders.iter().position(|m| *m == material) {
267 Some(slot) => slot,
268 None => {
269 shaders.push(material);
270 shaders.len() - 1
271 }
272 };
273 mesh.triangles.push(([corners[0], corners[1], corners[2]], shading as u32));
274 }
275 if mesh.triangles.is_empty() {
276 continue;
277 }
278 let name = node_name(&body.name, &mut taken);
279 scene.models.push(Model { name, geometry: Geometry::Mesh(mesh), shaders, two_sided: false });
280 owners.push(Owner::Solid(body.name.clone()));
281 if let Some(lines) = line_set(&body.edges) {
282 let material = material_index(&mut scene, EDGE_RGB, true);
283 let name = node_name(&format!("{} edges", body.name), &mut taken);
284 scene.models.push(Model { name, geometry: Geometry::Lines(lines), shaders: vec![material], two_sided: false });
285 owners.push(Owner::Solid(body.name.clone()));
286 }
287 }
288 if scene.models.is_empty() {
289 return Err("the scene has no solid to show in 3D".into());
290 }
291
292 let mut annotations = 0;
293 let cameras: Vec<(&PmiView, &PmiCamera)> =
294 pmi.views.iter().filter_map(|view| view.camera.as_ref().map(|camera| (view, camera))).collect();
295 for (view, camera) in &cameras {
296 let Some(rows) = report.and_then(|report| report.view(&view.id)) else { continue };
297 for (row, drawn) in view_annotations(view, camera, rows) {
298 let polylines: Vec<Vec<[f32; 3]>> = drawn.lines.iter().map(|line| line.iter().copied().map(to_f32).collect()).collect();
299 let lines = line_set(&polylines);
300 let fill = triangle_mesh(&drawn.arrows);
301 if lines.is_none() && fill.is_none() {
302 continue;
303 }
304 annotations += 1;
305 let base = format!("PMI {} {}", view.id, row.id);
306 if let Some(lines) = lines {
307 let material = material_index(&mut scene, PMI_RGB, true);
308 let name = node_name(&base, &mut taken);
309 scene.models.push(Model { name, geometry: Geometry::Lines(lines), shaders: vec![material], two_sided: false });
310 owners.push(Owner::View(view.id.clone()));
311 }
312 if let Some(fill) = fill {
313 let material = material_index(&mut scene, PMI_RGB, true);
314 let name = node_name(&format!("{base} fill"), &mut taken);
315 scene.models.push(Model { name, geometry: Geometry::Mesh(fill), shaders: vec![material], two_sided: true });
316 owners.push(Owner::View(view.id.clone()));
317 }
318 }
319 }
320
321 let u3d = u3d::write(&scene)?;
322 let nodes: Vec<String> = scene.models.iter().map(|model| model.name.clone()).collect();
323 let mut views: Vec<View3d> = cameras
324 .iter()
325 .map(|(view, camera)| {
326 let rows = report.and_then(|report| report.view(&view.id));
330 let mut stages: std::collections::HashMap<&str, Vec<PmiPose>> = std::collections::HashMap::new();
331 for row in rows.into_iter().flat_map(|rows| &rows.annotations) {
332 if !row.enabled || row.status != PmiStatus::Ok {
333 continue;
334 }
335 if let PmiGeometry::Explode { solids, translate, rotate_deg, scale, center, .. } = &row.geometry {
336 for solid in solids {
337 stages.entry(solid.as_str()).or_default().push(PmiPose {
338 center: *center,
339 translate: *translate,
340 rotate_deg: *rotate_deg,
341 scale: *scale,
342 });
343 }
344 }
345 }
346 View3d {
347 id: view.id.clone(),
348 name: if view.name.trim().is_empty() { view.id.clone() } else { view.name.clone() },
349 camera: (*camera).clone(),
350 wireframe: view.display.wireframe,
351 visible: owners
352 .iter()
353 .map(|owner| match owner {
354 Owner::Solid(solid) => !view.hides(solid),
355 Owner::View(id) => *id == view.id,
356 })
357 .collect(),
358 poses: owners
359 .iter()
360 .map(|owner| match owner {
361 Owner::Solid(solid) => stages.get(solid.as_str()).map(|stages| stage_matrix(stages)),
362 Owner::View(_) => None,
363 })
364 .collect(),
365 section: view.section_plane_in(rows),
366 }
367 })
368 .collect();
369 if views.is_empty() {
372 views.push(View3d {
373 id: ISOMETRIC.into(),
374 name: "Isometric".into(),
375 camera: isometric_camera(bodies),
376 wireframe: false,
377 visible: owners.iter().map(|owner| matches!(owner, Owner::Solid(_))).collect(),
378 poses: vec![None; owners.len()],
379 section: None,
380 });
381 }
382 Ok(Model3d { u3d, nodes, views, annotations })
383}
384
385#[derive(Debug, Clone, Default, PartialEq)]
387pub struct DrawnAnnotation {
388 pub lines: Vec<Vec<[f64; 3]>>,
391 pub arrows: Vec<[[f64; 3]; 3]>,
393}
394
395pub fn view_annotations<'a>(view: &PmiView, camera: &PmiCamera, rows: &'a brep_kernel::PmiViewReport) -> Vec<(&'a PmiAnnotationReport, DrawnAnnotation)> {
404 let Some((right, _, forward)) = camera_frame(camera) else { return Vec::new() };
405 let wpp = world_per_pixel(camera);
406 let text_height = TEXT_PX_AT_12PT * wpp * (view.display.text_size_pt / 12.0);
407 let style = PmiLayoutStyle { arrow: ARROW_PX * wpp, text_height, view_dir: forward, view_up: camera.up, plane: None };
408 let mut out = Vec::new();
409 for row in &rows.annotations {
410 if !drawable(row) {
411 continue;
412 }
413 let row_style = PmiLayoutStyle {
414 plane: row.plane.or(Some(PmiPlane { origin: row.label_world, normal: [-forward[0], -forward[1], -forward[2]], x_axis: right })),
415 ..style
416 };
417 let drawn = brep_kernel::feature_pipeline::pmi::weld_symbol::present_row(row, &row_style)
419 .unwrap_or_else(|| pmi_present(&row.geometry, row.label_world, &row.text, &row_style));
420 let mut lines: Vec<Vec<[f64; 3]>> = drawn.polylines.iter().chain(&drawn.frames).cloned().collect();
421 for run in &drawn.texts {
422 lines.extend(run.strokes());
423 }
424 lines.retain(|line| line.len() >= 2);
425 if lines.is_empty() && drawn.arrows.is_empty() {
426 continue;
427 }
428 out.push((row, DrawnAnnotation { lines, arrows: drawn.arrows }));
429 }
430 out
431}
432
433pub fn stage_matrix(stages: &[PmiPose]) -> [f64; 12] {
438 let apply = |point: [f64; 3]| stages.iter().fold(point, |p, stage| stage.apply(p));
439 let origin = apply([0.0; 3]);
440 let mut matrix = [0.0; 12];
441 for (axis, unit) in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].into_iter().enumerate() {
442 let column = sub(apply(unit), origin);
443 matrix[axis * 3..axis * 3 + 3].copy_from_slice(&column);
444 }
445 matrix[9..].copy_from_slice(&origin);
446 matrix
447}
448
449fn cross_section(point: [f64; 3], normal: [f64; 3]) -> String {
456 let n = unit(normal).unwrap_or([1.0, 0.0, 0.0]);
457 let beta = (-n[2]).clamp(-1.0, 1.0).asin().to_degrees();
458 let gamma = n[1].atan2(n[0]).to_degrees();
459 format!(
460 "<< /Type /3DCrossSection /C [{} {} {}] /O [null {} {}] /PO 0 /IV true >>",
461 num(point[0]),
462 num(point[1]),
463 num(point[2]),
464 num(beta),
465 num(gamma)
466 )
467}
468
469pub const ISOMETRIC: &str = "ISOMETRIC";
471
472pub fn isometric_camera(bodies: &[Body]) -> PmiCamera {
475 let mut min = [f64::INFINITY; 3];
476 let mut max = [f64::NEG_INFINITY; 3];
477 for p in bodies.iter().flat_map(|body| body.positions.iter()) {
478 for axis in 0..3 {
479 min[axis] = min[axis].min(f64::from(p[axis]));
480 max[axis] = max[axis].max(f64::from(p[axis]));
481 }
482 }
483 if !min[0].is_finite() {
484 (min, max) = ([-1.0; 3], [1.0; 3]);
485 }
486 let centre = [(min[0] + max[0]) * 0.5, (min[1] + max[1]) * 0.5, (min[2] + max[2]) * 0.5];
487 let radius = (dot(sub(max, min), sub(max, min)).sqrt() * 0.5).max(1e-3);
488 let d = radius * 4.0 / 3f64.sqrt();
489 PmiCamera {
490 eye: [centre[0] + d, centre[1] + d, centre[2] + d],
491 target: centre,
492 up: [0.0, 1.0, 0.0],
493 projection: PmiProjection::Orthographic { half_height: radius * 1.1 },
494 viewport: [1280.0, 800.0],
495 }
496}
497
498fn drawable(row: &PmiAnnotationReport) -> bool {
502 row.enabled && row.status == PmiStatus::Ok && !matches!(row.geometry, PmiGeometry::Explode { .. } | PmiGeometry::Hide { .. })
503}
504
505fn num(value: f64) -> String {
510 let text = format!("{value:.6}");
511 let text = text.trim_end_matches('0').trim_end_matches('.');
512 if text == "-0" || text.is_empty() {
513 "0".into()
514 } else {
515 text.into()
516 }
517}
518
519pub fn c2w(camera: &PmiCamera) -> Option<([f64; 12], f64)> {
522 let (right, up, forward) = camera_frame(camera)?;
523 let y = if CAMERA_Y_UP { up } else { [-up[0], -up[1], -up[2]] };
524 let e = camera.eye;
525 let m = [right[0], right[1], right[2], y[0], y[1], y[2], forward[0], forward[1], forward[2], e[0], e[1], e[2]];
526 Some((m, dot(sub(camera.target, camera.eye), forward)))
527}
528
529pub fn projection(camera: &PmiCamera, box_height_pt: f64, scale: Option<f64>) -> Projection3d {
533 match (&camera.projection, scale) {
534 (_, Some(scale)) => Projection3d::Orthographic { scale },
535 (PmiProjection::Perspective { fov_y_deg }, None) => Projection3d::Perspective { fov_y_deg: *fov_y_deg },
536 (PmiProjection::Orthographic { half_height }, None) => {
537 Projection3d::Orthographic { scale: box_height_pt * 0.5 / half_height.max(1e-9) }
538 }
539 }
540}
541
542pub fn view_dict(model: &Model3d, view: &View3d, name: &str, projection: Projection3d) -> String {
546 let (matrix, orbit) = c2w(&view.camera).unwrap_or(([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 1.0));
547 let matrix: Vec<String> = matrix.iter().map(|v| num(*v)).collect();
548 let projection = match projection {
549 Projection3d::Orthographic { scale } => format!("<< /Subtype /O /OS {} >>", num(scale)),
550 Projection3d::Perspective { fov_y_deg } => {
551 format!("<< /Subtype /P /FOV {} /PS /H >>", num(fov_y_deg.clamp(1.0, 179.0)))
552 }
553 };
554 let nodes: Vec<String> = model
555 .nodes
556 .iter()
557 .zip(&view.visible)
558 .zip(view.poses.iter().chain(std::iter::repeat(&None)))
559 .map(|((node, visible), pose)| match pose {
560 Some(pose) => {
561 let pose: Vec<String> = pose.iter().map(|v| num(*v)).collect();
562 format!("<< /Type /3DNode /N ({}) /V {visible} /M [{}] >>", string_literal(node), pose.join(" "))
563 }
564 None => format!("<< /Type /3DNode /N ({}) /V {visible} >>", string_literal(node)),
565 })
566 .collect();
567 let section = view
568 .section
569 .map(|(point, normal)| format!(" /SA [{}]", cross_section(point, normal)))
570 .unwrap_or_default();
571 format!(
572 "<< /Type /3DView /XN ({}) /IN ({}) /MS /M /C2W [{}] /CO {} /P {} \
573 /BG << /Type /3DBG /Subtype /SC /C [1 1 1] >> \
574 /RM << /Type /3DRenderMode /Subtype /{} >> \
575 /LS << /Type /3DLightingScheme /Subtype /Hard >>{} /NR true /NA [{}] >>",
576 string_literal(name),
577 string_literal(&view.id),
578 matrix.join(" "),
579 num(orbit.max(0.0)),
580 projection,
581 if view.wireframe { "Wireframe" } else { "Solid" },
582 section,
583 nodes.join(" ")
584 )
585}
586
587pub fn stream_object(model: &Model3d, va_box_height_pt: f64) -> String {
591 let views: Vec<String> = model
592 .views
593 .iter()
594 .map(|view| view_dict(model, view, &view.name, projection(&view.camera, va_box_height_pt, None)))
595 .collect();
596 let data = ascii85(&model.u3d) + "\n";
599 format!(
600 "<< /Type /3D /Subtype /U3D /Filter /ASCII85Decode /DV 0 /VA [{}] /Length {} >>\nstream\n{}endstream",
601 views.join(" "),
602 data.len(),
603 data
604 )
605}
606
607pub fn ascii85(bytes: &[u8]) -> String {
609 let mut out = String::with_capacity(bytes.len() * 5 / 4 + bytes.len() / 60 + 4);
610 let mut column = 0;
611 let mut push = |c: char, out: &mut String| {
612 out.push(c);
613 column += 1;
614 if column == 76 {
615 out.push('\n');
616 column = 0;
617 }
618 };
619 for chunk in bytes.chunks(4) {
620 let mut word = [0u8; 4];
621 word[..chunk.len()].copy_from_slice(chunk);
622 let value = u32::from_be_bytes(word);
623 if chunk.len() == 4 && value == 0 {
624 push('z', &mut out);
625 continue;
626 }
627 let mut digits = [0u8; 5];
628 let mut v = value;
629 for digit in digits.iter_mut().rev() {
630 *digit = (v % 85) as u8;
631 v /= 85;
632 }
633 for digit in &digits[..chunk.len() + 1] {
634 push((b'!' + digit) as char, &mut out);
635 }
636 }
637 out.push_str("~>");
638 out
639}
640
641pub fn rect_pt(centre_mm: [f64; 2], half_mm: [f64; 2], page_height_mm: f64) -> [f64; 4] {
645 [
646 (centre_mm[0] - half_mm[0]) * PT_PER_MM,
647 (page_height_mm - centre_mm[1] - half_mm[1]) * PT_PER_MM,
648 (centre_mm[0] + half_mm[0]) * PT_PER_MM,
649 (page_height_mm - centre_mm[1] + half_mm[1]) * PT_PER_MM,
650 ]
651}
652
653#[derive(Debug, Clone)]
659pub struct Pdf3d {
660 pub model: Model3d,
661 pub placements: Vec<Placement3d>,
662 pub page: Option<Page3d>,
664}
665
666#[derive(Debug, Clone, PartialEq)]
670pub struct Placement3d {
671 pub page: usize,
673 pub id: String,
675 pub view: String,
677 pub centre_mm: [f64; 2],
680 pub half_mm: [f64; 2],
681 pub scale: f64,
683}
684
685#[derive(Debug, Clone, PartialEq)]
687pub struct Button {
688 pub rect_mm: [f64; 4],
690 pub label: String,
691 pub view: usize,
693}
694
695#[derive(Debug, Clone)]
697pub struct Page3d {
698 pub width_mm: f64,
699 pub height_mm: f64,
700 pub title: String,
701 pub title_at: [f64; 2],
702 pub title_mm: f64,
703 pub box_mm: [f64; 4],
705 pub default_view: usize,
707 pub poster: Option<ViewDrawing>,
710 pub poster_scale: Option<f64>,
713 pub buttons: Vec<Button>,
714 pub button_text_mm: f64,
715 pub caption: Vec<String>,
716 pub caption_at: Vec<[f64; 2]>,
717 pub caption_mm: f64,
718}
719
720use super::project::ViewDrawing;
721
722const PAGE_MARGIN_MM: f64 = 12.0;
723const TITLE_MM: f64 = 5.0;
724const BUTTON_H_MM: f64 = 8.0;
725const BUTTON_GAP_MM: f64 = 3.0;
726const BUTTON_TEXT_MM: f64 = 2.8;
727const BUTTONS_PER_ROW: usize = 8;
728const CAPTION_MM: f64 = 2.8;
729
730pub const CAPTION: [&str; 2] = [
732 "Interactive 3D model: open this file in Adobe Acrobat or Reader (with 3D content enabled) or in Foxit to rotate, zoom and switch PMI views.",
733 "Other PDF viewers show the drawing above in place of the model.",
734];
735
736impl Page3d {
737 pub fn layout(width_mm: f64, height_mm: f64, title: &str, model: &Model3d) -> Page3d {
741 let (w, h) = (width_mm.max(100.0), height_mm.max(100.0));
742 let inner = w - 2.0 * PAGE_MARGIN_MM;
743 let caption_at: Vec<[f64; 2]> = (0..CAPTION.len())
744 .map(|line| [w * 0.5, h - PAGE_MARGIN_MM - (CAPTION.len() - 1 - line) as f64 * CAPTION_MM * 1.8])
745 .collect();
746 let rows = model.views.len().div_ceil(BUTTONS_PER_ROW);
747 let per_row = model.views.len().min(BUTTONS_PER_ROW).max(1);
748 let button_w = ((inner - (per_row - 1) as f64 * BUTTON_GAP_MM) / per_row as f64).min(48.0);
749 let buttons_bottom = caption_at[0][1] - CAPTION_MM * 2.0;
750 let buttons_top = buttons_bottom - rows as f64 * (BUTTON_H_MM + BUTTON_GAP_MM) + BUTTON_GAP_MM;
751 let buttons = model
752 .views
753 .iter()
754 .enumerate()
755 .map(|(index, view)| {
756 let (row, column) = (index / BUTTONS_PER_ROW, index % BUTTONS_PER_ROW);
757 let in_row = (model.views.len() - row * BUTTONS_PER_ROW).min(BUTTONS_PER_ROW);
758 let row_w = in_row as f64 * button_w + (in_row - 1) as f64 * BUTTON_GAP_MM;
759 let x0 = (w - row_w) * 0.5 + column as f64 * (button_w + BUTTON_GAP_MM);
760 let y0 = buttons_top + row as f64 * (BUTTON_H_MM + BUTTON_GAP_MM);
761 Button { rect_mm: [x0, y0, x0 + button_w, y0 + BUTTON_H_MM], label: view.name.clone(), view: index }
762 })
763 .collect();
764 let box_top = PAGE_MARGIN_MM + TITLE_MM * 2.0;
765 let box_bottom = if rows > 0 { buttons_top - BUTTON_GAP_MM * 2.0 } else { buttons_bottom };
766 Page3d {
767 width_mm: w,
768 height_mm: h,
769 title: title.to_string(),
770 title_at: [w * 0.5, PAGE_MARGIN_MM + TITLE_MM * 0.5],
771 title_mm: TITLE_MM,
772 box_mm: [PAGE_MARGIN_MM, box_top, w - PAGE_MARGIN_MM, box_bottom.max(box_top + 20.0)],
773 default_view: 0,
774 poster: None,
775 poster_scale: None,
776 buttons,
777 button_text_mm: BUTTON_TEXT_MM,
778 caption: CAPTION.iter().map(|line| line.to_string()).collect(),
779 caption_at,
780 caption_mm: CAPTION_MM,
781 }
782 }
783
784 pub fn box_centre_mm(&self) -> [f64; 2] {
785 [(self.box_mm[0] + self.box_mm[2]) * 0.5, (self.box_mm[1] + self.box_mm[3]) * 0.5]
786 }
787
788 pub fn box_half_mm(&self) -> [f64; 2] {
789 [(self.box_mm[2] - self.box_mm[0]) * 0.5, (self.box_mm[3] - self.box_mm[1]) * 0.5]
790 }
791}
792
793#[derive(Debug, Clone)]
796pub struct Plan {
797 stream: usize,
798 placements: Vec<(usize, usize)>,
800 page: Option<(usize, usize, Vec<usize>)>,
802 placement_pages: Vec<usize>,
804 page_index: usize,
806}
807
808fn rect_text(r: [f64; 4]) -> String {
809 format!("[{:.4} {:.4} {:.4} {:.4}]", r[0], r[1], r[2], r[3])
810}
811
812fn empty_appearance(rect: [f64; 4]) -> String {
815 format!(
816 "<< /Type /XObject /Subtype /Form /BBox [0 0 {:.4} {:.4}] /Length 1 >>\nstream\n\nendstream",
817 rect[2] - rect[0],
818 rect[3] - rect[1]
819 )
820}
821
822impl Plan {
823 pub fn new(three_d: &Pdf3d, mut next: usize, sheets: usize) -> Plan {
826 let stream = next;
827 next += 1;
828 let placements = three_d
829 .placements
830 .iter()
831 .map(|_| {
832 next += 2;
833 (next - 2, next - 1)
834 })
835 .collect();
836 let page = three_d.page.as_ref().map(|page| {
837 let annot = next;
838 let links = (0..page.buttons.len()).map(|i| annot + 2 + i).collect::<Vec<_>>();
839 next += 2 + page.buttons.len();
840 (annot, annot + 1, links)
841 });
842 Plan {
843 stream,
844 placements,
845 page,
846 placement_pages: three_d.placements.iter().map(|p| p.page).collect(),
847 page_index: sheets,
848 }
849 }
850
851 pub fn annots_on(&self, index: usize) -> String {
854 let mut refs: Vec<String> = self
855 .placements
856 .iter()
857 .zip(&self.placement_pages)
858 .filter(|(_, page)| **page == index)
859 .map(|((annot, _), _)| format!("{annot} 0 R"))
860 .collect();
861 if let Some((annot, _, links)) = &self.page {
862 if index == self.page_index {
863 refs.push(format!("{annot} 0 R"));
864 refs.extend(links.iter().map(|link| format!("{link} 0 R")));
865 }
866 }
867 if refs.is_empty() {
868 String::new()
869 } else {
870 format!(" /Annots [{}]", refs.join(" "))
871 }
872 }
873
874 pub fn objects(&self, three_d: &Pdf3d, pages: &[&super::project::SheetDrawing], first_page: usize) -> Vec<(usize, String)> {
877 let model = &three_d.model;
878 let placement_box_pt = three_d
879 .placements
880 .iter()
881 .map(|placement| placement.half_mm[1] * 2.0 * PT_PER_MM)
882 .fold(0.0f64, f64::max);
883 let va_box_pt = match &three_d.page {
884 Some(page) => page.box_half_mm()[1] * 2.0 * PT_PER_MM,
885 None if placement_box_pt > 0.0 => placement_box_pt,
886 None => 400.0,
887 };
888 let mut out = vec![(self.stream, stream_object(model, va_box_pt))];
889 for (placement, (annot, appearance)) in three_d.placements.iter().zip(&self.placements) {
890 let page_h = pages.get(placement.page).map_or(297.0, |page| page.height_mm.max(1.0));
891 let rect = rect_pt(placement.centre_mm, placement.half_mm, page_h);
892 let view = model.view(&placement.view);
893 let default = match view {
894 Some(view) => view_dict(
895 model,
896 view,
897 &format!("{} {}", placement.id, view.name),
898 Projection3d::Orthographic { scale: placement.scale * PT_PER_MM },
899 ),
900 None => "0".to_string(),
901 };
902 out.push((
903 *annot,
904 format!(
905 "<< /Type /Annot /Subtype /3D /Rect {} /F 4 /P {} 0 R /NM ({}) \
906 /Contents (Click to turn this view in 3D: {}) /3DD {} 0 R /3DV {} \
907 /3DA << /A /XA /D /PC /TB true /NP false >> /AP << /N {} 0 R >> >>",
908 rect_text(rect),
909 first_page + placement.page * 2,
910 string_literal(&placement.id),
911 string_literal(&view.map_or(placement.view.clone(), |view| view.name.clone())),
912 self.stream,
913 default,
914 appearance
915 ),
916 ));
917 out.push((*appearance, empty_appearance(rect)));
918 }
919 if let (Some(page), Some((annot, appearance, links))) = (&three_d.page, &self.page) {
920 let page_number = first_page + self.page_index * 2;
921 let rect = rect_pt(page.box_centre_mm(), page.box_half_mm(), page.height_mm);
922 let default = match (model.views.get(page.default_view), page.poster_scale) {
923 (Some(view), Some(scale)) => {
924 view_dict(model, view, &view.name, Projection3d::Orthographic { scale: scale * PT_PER_MM })
925 }
926 _ => page.default_view.to_string(),
927 };
928 out.push((
929 *annot,
930 format!(
931 "<< /Type /Annot /Subtype /3D /Rect {} /F 4 /P {page_number} 0 R /NM (MODEL3D) \
932 /Contents (The 3D model with its PMI views) /3DD {} 0 R /3DV {default} \
933 /3DA << /A /PO /D /PC /TB true /NP true >> /AP << /N {appearance} 0 R >> >>",
934 rect_text(rect),
935 self.stream
936 ),
937 ));
938 out.push((*appearance, empty_appearance(rect)));
939 for (button, link) in page.buttons.iter().zip(links) {
940 let [x0, y0, x1, y1] = button.rect_mm;
941 let r = rect_pt([(x0 + x1) * 0.5, (y0 + y1) * 0.5], [(x1 - x0) * 0.5, (y1 - y0) * 0.5], page.height_mm);
942 out.push((
943 *link,
944 format!(
945 "<< /Type /Annot /Subtype /Link /Rect {} /Border [0 0 0] /P {page_number} 0 R \
946 /A << /S /GoTo3DView /TA {annot} 0 R /V {} >> >>",
947 rect_text(r),
948 button.view
949 ),
950 ));
951 }
952 }
953 out
954 }
955}
956
957#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
961pub struct Summary {
962 pub annotations: usize,
963 pub views: usize,
964 pub links: usize,
965 #[serde(rename = "u3dBytes")]
966 pub u3d_bytes: usize,
967}
968
969pub fn summary(pdf: &[u8]) -> Option<Summary> {
971 let text = String::from_utf8_lossy(pdf);
972 let stream_at = text.find("/Subtype /U3D")?;
973 let dict_end = text[stream_at..].find("\nstream\n")? + stream_at;
974 let dict = &text[stream_at..dict_end];
975 let data_start = dict_end + "\nstream\n".len();
976 let data_end = text[data_start..].find("~>")? + data_start;
977 let data = &text[data_start..data_end];
978 let mut u3d_bytes = 0;
979 let mut group = 0;
980 for c in data.chars().filter(|c| !c.is_whitespace()) {
981 if c == 'z' {
982 u3d_bytes += 4;
983 } else {
984 group += 1;
985 if group == 5 {
986 u3d_bytes += 4;
987 group = 0;
988 }
989 }
990 }
991 if group > 0 {
992 u3d_bytes += group - 1;
993 }
994 Some(Summary {
995 annotations: text.matches("/Subtype /3D /Rect").count(),
996 views: dict.matches("/Type /3DView").count(),
997 links: text.matches("/S /GoTo3DView").count(),
998 u3d_bytes,
999 })
1000}
1001