1use std::{
2 fmt, fs,
3 path::Path,
4 str::FromStr,
5 time::{Instant, SystemTime, UNIX_EPOCH},
6};
7
8use anyhow::{Context, Result, bail, ensure};
9use fontdue::{Font, FontSettings};
10use serde::{Deserialize, Serialize};
11use tiny_skia::{
12 BlendMode, Color, FillRule, LineCap, LineJoin, Paint, Path as SkiaPath, PathBuilder, Pixmap,
13 PixmapPaint, Stroke, Transform,
14};
15
16use crate::{
17 layout::{LayoutOptions, call_control_points, call_curve, sample_rect},
18 model::{Atlas, NodeKind, Point, Rect},
19};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum RenderBackend {
23 Software,
24 Wgpu,
25}
26
27impl FromStr for RenderBackend {
28 type Err = anyhow::Error;
29
30 fn from_str(value: &str) -> Result<Self> {
31 match value {
32 "software" | "cpu" => Ok(Self::Software),
33 "wgpu" | "gpu" => Ok(Self::Wgpu),
34 _ => bail!("unknown render backend {value:?}; expected software or wgpu"),
35 }
36 }
37}
38
39impl fmt::Display for RenderBackend {
40 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41 formatter.write_str(match self {
42 Self::Software => "software",
43 Self::Wgpu => "wgpu",
44 })
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum Theme {
50 Architect,
51 Night,
52 Ink,
53 SolarizedDark,
54 SolarizedLight,
55}
56
57impl FromStr for Theme {
58 type Err = anyhow::Error;
59
60 fn from_str(value: &str) -> Result<Self> {
61 match value {
62 "architect" | "architect-pencil" | "pencil" => Ok(Self::Architect),
63 "night" | "night-transit" => Ok(Self::Night),
64 "ink" | "ink-transit" => Ok(Self::Ink),
65 "solarized-dark" => Ok(Self::SolarizedDark),
66 "solarized-light" => Ok(Self::SolarizedLight),
67 _ => bail!(
68 "unknown theme {value:?}; expected architect, night, ink, solarized-dark, or solarized-light"
69 ),
70 }
71 }
72}
73
74impl fmt::Display for Theme {
75 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76 formatter.write_str(match self {
77 Self::Architect => "architect",
78 Self::Night => "night",
79 Self::Ink => "ink",
80 Self::SolarizedDark => "solarized-dark",
81 Self::SolarizedLight => "solarized-light",
82 })
83 }
84}
85
86#[derive(Debug, Clone)]
87pub struct RenderOptions {
88 pub backend: RenderBackend,
89 pub theme: Theme,
90 pub source_url_template: Option<String>,
93 pub call_opacity: u8,
94 pub call_width: f32,
95 pub boundary_width: f32,
96 pub density_aware_exposure: bool,
99 pub density_reference_calls: usize,
100 pub pdf_dpi: f64,
102 pub pdf_call_dpi: Option<f64>,
105 pub pdf_call_tile_size: u32,
107 pub pdf_resume: bool,
109 pub pdf_restart: bool,
111 pub pdf_stop_after_tiles: Option<usize>,
113 pub pdf_compression_workers: usize,
116}
117
118impl Default for RenderOptions {
119 fn default() -> Self {
120 Self {
121 backend: RenderBackend::Software,
122 theme: Theme::Architect,
123 source_url_template: None,
124 call_opacity: 34,
125 call_width: 1.10,
126 boundary_width: 0.62,
127 density_aware_exposure: true,
128 density_reference_calls: 2_500,
129 pdf_dpi: 144.0,
130 pdf_call_dpi: None,
131 pdf_call_tile_size: 2_048,
132 pdf_resume: false,
133 pdf_restart: false,
134 pdf_stop_after_tiles: None,
135 pdf_compression_workers: 0,
136 }
137 }
138}
139
140#[derive(Debug, Clone, Default, Serialize, Deserialize)]
141pub struct PdfTileTimingStats {
142 pub planning_ms: u64,
143 pub scene_prepare_ms: u64,
144 pub spline_evaluation_gpu_ms: Option<f64>,
145 pub rasterization_gpu_ms: Option<f64>,
146 pub render_and_readback_ms: u64,
147 pub rgba_split_ms: u64,
148 pub compression_ms: u64,
149 pub cache_write_ms: u64,
150 pub pdf_assembly_ms: u64,
151 pub tile_pipeline_wall_ms: u64,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct PdfTileCacheStats {
157 pub enabled: bool,
158 pub cache_key: String,
159 pub manifest_path: String,
160 pub tiles_rendered: usize,
161 pub tiles_reused: usize,
162 pub compression_workers: usize,
163 pub max_in_flight_tiles: usize,
164 pub compression_codec: String,
165 pub compression_level: i32,
166 pub timings: PdfTileTimingStats,
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct RenderStats {
171 pub backend: String,
172 pub gpu_adapter: Option<String>,
173 pub width: u32,
174 pub height: u32,
175 pub call_layer_width: u32,
176 pub call_layer_height: u32,
177 pub call_layer_dpi: Option<f64>,
178 pub call_layer_tiles: usize,
179 pub call_layer_tile_size: Option<u32>,
180 pub call_layer_overlap: Option<u32>,
181 pub files_drawn: usize,
182 pub file_labels_drawn: usize,
183 pub directory_labels_drawn: usize,
184 pub calls_drawn: usize,
185 pub directory_boundaries_drawn: usize,
186 pub output_bytes: u64,
187 pub effective_call_opacity: u8,
188 pub call_compositing: String,
189 pub direction_source_color: String,
190 pub direction_target_color: String,
191 pub render_ms: u64,
192 #[serde(skip_serializing_if = "Option::is_none")]
193 pub pdf_tile_cache: Option<PdfTileCacheStats>,
194}
195
196pub fn render_png(
197 atlas: &Atlas,
198 output: &Path,
199 layout_options: &LayoutOptions,
200 render_options: &RenderOptions,
201) -> Result<RenderStats> {
202 match render_options.backend {
203 RenderBackend::Software => {
204 render_software_png(atlas, output, layout_options, render_options)
205 }
206 RenderBackend::Wgpu => {
207 match crate::render_wgpu::render_wgpu_png(atlas, output, layout_options, render_options)
208 {
209 Ok(stats) => Ok(stats),
210 Err(error) if gpu_is_unavailable(&error) => {
211 eprintln!(
212 "wgpu is unavailable ({error:#}); falling back to the software call renderer"
213 );
214 let mut stats =
215 render_software_png(atlas, output, layout_options, render_options)?;
216 stats.backend = "software (wgpu unavailable)".to_owned();
217 Ok(stats)
218 }
219 Err(error) => Err(error),
220 }
221 }
222 }
223}
224
225pub fn render_output(
226 atlas: &Atlas,
227 output: &Path,
228 layout_options: &LayoutOptions,
229 render_options: &RenderOptions,
230) -> Result<RenderStats> {
231 match output
232 .extension()
233 .and_then(|extension| extension.to_str())
234 .unwrap_or_default()
235 .to_ascii_lowercase()
236 .as_str()
237 {
238 "png" => render_png(atlas, output, layout_options, render_options),
239 "svg" | "pdf" => {
240 crate::export::render_vector_artifact(atlas, output, layout_options, render_options)
241 }
242 "html" | "htm" => {
243 crate::html::render_interactive_html(atlas, output, layout_options, render_options)
244 }
245 extension => {
246 bail!("unsupported output extension {extension:?}; expected .png, .svg, .pdf, or .html")
247 }
248 }
249}
250
251pub(crate) fn render_call_layer_png(
252 atlas: &Atlas,
253 output: &Path,
254 layout_options: &LayoutOptions,
255 render_options: &RenderOptions,
256) -> Result<RenderStats> {
257 match render_options.backend {
258 RenderBackend::Software => {
259 render_software_call_layer_png(atlas, output, layout_options, render_options)
260 }
261 RenderBackend::Wgpu => match crate::render_wgpu::render_wgpu_call_layer_png(
262 atlas,
263 output,
264 layout_options,
265 render_options,
266 ) {
267 Ok(stats) => Ok(stats),
268 Err(error) if gpu_is_unavailable(&error) => {
269 eprintln!(
270 "wgpu is unavailable ({error:#}); falling back to the software call renderer"
271 );
272 let mut stats =
273 render_software_call_layer_png(atlas, output, layout_options, render_options)?;
274 stats.backend = "software (wgpu unavailable)".to_owned();
275 Ok(stats)
276 }
277 Err(error) => Err(error),
278 },
279 }
280}
281
282pub(crate) fn gpu_is_unavailable(error: &anyhow::Error) -> bool {
283 let message = format!("{error:#}");
284 message.contains("no compatible GPU adapter")
285 || message.contains("No suitable graphics adapter")
286 || message.contains("does not support blendable RGBA16Float")
287 || message.contains("does not support 4x multisampled RGBA16Float")
288 || message.contains("exceeds the adapter's")
289 || message.contains("GPU spline scene exceeds")
290}
291
292pub(crate) fn render_software_png(
293 atlas: &Atlas,
294 output: &Path,
295 layout_options: &LayoutOptions,
296 render_options: &RenderOptions,
297) -> Result<RenderStats> {
298 render_software_png_inner(atlas, output, layout_options, render_options, true, true)
299}
300
301pub(crate) fn render_software_base_png(
302 atlas: &Atlas,
303 output: &Path,
304 layout_options: &LayoutOptions,
305 render_options: &RenderOptions,
306) -> Result<RenderStats> {
307 render_software_png_inner(atlas, output, layout_options, render_options, false, false)
308}
309
310pub(crate) fn render_software_call_layer_png(
311 atlas: &Atlas,
312 output: &Path,
313 layout_options: &LayoutOptions,
314 render_options: &RenderOptions,
315) -> Result<RenderStats> {
316 let started = Instant::now();
317 let palette = Palette::for_theme(render_options.theme);
318 let opacity = effective_call_opacity(atlas.calls.len(), render_options);
319 let call_indices: Vec<_> = (0..atlas.calls.len()).collect();
320 let (pixmap, calls_drawn) = render_software_call_tile(
321 atlas,
322 layout_options,
323 render_options,
324 &call_indices,
325 CallTileViewport {
326 x: 0,
327 y: 0,
328 width: layout_options.width,
329 height: layout_options.height,
330 },
331 )?;
332 if let Some(parent) = output.parent() {
333 fs::create_dir_all(parent)
334 .with_context(|| format!("cannot create output directory {}", parent.display()))?;
335 }
336 pixmap
337 .save_png(output)
338 .with_context(|| format!("cannot save {}", output.display()))?;
339 Ok(RenderStats {
340 backend: RenderBackend::Software.to_string(),
341 gpu_adapter: None,
342 width: layout_options.width,
343 height: layout_options.height,
344 call_layer_width: layout_options.width,
345 call_layer_height: layout_options.height,
346 call_layer_dpi: None,
347 call_layer_tiles: 1,
348 call_layer_tile_size: None,
349 call_layer_overlap: None,
350 files_drawn: atlas.files().count(),
351 file_labels_drawn: 0,
352 directory_labels_drawn: 0,
353 calls_drawn,
354 directory_boundaries_drawn: atlas
355 .nodes
356 .iter()
357 .filter(|node| node.kind == NodeKind::Directory && node.id != 0)
358 .count(),
359 output_bytes: fs::metadata(output)?.len(),
360 effective_call_opacity: opacity,
361 call_compositing: optical_density_description(),
362 direction_source_color: palette.direction_source.hex(),
363 direction_target_color: palette.direction_target.hex(),
364 render_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
365 pdf_tile_cache: None,
366 })
367}
368
369#[derive(Debug, Clone, Copy)]
373pub(crate) struct CallTileViewport {
374 pub x: u32,
375 pub y: u32,
376 pub width: u32,
377 pub height: u32,
378}
379
380#[derive(Debug)]
381pub(crate) struct CallTile {
382 pub core_x: u32,
383 pub core_y: u32,
384 pub core_width: u32,
385 pub core_height: u32,
386 pub render_x: u32,
387 pub render_y: u32,
388 pub render_width: u32,
389 pub render_height: u32,
390 pub call_indices: Vec<usize>,
391}
392
393pub(crate) fn plan_call_tiles(
394 atlas: &Atlas,
395 layout: &LayoutOptions,
396 render: &RenderOptions,
397) -> Result<(Vec<CallTile>, usize, u32)> {
398 ensure!(
399 (64..=8_192).contains(&render.pdf_call_tile_size),
400 "--pdf-call-tile-size must be between 64 and 8192 pixels"
401 );
402 let tile_size = render.pdf_call_tile_size;
403 let overlap = call_tile_overlap(layout, render);
404 let columns = layout.width.div_ceil(tile_size);
405 let rows = layout.height.div_ceil(tile_size);
406 let mut tiles = Vec::with_capacity((columns as usize).saturating_mul(rows as usize));
407 for row in 0..rows {
408 for column in 0..columns {
409 let core_x = column * tile_size;
410 let core_y = row * tile_size;
411 let core_width = tile_size.min(layout.width - core_x);
412 let core_height = tile_size.min(layout.height - core_y);
413 let render_x = core_x.saturating_sub(overlap);
414 let render_y = core_y.saturating_sub(overlap);
415 let render_x1 = (core_x + core_width)
416 .saturating_add(overlap)
417 .min(layout.width);
418 let render_y1 = (core_y + core_height)
419 .saturating_add(overlap)
420 .min(layout.height);
421 tiles.push(CallTile {
422 core_x,
423 core_y,
424 core_width,
425 core_height,
426 render_x,
427 render_y,
428 render_width: render_x1 - render_x,
429 render_height: render_y1 - render_y,
430 call_indices: Vec::new(),
431 });
432 }
433 }
434
435 let drawing_scale = (layout.width.min(layout.height) as f64 / 1080.0).max(0.5);
436 let stroke_margin = (f64::from(render.call_width) * drawing_scale * 1.28 * 0.5 + 2.0).ceil();
437 let mut calls_drawn = 0;
438 for (call_index, call) in atlas.calls.iter().enumerate() {
439 let mut points = call_control_points(atlas, call);
440 if points.len() < 2 {
441 continue;
442 }
443 let first = points[0];
444 let last = *points.last().expect("target control point");
445 let denominator = points.len().saturating_sub(1).max(1) as f64;
446 let bundle_strength = layout.bundle_strength.clamp(0.0, 1.0);
447 for (index, point) in points.iter_mut().enumerate() {
448 let amount = index as f64 / denominator;
449 let direct_x = first.x + (last.x - first.x) * amount;
450 let direct_y = first.y + (last.y - first.y) * amount;
451 point.x = direct_x + (point.x - direct_x) * bundle_strength;
452 point.y = direct_y + (point.y - direct_y) * bundle_strength;
453 }
454 calls_drawn += 1;
455 let Some((x0, y0, x1, y1)) =
456 curve_bounds(&points, stroke_margin, layout.width, layout.height)
457 else {
458 continue;
459 };
460 let first_column = x0 / tile_size;
461 let last_column = x1.saturating_sub(1) / tile_size;
462 let first_row = y0 / tile_size;
463 let last_row = y1.saturating_sub(1) / tile_size;
464 for row in first_row..=last_row {
465 for column in first_column..=last_column {
466 let index = (row * columns + column) as usize;
467 tiles[index].call_indices.push(call_index);
468 }
469 }
470 }
471 tiles.retain(|tile| !tile.call_indices.is_empty());
472 Ok((tiles, calls_drawn, overlap))
473}
474
475fn curve_bounds(
476 points: &[Point],
477 margin: f64,
478 width: u32,
479 height: u32,
480) -> Option<(u32, u32, u32, u32)> {
481 let min_x = points
482 .iter()
483 .map(|point| point.x)
484 .fold(f64::INFINITY, f64::min)
485 - margin;
486 let min_y = points
487 .iter()
488 .map(|point| point.y)
489 .fold(f64::INFINITY, f64::min)
490 - margin;
491 let max_x = points
492 .iter()
493 .map(|point| point.x)
494 .fold(f64::NEG_INFINITY, f64::max)
495 + margin;
496 let max_y = points
497 .iter()
498 .map(|point| point.y)
499 .fold(f64::NEG_INFINITY, f64::max)
500 + margin;
501 if max_x <= 0.0 || max_y <= 0.0 || min_x >= f64::from(width) || min_y >= f64::from(height) {
502 return None;
503 }
504 let x0 = min_x.floor().clamp(0.0, f64::from(width)) as u32;
505 let y0 = min_y.floor().clamp(0.0, f64::from(height)) as u32;
506 let x1 = max_x.ceil().clamp(0.0, f64::from(width)) as u32;
507 let y1 = max_y.ceil().clamp(0.0, f64::from(height)) as u32;
508 (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
509}
510
511pub(crate) fn call_tile_overlap(layout: &LayoutOptions, render: &RenderOptions) -> u32 {
512 let drawing_scale = (layout.width.min(layout.height) as f64 / 1080.0).max(0.5);
513 (f64::from(render.call_width) * drawing_scale * 1.28 * 0.5 + 0.34 + 2.0)
514 .ceil()
515 .max(4.0) as u32
516}
517
518pub(crate) fn render_software_call_tile(
519 atlas: &Atlas,
520 layout_options: &LayoutOptions,
521 render_options: &RenderOptions,
522 call_indices: &[usize],
523 viewport: CallTileViewport,
524) -> Result<(Pixmap, usize)> {
525 let palette = Palette::for_theme(render_options.theme);
526 let drawing_scale = (layout_options.width.min(layout_options.height) as f32 / 1080.0).max(0.5);
527 let opacity = effective_call_opacity(atlas.calls.len(), render_options);
528 let mut density = OpticalDensityLayer::new(viewport.width, viewport.height)?;
529 let mut ordered_indices = call_indices.to_vec();
530 ordered_indices.sort_unstable_by_key(|index| {
531 atlas
532 .calls
533 .get(*index)
534 .map(|call| call.id)
535 .unwrap_or(u64::MAX)
536 });
537 let mut calls_drawn = 0;
538 for index in ordered_indices {
539 let Some(call) = atlas.calls.get(index) else {
540 continue;
541 };
542 let mut points = call_curve(atlas, call, layout_options);
543 if points.len() < 2 {
544 continue;
545 }
546 for point in &mut points {
547 point.x -= f64::from(viewport.x);
548 point.y -= f64::from(viewport.y);
549 }
550 density.deposit_pencil_call(
551 &points,
552 palette.direction_source,
553 palette.direction_target,
554 opacity,
555 render_options.call_width * drawing_scale,
556 call.id ^ 0xca11_517e,
557 );
558 calls_drawn += 1;
559 }
560 Ok((density.resolve()?, calls_drawn))
561}
562
563#[derive(Clone, Copy, Default)]
564struct OpticalDensityPixel {
565 red: f32,
566 green: f32,
567 blue: f32,
568 density: f32,
569}
570
571struct OpticalDensityLayer {
572 width: u32,
573 height: u32,
574 pixels: Vec<OpticalDensityPixel>,
575 coverage: Vec<f32>,
576 path_position: Vec<f32>,
577 dirty: Vec<u32>,
578}
579
580impl OpticalDensityLayer {
581 fn new(width: u32, height: u32) -> Result<Self> {
582 let pixel_count = (width as usize)
583 .checked_mul(height as usize)
584 .context("optical-density call tile dimensions overflow")?;
585 Ok(Self {
586 width,
587 height,
588 pixels: vec![OpticalDensityPixel::default(); pixel_count],
589 coverage: vec![0.0; pixel_count],
590 path_position: vec![0.0; pixel_count],
591 dirty: Vec::new(),
592 })
593 }
594
595 fn deposit_pencil_call(
596 &mut self,
597 points: &[Point],
598 source: Rgba,
599 target: Rgba,
600 opacity: u8,
601 width: f32,
602 seed: u64,
603 ) {
604 if opacity == 0 || points.len() < 2 {
605 return;
606 }
607 let source = linear_rgb(source);
608 let target = linear_rgb(target);
609 for (pass, (alpha_scale, width_scale, amplitude)) in
610 [(0.62, 0.82, 0.14), (0.38, 1.28, 0.34)]
611 .into_iter()
612 .enumerate()
613 {
614 let jittered = jitter_points(points, seed ^ pass as u64, amplitude);
615 let alpha = (opacity as f32 * alpha_scale).round().max(1.0) / 255.0;
616 let unit_density = -(1.0 - alpha.min(0.999_999)).ln();
617 self.rasterize_path(&jittered, width * width_scale);
618 self.commit_path(unit_density, source, target);
619 }
620 }
621
622 fn rasterize_path(&mut self, points: &[Point], width: f32) {
623 let denominator = points.len().saturating_sub(1).max(1) as f64;
624 for (segment, pair) in points.windows(2).enumerate() {
625 let start = pair[0];
626 let end = pair[1];
627 let dx = end.x - start.x;
628 let dy = end.y - start.y;
629 let length_squared = dx * dx + dy * dy;
630 if length_squared <= f64::EPSILON {
631 continue;
632 }
633 let radius = f64::from(width.max(0.05)) * 0.5;
634 let x0 = (start.x.min(end.x) - radius - 0.5)
635 .floor()
636 .clamp(0.0, f64::from(self.width)) as u32;
637 let y0 = (start.y.min(end.y) - radius - 0.5)
638 .floor()
639 .clamp(0.0, f64::from(self.height)) as u32;
640 let x1 = (start.x.max(end.x) + radius + 0.5)
641 .ceil()
642 .clamp(0.0, f64::from(self.width)) as u32;
643 let y1 = (start.y.max(end.y) + radius + 0.5)
644 .ceil()
645 .clamp(0.0, f64::from(self.height)) as u32;
646 for y in y0..y1 {
647 for x in x0..x1 {
648 let px = f64::from(x) + 0.5;
649 let py = f64::from(y) + 0.5;
650 let along = (((px - start.x) * dx + (py - start.y) * dy) / length_squared)
651 .clamp(0.0, 1.0);
652 let closest_x = start.x + dx * along;
653 let closest_y = start.y + dy * along;
654 let distance = (px - closest_x).hypot(py - closest_y);
655 let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0) as f32;
656 if coverage == 0.0 {
657 continue;
658 }
659 let index = y as usize * self.width as usize + x as usize;
660 if coverage > self.coverage[index] {
661 if self.coverage[index] == 0.0 {
662 self.dirty.push(index as u32);
663 }
664 self.coverage[index] = coverage;
665 self.path_position[index] = ((segment as f64 + along) / denominator) as f32;
666 }
667 }
668 }
669 }
670 }
671
672 fn commit_path(&mut self, unit_density: f32, source: [f32; 3], target: [f32; 3]) {
673 for index in self.dirty.drain(..) {
674 let index = index as usize;
675 let weight = self.coverage[index] * unit_density;
676 let t = self.path_position[index].clamp(0.0, 1.0);
677 let color = [
678 source[0] + (target[0] - source[0]) * t,
679 source[1] + (target[1] - source[1]) * t,
680 source[2] + (target[2] - source[2]) * t,
681 ];
682 let pixel = &mut self.pixels[index];
683 pixel.red += color[0] * weight;
684 pixel.green += color[1] * weight;
685 pixel.blue += color[2] * weight;
686 pixel.density += weight;
687 self.coverage[index] = 0.0;
688 self.path_position[index] = 0.0;
689 }
690 }
691
692 fn resolve(self) -> Result<Pixmap> {
693 let mut pixmap = Pixmap::new(self.width, self.height)
694 .context("optical-density call tile dimensions are too large")?;
695 for (output, density) in pixmap.data_mut().chunks_exact_mut(4).zip(self.pixels) {
696 if density.density <= f32::EPSILON {
697 continue;
698 }
699 let alpha = 1.0 - (-density.density).exp();
700 let inverse_density = density.density.recip();
701 let color = [
702 linear_to_srgb((density.red * inverse_density).clamp(0.0, 1.0)),
703 linear_to_srgb((density.green * inverse_density).clamp(0.0, 1.0)),
704 linear_to_srgb((density.blue * inverse_density).clamp(0.0, 1.0)),
705 ];
706 let alpha_byte = (alpha * 255.0).round().clamp(0.0, 255.0) as u8;
707 output[3] = alpha_byte;
708 for (channel, value) in output[..3].iter_mut().zip(color) {
709 *channel = (value * alpha * 255.0)
710 .round()
711 .clamp(0.0, f32::from(alpha_byte)) as u8;
712 }
713 }
714 Ok(pixmap)
715 }
716}
717
718fn linear_rgb(color: Rgba) -> [f32; 3] {
719 [
720 srgb_to_linear(color.r),
721 srgb_to_linear(color.g),
722 srgb_to_linear(color.b),
723 ]
724}
725
726fn linear_to_srgb(value: f32) -> f32 {
727 if value <= 0.003_130_8 {
728 value * 12.92
729 } else {
730 1.055 * value.powf(1.0 / 2.4) - 0.055
731 }
732}
733
734pub(crate) fn optical_density_description() -> String {
735 "order-independent optical density with exponential transmittance".to_owned()
736}
737
738fn render_software_png_inner(
739 atlas: &Atlas,
740 output: &Path,
741 layout_options: &LayoutOptions,
742 render_options: &RenderOptions,
743 draw_calls: bool,
744 draw_label_layer: bool,
745) -> Result<RenderStats> {
746 let render_started = Instant::now();
747 let palette = Palette::for_theme(render_options.theme);
748 let architectural = matches!(render_options.theme, Theme::Architect | Theme::Night);
749 let drawing_scale = (layout_options.width.min(layout_options.height) as f32 / 1080.0).max(0.5);
750 let mut pixmap = Pixmap::new(layout_options.width, layout_options.height)
751 .context("output dimensions are too large for the software renderer")?;
752 pixmap.fill(palette.background.color());
753 if architectural {
754 draw_paper_texture(
755 &mut pixmap,
756 layout_options.texture_seed,
757 palette.paper_fiber,
758 )?;
759 }
760
761 let root_points = sample_rect(atlas.nodes[0].rect, 3);
762 let root_path = polygon_path(&root_points)?;
763 fill_path(&mut pixmap, &root_path, palette.land, BlendMode::SourceOver);
764
765 let mut files_drawn = 0;
766 for node in atlas
767 .nodes
768 .iter()
769 .filter(|node| node.kind == NodeKind::File)
770 {
771 let perimeter_samples = if architectural {
772 if node.rect.width().min(node.rect.height()) > 30.0 {
773 8
774 } else {
775 3
776 }
777 } else {
778 2
779 };
780 let points = sample_rect(node.rect, perimeter_samples);
781 let path = polygon_path(&points)?;
782 fill_path(
783 &mut pixmap,
784 &path,
785 palette.file_color(&node.language),
786 BlendMode::SourceOver,
787 );
788 if architectural {
789 pencil_outline(
790 &mut pixmap,
791 &points,
792 palette.file_border,
793 PencilStroke {
794 width: render_options.boundary_width * 0.62 * drawing_scale,
795 seed: node.id as u64 ^ layout_options.texture_seed,
796 blend_mode: boundary_blend_mode(render_options.theme),
797 },
798 0.24 * drawing_scale as f64,
799 2,
800 )?;
801 }
802 files_drawn += 1;
803 }
804
805 let mut directory_boundaries_drawn = 0;
806 let mut directories: Vec<_> = atlas
807 .nodes
808 .iter()
809 .filter(|node| node.kind == NodeKind::Directory && node.id != 0)
810 .collect();
811 directories.sort_by_key(|node| node.depth);
812 for directory in directories {
813 let samples = if architectural { 10 } else { 4 };
814 let points = sample_rect(directory.rect, samples);
815 let path = polygon_path(&points)?;
816 let width =
817 render_options.boundary_width * drawing_scale * (1.0 + 0.35 / directory.depth as f32);
818 if architectural {
819 pencil_outline(
820 &mut pixmap,
821 &points,
822 palette.directory_border,
823 PencilStroke {
824 width,
825 seed: directory.id as u64 ^ 0xd1ec_7000,
826 blend_mode: boundary_blend_mode(render_options.theme),
827 },
828 0.34 * drawing_scale as f64,
829 3,
830 )?;
831 } else {
832 stroke_path(
833 &mut pixmap,
834 &path,
835 palette.directory_border,
836 width,
837 BlendMode::SourceOver,
838 );
839 }
840 directory_boundaries_drawn += 1;
841 }
842
843 if architectural {
844 pencil_outline(
845 &mut pixmap,
846 &root_points,
847 palette.outer_border,
848 PencilStroke {
849 width: render_options.boundary_width * 1.8 * drawing_scale,
850 seed: layout_options.texture_seed ^ 0xc0a5_7000,
851 blend_mode: boundary_blend_mode(render_options.theme),
852 },
853 0.28 * drawing_scale as f64,
854 3,
855 )?;
856 } else {
857 stroke_path(
858 &mut pixmap,
859 &root_path,
860 palette.outer_border,
861 render_options.boundary_width * 2.2 * drawing_scale,
862 BlendMode::SourceOver,
863 );
864 }
865 let effective_call_opacity = effective_call_opacity(atlas.calls.len(), render_options);
866 let calls_drawn = if draw_calls {
867 let call_indices: Vec<_> = (0..atlas.calls.len()).collect();
871 let (call_layer, calls_drawn) = render_software_call_tile(
872 atlas,
873 layout_options,
874 render_options,
875 &call_indices,
876 CallTileViewport {
877 x: 0,
878 y: 0,
879 width: layout_options.width,
880 height: layout_options.height,
881 },
882 )?;
883 pixmap.draw_pixmap(
884 0,
885 0,
886 call_layer.as_ref(),
887 &PixmapPaint::default(),
888 Transform::identity(),
889 None,
890 );
891 calls_drawn
892 } else {
893 0
894 };
895
896 let label_stats = if draw_label_layer {
900 draw_labels(&mut pixmap, atlas, layout_options, palette)?
901 } else {
902 LabelStats::default()
903 };
904
905 if let Some(parent) = output.parent() {
906 fs::create_dir_all(parent)
907 .with_context(|| format!("cannot create output directory {}", parent.display()))?;
908 }
909 pixmap
910 .save_png(output)
911 .with_context(|| format!("cannot save {}", output.display()))?;
912 let output_bytes = fs::metadata(output)?.len();
913
914 Ok(RenderStats {
915 backend: RenderBackend::Software.to_string(),
916 gpu_adapter: None,
917 width: layout_options.width,
918 height: layout_options.height,
919 call_layer_width: layout_options.width,
920 call_layer_height: layout_options.height,
921 call_layer_dpi: None,
922 call_layer_tiles: 1,
923 call_layer_tile_size: None,
924 call_layer_overlap: None,
925 files_drawn,
926 file_labels_drawn: label_stats.files,
927 directory_labels_drawn: label_stats.directories,
928 calls_drawn,
929 directory_boundaries_drawn,
930 output_bytes,
931 effective_call_opacity,
932 call_compositing: optical_density_description(),
933 direction_source_color: palette.direction_source.hex(),
934 direction_target_color: palette.direction_target.hex(),
935 render_ms: render_started
936 .elapsed()
937 .as_millis()
938 .min(u128::from(u64::MAX)) as u64,
939 pdf_tile_cache: None,
940 })
941}
942
943fn srgb_to_linear(value: u8) -> f32 {
944 let value = value as f32 / 255.0;
945 if value <= 0.04045 {
946 value / 12.92
947 } else {
948 ((value + 0.055) / 1.055).powf(2.4)
949 }
950}
951
952pub fn effective_call_opacity(call_count: usize, options: &RenderOptions) -> u8 {
953 if !options.density_aware_exposure
954 || call_count <= options.density_reference_calls.max(1)
955 || options.call_opacity == 0
956 {
957 return options.call_opacity;
958 }
959 let scale = (options.density_reference_calls.max(1) as f64 / call_count as f64).sqrt();
960 (f64::from(options.call_opacity) * scale)
961 .round()
962 .clamp(2.0, f64::from(options.call_opacity)) as u8
963}
964
965fn draw_paper_texture(pixmap: &mut Pixmap, seed: u64, color: Rgba) -> Result<()> {
966 let width = pixmap.width() as f64;
967 let height = pixmap.height() as f64;
968 let drawing_scale = (width.min(height) / 1080.0).max(0.5) as f32;
969 let fibers = ((width * height / 2600.0) as usize).clamp(280, 1400);
970 let mut state = seed ^ 0x5eed_f1be_7000;
971 for index in 0..fibers {
972 state = splitmix64(state ^ index as u64);
973 let x = unit_f64(state) * width;
974 state = splitmix64(state);
975 let y = unit_f64(state) * height;
976 state = splitmix64(state);
977 let length = 8.0 + unit_f64(state) * width * 0.075;
978 state = splitmix64(state);
979 let rise = (unit_f64(state) - 0.5) * 1.8;
980 let path = open_path(&[
981 Point { x, y },
982 Point {
983 x: (x + length).min(width),
984 y: (y + rise).clamp(0.0, height),
985 },
986 ])?;
987 stroke_path(
988 pixmap,
989 &path,
990 color,
991 0.24 * drawing_scale,
992 BlendMode::Multiply,
993 );
994 }
995 Ok(())
996}
997
998#[derive(Clone, Copy)]
999struct PencilStroke {
1000 width: f32,
1001 seed: u64,
1002 blend_mode: BlendMode,
1003}
1004
1005fn pencil_outline(
1006 pixmap: &mut Pixmap,
1007 points: &[Point],
1008 color: Rgba,
1009 stroke: PencilStroke,
1010 amplitude: f64,
1011 passes: usize,
1012) -> Result<()> {
1013 let passes = passes.max(1);
1014 for pass in 0..passes {
1015 let jittered = jitter_points(
1016 points,
1017 stroke.seed ^ pass as u64,
1018 amplitude * (pass + 1) as f64,
1019 );
1020 let path = polygon_path(&jittered)?;
1021 let mut pass_color = color;
1022 pass_color.a = ((color.a as usize / passes).max(1) as u8).saturating_add(5);
1023 stroke_path(
1024 pixmap,
1025 &path,
1026 pass_color,
1027 stroke.width * (0.78 + pass as f32 * 0.13),
1028 stroke.blend_mode,
1029 );
1030 }
1031 Ok(())
1032}
1033
1034fn boundary_blend_mode(theme: Theme) -> BlendMode {
1035 if theme == Theme::Night {
1036 BlendMode::Plus
1037 } else {
1038 BlendMode::Multiply
1039 }
1040}
1041
1042pub(crate) fn jitter_points(points: &[Point], seed: u64, amplitude: f64) -> Vec<Point> {
1043 let mut state = seed;
1044 points
1045 .iter()
1046 .map(|point| {
1047 state = splitmix64(state);
1048 let dx = (unit_f64(state) - 0.5) * 2.0 * amplitude;
1049 state = splitmix64(state);
1050 let dy = (unit_f64(state) - 0.5) * 2.0 * amplitude;
1051 Point {
1052 x: point.x + dx,
1053 y: point.y + dy,
1054 }
1055 })
1056 .collect()
1057}
1058
1059#[derive(Debug, Default, Clone, Copy)]
1060pub(crate) struct LabelStats {
1061 pub files: usize,
1062 pub directories: usize,
1063}
1064
1065#[derive(Debug, Clone)]
1066pub(crate) struct LabelCommand {
1067 pub text: String,
1068 pub size: f32,
1069 pub color: Rgba,
1070 pub placement: LabelPlacement,
1071}
1072
1073#[derive(Debug, Clone, Copy)]
1074pub(crate) enum LabelPlacement {
1075 Horizontal { x: f32, baseline: f32 },
1076 Vertical { x: f32, y: f32 },
1077 Signature { x: f32, baseline: f32 },
1078}
1079
1080pub(crate) fn draw_labels(
1081 pixmap: &mut Pixmap,
1082 atlas: &Atlas,
1083 options: &LayoutOptions,
1084 palette: Palette,
1085) -> Result<LabelStats> {
1086 let Some(font) = load_label_font() else {
1087 return Ok(LabelStats::default());
1088 };
1089 let (commands, stats) = build_label_commands(&font, atlas, options, palette);
1090 for command in commands {
1091 match command.placement {
1092 LabelPlacement::Horizontal { x, baseline } => draw_text(
1093 pixmap,
1094 &font,
1095 &command.text,
1096 x,
1097 baseline,
1098 command.size,
1099 command.color,
1100 ),
1101 LabelPlacement::Vertical { x, y } => draw_text_rotated_clockwise(
1102 pixmap,
1103 &font,
1104 &command.text,
1105 x,
1106 y,
1107 command.size,
1108 command.color,
1109 ),
1110 LabelPlacement::Signature { x, baseline } => {
1111 draw_hollow_heart(
1112 pixmap,
1113 x,
1114 baseline - command.size * 0.88,
1115 command.size * 0.92,
1116 command.color,
1117 );
1118 draw_text(
1119 pixmap,
1120 &font,
1121 &command.text,
1122 x + command.size * 1.18,
1123 baseline,
1124 command.size,
1125 command.color,
1126 );
1127 }
1128 }
1129 }
1130 Ok(stats)
1131}
1132
1133pub(crate) fn collect_label_commands(
1134 atlas: &Atlas,
1135 options: &LayoutOptions,
1136 palette: Palette,
1137) -> (Vec<LabelCommand>, LabelStats) {
1138 let Some(font) = load_label_font() else {
1139 return (Vec::new(), LabelStats::default());
1140 };
1141 build_label_commands(&font, atlas, options, palette)
1142}
1143
1144fn build_label_commands(
1145 font: &Font,
1146 atlas: &Atlas,
1147 options: &LayoutOptions,
1148 palette: Palette,
1149) -> (Vec<LabelCommand>, LabelStats) {
1150 let scale = (options.width.min(options.height) as f32 / 1080.0).max(0.55);
1151 let root = &atlas.nodes[0];
1152 let title_size = 17.0 * scale;
1153 let title = root.name.to_uppercase();
1154 let title_baseline = (root.rect.y0 as f32 - 13.0 * scale).max(title_size + 2.0);
1155 let mut commands = vec![LabelCommand {
1156 text: title,
1157 size: title_size,
1158 color: palette.label,
1159 placement: LabelPlacement::Horizontal {
1160 x: root.rect.x0 as f32,
1161 baseline: title_baseline,
1162 },
1163 }];
1164
1165 let meta = format!(
1166 "{} FILES / {} CALLS",
1167 atlas.files().count(),
1168 atlas.calls.len()
1169 );
1170 let meta_size = 9.5 * scale;
1171 let meta_width = measure_text(font, &meta, meta_size);
1172 commands.push(LabelCommand {
1173 text: meta,
1174 size: meta_size,
1175 color: palette.label,
1176 placement: LabelPlacement::Horizontal {
1177 x: (root.rect.x1 as f32 - meta_width).max(root.rect.x0 as f32),
1178 baseline: title_baseline,
1179 },
1180 });
1181
1182 let footer_size = 8.5 * scale;
1183 let footer_baseline =
1184 (root.rect.y1 as f32 + 17.0 * scale).min(options.height as f32 - 5.0 * scale);
1185 let mut footer_color = palette.label;
1186 footer_color.a = footer_color.a.saturating_mul(3) / 4;
1187 let revision: String = atlas.revision.chars().take(12).collect();
1188 let provenance = format!(
1189 "GIT {} / {}",
1190 revision.to_uppercase(),
1191 current_utc_timestamp()
1192 );
1193 commands.push(LabelCommand {
1194 text: provenance,
1195 size: footer_size,
1196 color: footer_color,
1197 placement: LabelPlacement::Horizontal {
1198 x: root.rect.x0 as f32,
1199 baseline: footer_baseline,
1200 },
1201 });
1202
1203 let signature = "tessi";
1204 let signature_width = footer_size * 1.18 + measure_text(font, signature, footer_size);
1205 commands.push(LabelCommand {
1206 text: signature.to_owned(),
1207 size: footer_size,
1208 color: footer_color,
1209 placement: LabelPlacement::Signature {
1210 x: (root.rect.x1 as f32 - signature_width).max(root.rect.x0 as f32),
1211 baseline: footer_baseline,
1212 },
1213 });
1214
1215 let mut occupied = Vec::new();
1216 let mut stats = LabelStats::default();
1217 let mut directories: Vec<_> = atlas
1218 .nodes
1219 .iter()
1220 .filter(|node| {
1221 node.kind == NodeKind::Directory
1222 && node.id != 0
1223 && node.depth <= 2
1224 && node.rect.width() > 64.0 * scale as f64
1225 && node.rect.height() > 25.0 * scale as f64
1226 })
1227 .collect();
1228 directories.sort_by_key(|node| node.depth);
1229
1230 for node in directories {
1231 let size = if node.depth == 1 { 11.0 } else { 8.5 } * scale;
1232 let max_width = (node.rect.width() as f32 - 10.0 * scale).max(1.0);
1233 let text = node.name.to_uppercase();
1234 let fitted = fit_font_size(font, &text, size, max_width, 6.0 * scale);
1235 let x = node.rect.x0 as f32 + 5.0 * scale;
1236 let preferred_baseline = node.rect.y0 as f32 + fitted + 5.0 * scale;
1237 let Some((baseline, bounds)) = place_label(
1238 node.rect,
1239 x,
1240 preferred_baseline,
1241 fitted,
1242 measure_text(font, &text, fitted),
1243 2.5 * scale,
1244 &occupied,
1245 ) else {
1246 continue;
1247 };
1248 commands.push(LabelCommand {
1249 text,
1250 size: fitted,
1251 color: palette.label,
1252 placement: LabelPlacement::Horizontal { x, baseline },
1253 });
1254 occupied.push(bounds);
1255 stats.directories += 1;
1256 }
1257
1258 for node in atlas
1263 .nodes
1264 .iter()
1265 .filter(|node| node.kind == NodeKind::File)
1266 {
1267 let Some(label) = fit_file_label(font, &node.name, node.rect, scale, &occupied) else {
1268 continue;
1269 };
1270 let mut color = palette.label;
1271 color.a = color.a.saturating_mul(3) / 4;
1272 commands.push(LabelCommand {
1273 text: label.text,
1274 size: label.size,
1275 color,
1276 placement: label.placement,
1277 });
1278 stats.files += 1;
1279 }
1280 (commands, stats)
1281}
1282
1283#[derive(Debug, Clone)]
1284struct FittedFileLabel {
1285 text: String,
1286 size: f32,
1287 placement: LabelPlacement,
1288}
1289
1290fn fit_file_label(
1291 font: &Font,
1292 text: &str,
1293 container: Rect,
1294 scale: f32,
1295 occupied: &[LabelBounds],
1296) -> Option<FittedFileLabel> {
1297 let padding = (1.8 * scale)
1298 .min(container.width() as f32 * 0.16)
1299 .min(container.height() as f32 * 0.16)
1300 .max(0.6);
1301 let fitted = if container.height() > container.width() * 1.8 {
1302 fit_vertical_file_label(font, text, container, scale, padding, occupied)
1303 .or_else(|| fit_horizontal_file_label(font, text, container, scale, padding, occupied))
1304 } else {
1305 fit_horizontal_file_label(font, text, container, scale, padding, occupied)
1306 .or_else(|| fit_vertical_file_label(font, text, container, scale, padding, occupied))
1307 };
1308 fitted.or_else(|| fit_compact_file_marker(font, text, container, scale, occupied))
1309}
1310
1311fn fit_compact_file_marker(
1312 font: &Font,
1313 text: &str,
1314 container: Rect,
1315 scale: f32,
1316 occupied: &[LabelBounds],
1317) -> Option<FittedFileLabel> {
1318 let marker = text.chars().next()?.to_string();
1319 let size = 1.5 * scale;
1320 let width = measure_text(font, &marker, size);
1321 let padding = 0.3_f32.min(container.width() as f32 * 0.08);
1322 let x_positions = [
1323 container.x0 as f32 + padding,
1324 (container.x0 + container.x1) as f32 / 2.0 - width / 2.0,
1325 ];
1326 let baselines = [
1327 container.y1 as f32 - padding - size * 0.22,
1328 container.y0 as f32 + padding + size,
1329 (container.y0 + container.y1) as f32 / 2.0 + size * 0.39,
1330 ];
1331 for x in x_positions {
1332 for baseline in baselines {
1333 let bounds = label_bounds(x, baseline, width, size);
1334 if label_fits(container, bounds)
1335 && !occupied.iter().any(|other| bounds.overlaps(*other, 0.0))
1336 {
1337 return Some(FittedFileLabel {
1338 text: marker,
1339 size,
1340 placement: LabelPlacement::Horizontal { x, baseline },
1341 });
1342 }
1343 }
1344 }
1345 None
1346}
1347
1348fn fit_horizontal_file_label(
1349 font: &Font,
1350 text: &str,
1351 container: Rect,
1352 scale: f32,
1353 padding: f32,
1354 occupied: &[LabelBounds],
1355) -> Option<FittedFileLabel> {
1356 let available_width = container.width() as f32 - 2.0 * padding;
1357 let available_height = container.height() as f32 - 2.0 * padding;
1358 let preferred = (7.5 * scale).min(available_height / 1.22);
1359 let minimum = 1.5 * scale;
1360 if available_width <= 0.0 || preferred < minimum {
1361 return None;
1362 }
1363
1364 let preferred_width = measure_text(font, text, preferred).max(1.0);
1365 let required_size = preferred * available_width / preferred_width;
1366 let size = required_size.clamp(minimum, preferred);
1367 let fitted_text = truncate_text_to_width(font, text, size, available_width)?;
1368 let width = measure_text(font, &fitted_text, size);
1369 let x = container.x0 as f32 + padding;
1370 let bottom = container.y1 as f32 - padding - size * 0.22;
1371 let top = container.y0 as f32 + padding + size;
1372 let middle = (container.y0 + container.y1) as f32 / 2.0 + size * 0.39;
1373
1374 for baseline in [bottom, top, middle] {
1375 let bounds = label_bounds(x, baseline, width, size);
1376 if label_fits(container, bounds)
1377 && !occupied
1378 .iter()
1379 .any(|other| bounds.overlaps(*other, 0.7 * scale))
1380 {
1381 return Some(FittedFileLabel {
1382 text: fitted_text,
1383 size,
1384 placement: LabelPlacement::Horizontal { x, baseline },
1385 });
1386 }
1387 }
1388 None
1389}
1390
1391fn fit_vertical_file_label(
1392 font: &Font,
1393 text: &str,
1394 container: Rect,
1395 scale: f32,
1396 padding: f32,
1397 occupied: &[LabelBounds],
1398) -> Option<FittedFileLabel> {
1399 let available_cross = container.width() as f32 - 2.0 * padding;
1400 let available_length = container.height() as f32 - 2.0 * padding;
1401 let preferred = (7.5 * scale).min(available_cross / 1.22);
1402 let minimum = 1.5 * scale;
1403 if available_length <= 0.0 || preferred < minimum {
1404 return None;
1405 }
1406
1407 let preferred_width = measure_text(font, text, preferred).max(1.0);
1408 let required_size = preferred * available_length / preferred_width;
1409 let size = required_size.clamp(minimum, preferred);
1410 let fitted_text = truncate_text_to_width(font, text, size, available_length)?;
1411 let text_length = measure_text(font, &fitted_text, size);
1412 let label_width = size * 1.22;
1413 let left = container.x0 as f32 + padding;
1414 let right = container.x1 as f32 - padding - label_width;
1415 let center_x = (container.x0 + container.x1) as f32 / 2.0 - label_width / 2.0;
1416 let top = container.y0 as f32 + padding;
1417 let bottom = container.y1 as f32 - padding - text_length;
1418 let center_y = (container.y0 + container.y1) as f32 / 2.0 - text_length / 2.0;
1419
1420 for (x, y) in [
1421 (left, bottom),
1422 (right, bottom),
1423 (left, top),
1424 (right, top),
1425 (center_x, center_y),
1426 ] {
1427 let bounds = LabelBounds {
1428 x0: x,
1429 y0: y,
1430 x1: x + label_width,
1431 y1: y + text_length,
1432 };
1433 if label_fits(container, bounds)
1434 && !occupied
1435 .iter()
1436 .any(|other| bounds.overlaps(*other, 0.7 * scale))
1437 {
1438 return Some(FittedFileLabel {
1439 text: fitted_text,
1440 size,
1441 placement: LabelPlacement::Vertical { x, y },
1442 });
1443 }
1444 }
1445 None
1446}
1447
1448fn truncate_text_to_width(font: &Font, text: &str, size: f32, max_width: f32) -> Option<String> {
1449 if measure_text(font, text, size) <= max_width {
1450 return Some(text.to_owned());
1451 }
1452 let ellipsis = "...";
1453 let ellipsis_width = measure_text(font, ellipsis, size);
1454 let mut output = String::new();
1455 for character in text.chars() {
1456 let candidate_width = measure_text(font, &output, size)
1457 + font.metrics(character, size).advance_width
1458 + ellipsis_width;
1459 if candidate_width > max_width {
1460 break;
1461 }
1462 output.push(character);
1463 }
1464 if output.is_empty() {
1465 return None;
1466 }
1467 output.push_str(ellipsis);
1468 Some(output)
1469}
1470
1471#[derive(Debug, Clone, Copy, PartialEq)]
1472struct LabelBounds {
1473 x0: f32,
1474 y0: f32,
1475 x1: f32,
1476 y1: f32,
1477}
1478
1479impl LabelBounds {
1480 fn overlaps(self, other: Self, gap: f32) -> bool {
1481 self.x0 < other.x1 + gap
1482 && self.x1 > other.x0 - gap
1483 && self.y0 < other.y1 + gap
1484 && self.y1 > other.y0 - gap
1485 }
1486}
1487
1488fn label_bounds(x: f32, baseline: f32, width: f32, size: f32) -> LabelBounds {
1489 LabelBounds {
1490 x0: x,
1491 y0: baseline - size,
1492 x1: x + width,
1493 y1: baseline + size * 0.22,
1494 }
1495}
1496
1497fn label_fits(container: Rect, bounds: LabelBounds) -> bool {
1498 bounds.x0 >= container.x0 as f32
1499 && bounds.y0 >= container.y0 as f32
1500 && bounds.x1 <= container.x1 as f32
1501 && bounds.y1 <= container.y1 as f32
1502}
1503
1504fn place_label(
1505 container: Rect,
1506 x: f32,
1507 preferred_baseline: f32,
1508 size: f32,
1509 width: f32,
1510 gap: f32,
1511 occupied: &[LabelBounds],
1512) -> Option<(f32, LabelBounds)> {
1513 let mut baseline = preferred_baseline;
1514 for _ in 0..=occupied.len() {
1515 let bounds = label_bounds(x, baseline, width, size);
1516 if !label_fits(container, bounds) {
1517 return None;
1518 }
1519 let colliding_bottom = occupied
1520 .iter()
1521 .filter(|other| bounds.overlaps(**other, gap))
1522 .map(|other| other.y1)
1523 .reduce(f32::max);
1524 let Some(bottom) = colliding_bottom else {
1525 return Some((baseline, bounds));
1526 };
1527 baseline = bottom + gap + size;
1528 }
1529 None
1530}
1531
1532fn load_label_font() -> Option<Font> {
1533 const FONT_PATHS: &[&str] = &[
1534 "/System/Library/Fonts/SFNSMono.ttf",
1535 "/System/Library/Fonts/Supplemental/Courier New.ttf",
1536 "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
1537 "/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
1538 ];
1539 FONT_PATHS.iter().find_map(|path| {
1540 let bytes = fs::read(path).ok()?;
1541 Font::from_bytes(bytes, FontSettings::default()).ok()
1542 })
1543}
1544
1545fn fit_font_size(font: &Font, text: &str, preferred: f32, max_width: f32, minimum: f32) -> f32 {
1546 let width = measure_text(font, text, preferred).max(1.0);
1547 (preferred * (max_width / width).min(1.0)).max(minimum.min(preferred))
1548}
1549
1550fn measure_text(font: &Font, text: &str, size: f32) -> f32 {
1551 text.chars()
1552 .map(|character| font.metrics(character, size).advance_width)
1553 .sum()
1554}
1555
1556fn draw_text(
1557 pixmap: &mut Pixmap,
1558 font: &Font,
1559 text: &str,
1560 x: f32,
1561 baseline: f32,
1562 size: f32,
1563 color: Rgba,
1564) {
1565 let width = pixmap.width() as i32;
1566 let height = pixmap.height() as i32;
1567 let mut pen_x = x;
1568 let data = pixmap.data_mut();
1569 for character in text.chars() {
1570 let (metrics, bitmap) = font.rasterize(character, size);
1571 let glyph_x = pen_x.round() as i32 + metrics.xmin;
1572 let glyph_y = baseline.round() as i32 - metrics.height as i32 - metrics.ymin;
1573 for row in 0..metrics.height {
1574 for column in 0..metrics.width {
1575 let destination_x = glyph_x + column as i32;
1576 let destination_y = glyph_y + row as i32;
1577 if destination_x < 0
1578 || destination_y < 0
1579 || destination_x >= width
1580 || destination_y >= height
1581 {
1582 continue;
1583 }
1584 let coverage = bitmap[row * metrics.width + column] as f32 / 255.0;
1585 let alpha = coverage * (color.a as f32 / 255.0);
1586 if alpha <= 0.0 {
1587 continue;
1588 }
1589 let offset = ((destination_y * width + destination_x) * 4) as usize;
1590 for (channel, source) in [color.r, color.g, color.b].into_iter().enumerate() {
1591 let destination = data[offset + channel] as f32;
1592 data[offset + channel] =
1593 (source as f32 * alpha + destination * (1.0 - alpha)).round() as u8;
1594 }
1595 }
1596 }
1597 pen_x += metrics.advance_width;
1598 }
1599}
1600
1601fn draw_text_rotated_clockwise(
1602 pixmap: &mut Pixmap,
1603 font: &Font,
1604 text: &str,
1605 x: f32,
1606 y: f32,
1607 size: f32,
1608 color: Rgba,
1609) {
1610 let canvas_width = pixmap.width() as i32;
1611 let canvas_height = pixmap.height() as i32;
1612 let normal_height = (size * 1.22).ceil().max(1.0) as i32;
1613 let origin_x = x.round() as i32;
1614 let origin_y = y.round() as i32;
1615 let mut pen_x = 0.0_f32;
1616 let data = pixmap.data_mut();
1617
1618 for character in text.chars() {
1619 let (metrics, bitmap) = font.rasterize(character, size);
1620 let glyph_x = pen_x.round() as i32 + metrics.xmin;
1621 let glyph_y = size.round() as i32 - metrics.height as i32 - metrics.ymin;
1622 for row in 0..metrics.height {
1623 for column in 0..metrics.width {
1624 let normal_x = glyph_x + column as i32;
1625 let normal_y = glyph_y + row as i32;
1626 if normal_y < 0 || normal_y >= normal_height {
1627 continue;
1628 }
1629 let destination_x = origin_x + normal_height - 1 - normal_y;
1630 let destination_y = origin_y + normal_x;
1631 if destination_x < 0
1632 || destination_y < 0
1633 || destination_x >= canvas_width
1634 || destination_y >= canvas_height
1635 {
1636 continue;
1637 }
1638 let coverage = bitmap[row * metrics.width + column] as f32 / 255.0;
1639 let alpha = coverage * (color.a as f32 / 255.0);
1640 if alpha <= 0.0 {
1641 continue;
1642 }
1643 let offset = ((destination_y * canvas_width + destination_x) * 4) as usize;
1644 for (channel, source) in [color.r, color.g, color.b].into_iter().enumerate() {
1645 let destination = data[offset + channel] as f32;
1646 data[offset + channel] =
1647 (source as f32 * alpha + destination * (1.0 - alpha)).round() as u8;
1648 }
1649 }
1650 }
1651 pen_x += metrics.advance_width;
1652 }
1653}
1654
1655fn draw_hollow_heart(pixmap: &mut Pixmap, x: f32, y: f32, size: f32, color: Rgba) {
1656 let mut builder = PathBuilder::new();
1657 builder.move_to(x + size * 0.5, y + size * 0.92);
1658 builder.cubic_to(
1659 x + size * 0.08,
1660 y + size * 0.64,
1661 x,
1662 y + size * 0.34,
1663 x + size * 0.21,
1664 y + size * 0.19,
1665 );
1666 builder.cubic_to(
1667 x + size * 0.36,
1668 y + size * 0.08,
1669 x + size * 0.5,
1670 y + size * 0.19,
1671 x + size * 0.5,
1672 y + size * 0.32,
1673 );
1674 builder.cubic_to(
1675 x + size * 0.5,
1676 y + size * 0.19,
1677 x + size * 0.64,
1678 y + size * 0.08,
1679 x + size * 0.79,
1680 y + size * 0.19,
1681 );
1682 builder.cubic_to(
1683 x + size,
1684 y + size * 0.34,
1685 x + size * 0.92,
1686 y + size * 0.64,
1687 x + size * 0.5,
1688 y + size * 0.92,
1689 );
1690 if let Some(path) = builder.finish() {
1691 stroke_path(
1692 pixmap,
1693 &path,
1694 color,
1695 (size * 0.075).max(0.55),
1696 BlendMode::SourceOver,
1697 );
1698 }
1699}
1700
1701fn current_utc_timestamp() -> String {
1702 let seconds = SystemTime::now()
1703 .duration_since(UNIX_EPOCH)
1704 .unwrap_or_default()
1705 .as_secs()
1706 .min(i64::MAX as u64) as i64;
1707 format_utc_timestamp(seconds)
1708}
1709
1710fn format_utc_timestamp(seconds: i64) -> String {
1711 let days = seconds.div_euclid(86_400);
1712 let seconds_of_day = seconds.rem_euclid(86_400);
1713 let hour = seconds_of_day / 3_600;
1714 let minute = seconds_of_day % 3_600 / 60;
1715 let second = seconds_of_day % 60;
1716
1717 let shifted = days + 719_468;
1719 let era = if shifted >= 0 {
1720 shifted
1721 } else {
1722 shifted - 146_096
1723 } / 146_097;
1724 let day_of_era = shifted - era * 146_097;
1725 let year_of_era =
1726 (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1727 let mut year = year_of_era + era * 400;
1728 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1729 let month_prime = (5 * day_of_year + 2) / 153;
1730 let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
1731 let month = month_prime + if month_prime < 10 { 3 } else { -9 };
1732 year += i64::from(month <= 2);
1733
1734 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02} UTC")
1735}
1736
1737fn splitmix64(mut value: u64) -> u64 {
1738 value = value.wrapping_add(0x9e3779b97f4a7c15);
1739 value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
1740 value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
1741 value ^ (value >> 31)
1742}
1743
1744fn unit_f64(value: u64) -> f64 {
1745 value as f64 / u64::MAX as f64
1746}
1747
1748fn polygon_path(points: &[Point]) -> Result<SkiaPath> {
1749 let mut builder = PathBuilder::new();
1750 let Some(first) = points.first() else {
1751 bail!("cannot create an empty polygon");
1752 };
1753 builder.move_to(first.x as f32, first.y as f32);
1754 for point in &points[1..] {
1755 builder.line_to(point.x as f32, point.y as f32);
1756 }
1757 builder.close();
1758 builder.finish().context("invalid polygon geometry")
1759}
1760
1761fn open_path(points: &[Point]) -> Result<SkiaPath> {
1762 let mut builder = PathBuilder::new();
1763 let Some(first) = points.first() else {
1764 bail!("cannot create an empty path");
1765 };
1766 builder.move_to(first.x as f32, first.y as f32);
1767 for point in &points[1..] {
1768 builder.line_to(point.x as f32, point.y as f32);
1769 }
1770 builder.finish().context("invalid path geometry")
1771}
1772
1773fn fill_path(pixmap: &mut Pixmap, path: &SkiaPath, color: Rgba, blend_mode: BlendMode) {
1774 let mut paint = Paint {
1775 anti_alias: true,
1776 blend_mode,
1777 ..Paint::default()
1778 };
1779 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1780 pixmap.fill_path(path, &paint, FillRule::Winding, Transform::identity(), None);
1781}
1782
1783fn stroke_path(
1784 pixmap: &mut Pixmap,
1785 path: &SkiaPath,
1786 color: Rgba,
1787 width: f32,
1788 blend_mode: BlendMode,
1789) {
1790 let mut paint = Paint {
1791 anti_alias: true,
1792 blend_mode,
1793 ..Paint::default()
1794 };
1795 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1796 let stroke = Stroke {
1797 width,
1798 line_cap: LineCap::Round,
1799 line_join: LineJoin::Round,
1800 ..Stroke::default()
1801 };
1802 pixmap.stroke_path(path, &paint, &stroke, Transform::identity(), None);
1803}
1804
1805#[derive(Debug, Clone, Copy)]
1806pub(crate) struct Rgba {
1807 pub r: u8,
1808 pub g: u8,
1809 pub b: u8,
1810 pub a: u8,
1811}
1812
1813impl Rgba {
1814 pub(crate) const fn rgb(r: u8, g: u8, b: u8) -> Self {
1815 Self { r, g, b, a: 255 }
1816 }
1817
1818 pub(crate) const fn with_alpha(r: u8, g: u8, b: u8, a: u8) -> Self {
1819 Self { r, g, b, a }
1820 }
1821
1822 fn color(self) -> Color {
1823 Color::from_rgba8(self.r, self.g, self.b, self.a)
1824 }
1825
1826 pub(crate) fn hex(self) -> String {
1827 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
1828 }
1829}
1830
1831#[derive(Debug, Clone, Copy)]
1832pub(crate) struct Palette {
1833 pub background: Rgba,
1834 pub land: Rgba,
1835 pub paper_fiber: Rgba,
1836 pub outer_border: Rgba,
1837 pub directory_border: Rgba,
1838 pub file_border: Rgba,
1839 pub label: Rgba,
1840 pub direction_source: Rgba,
1841 pub direction_target: Rgba,
1842 pub elixir: Rgba,
1843 pub rust: Rgba,
1844 pub tests: Rgba,
1845 pub docs: Rgba,
1846 pub config: Rgba,
1847 pub other: Rgba,
1848}
1849
1850impl Palette {
1851 pub(crate) fn for_theme(theme: Theme) -> Self {
1852 match theme {
1853 Theme::Architect => Self {
1854 background: Rgba::rgb(241, 238, 229),
1855 land: Rgba::rgb(246, 243, 235),
1856 paper_fiber: Rgba::with_alpha(83, 77, 65, 8),
1857 outer_border: Rgba::with_alpha(48, 48, 45, 150),
1858 directory_border: Rgba::with_alpha(54, 55, 53, 105),
1859 file_border: Rgba::with_alpha(68, 68, 64, 48),
1860 label: Rgba::with_alpha(48, 48, 45, 150),
1861 direction_source: Rgba::rgb(172, 52, 68),
1862 direction_target: Rgba::rgb(34, 92, 150),
1863 elixir: Rgba::rgb(234, 231, 237),
1864 rust: Rgba::rgb(238, 231, 222),
1865 tests: Rgba::rgb(230, 235, 230),
1866 docs: Rgba::rgb(238, 236, 229),
1867 config: Rgba::rgb(234, 233, 228),
1868 other: Rgba::rgb(241, 238, 231),
1869 },
1870 Theme::Night => Self {
1871 background: Rgba::rgb(6, 10, 17),
1872 land: Rgba::rgb(13, 20, 30),
1873 paper_fiber: Rgba::with_alpha(155, 175, 202, 6),
1874 outer_border: Rgba::with_alpha(160, 180, 205, 155),
1875 directory_border: Rgba::with_alpha(130, 150, 175, 70),
1876 file_border: Rgba::with_alpha(118, 140, 163, 32),
1877 label: Rgba::with_alpha(205, 218, 235, 215),
1878 direction_source: Rgba::rgb(255, 70, 142),
1879 direction_target: Rgba::rgb(55, 210, 255),
1880 elixir: Rgba::rgb(22, 30, 42),
1881 rust: Rgba::rgb(24, 32, 43),
1882 tests: Rgba::rgb(21, 31, 41),
1883 docs: Rgba::rgb(20, 28, 39),
1884 config: Rgba::rgb(25, 32, 42),
1885 other: Rgba::rgb(18, 26, 37),
1886 },
1887 Theme::Ink => Self {
1888 background: Rgba::rgb(245, 242, 232),
1889 land: Rgba::rgb(235, 231, 218),
1890 paper_fiber: Rgba::with_alpha(70, 62, 49, 0),
1891 outer_border: Rgba::with_alpha(29, 43, 67, 170),
1892 directory_border: Rgba::with_alpha(40, 52, 73, 70),
1893 file_border: Rgba::with_alpha(40, 52, 73, 30),
1894 label: Rgba::with_alpha(29, 43, 67, 150),
1895 direction_source: Rgba::rgb(190, 35, 70),
1896 direction_target: Rgba::rgb(30, 70, 175),
1897 elixir: Rgba::rgb(225, 218, 235),
1898 rust: Rgba::rgb(235, 219, 211),
1899 tests: Rgba::rgb(214, 231, 227),
1900 docs: Rgba::rgb(226, 226, 218),
1901 config: Rgba::rgb(220, 219, 215),
1902 other: Rgba::rgb(231, 228, 218),
1903 },
1904 Theme::SolarizedDark => Self {
1905 background: Rgba::rgb(0, 43, 54),
1906 land: Rgba::rgb(7, 54, 66),
1907 paper_fiber: Rgba::with_alpha(255, 255, 255, 0),
1908 outer_border: Rgba::with_alpha(147, 161, 161, 170),
1909 directory_border: Rgba::with_alpha(88, 110, 117, 90),
1910 file_border: Rgba::with_alpha(88, 110, 117, 35),
1911 label: Rgba::with_alpha(147, 161, 161, 170),
1912 direction_source: Rgba::rgb(220, 50, 47),
1913 direction_target: Rgba::rgb(38, 139, 210),
1914 elixir: Rgba::rgb(32, 65, 82),
1915 rust: Rgba::rgb(73, 55, 44),
1916 tests: Rgba::rgb(20, 73, 70),
1917 docs: Rgba::rgb(28, 60, 69),
1918 config: Rgba::rgb(48, 60, 64),
1919 other: Rgba::rgb(18, 55, 64),
1920 },
1921 Theme::SolarizedLight => Self {
1922 background: Rgba::rgb(253, 246, 227),
1923 land: Rgba::rgb(238, 232, 213),
1924 paper_fiber: Rgba::with_alpha(70, 62, 49, 0),
1925 outer_border: Rgba::with_alpha(88, 110, 117, 170),
1926 directory_border: Rgba::with_alpha(101, 123, 131, 80),
1927 file_border: Rgba::with_alpha(101, 123, 131, 35),
1928 label: Rgba::with_alpha(88, 110, 117, 160),
1929 direction_source: Rgba::rgb(220, 50, 47),
1930 direction_target: Rgba::rgb(38, 139, 210),
1931 elixir: Rgba::rgb(231, 222, 238),
1932 rust: Rgba::rgb(240, 219, 201),
1933 tests: Rgba::rgb(218, 235, 224),
1934 docs: Rgba::rgb(235, 230, 213),
1935 config: Rgba::rgb(226, 224, 211),
1936 other: Rgba::rgb(239, 233, 216),
1937 },
1938 }
1939 }
1940
1941 pub(crate) fn file_color(self, language: &str) -> Rgba {
1942 match language {
1943 "elixir" => self.elixir,
1944 "rust" => self.rust,
1945 "markdown" => self.docs,
1946 "config" | "data" => self.config,
1947 language if language.contains("test") => self.tests,
1948 _ => self.other,
1949 }
1950 }
1951}
1952
1953#[cfg(test)]
1954mod tests {
1955 use super::*;
1956
1957 #[test]
1958 fn utc_footer_timestamp_uses_stable_iso_style() {
1959 assert_eq!(format_utc_timestamp(0), "1970-01-01 00:00:00 UTC");
1960 assert_eq!(format_utc_timestamp(86_400), "1970-01-02 00:00:00 UTC");
1961 }
1962
1963 #[test]
1964 fn directional_palette_has_one_unambiguous_source_to_target_ramp() {
1965 let palette = Palette::for_theme(Theme::Night);
1966 let source = linear_rgb(palette.direction_source);
1967 let target = linear_rgb(palette.direction_target);
1968 assert_ne!(source, target);
1969 assert!(source[0] > target[0], "source is the pink end of the ramp");
1970 assert!(target[2] > source[2], "target is the cyan end of the ramp");
1971 }
1972
1973 #[test]
1974 fn night_treemap_uses_one_subtle_blueprint_family() {
1975 let palette = Palette::for_theme(Theme::Night);
1976 let fills = [
1977 palette.elixir,
1978 palette.rust,
1979 palette.tests,
1980 palette.docs,
1981 palette.config,
1982 palette.other,
1983 ];
1984 assert!(
1985 fills
1986 .iter()
1987 .all(|color| color.b >= color.g && color.g >= color.r)
1988 );
1989 for left in fills {
1990 for right in fills {
1991 assert!(left.r.abs_diff(right.r) <= 7);
1992 assert!(left.g.abs_diff(right.g) <= 7);
1993 assert!(left.b.abs_diff(right.b) <= 7);
1994 }
1995 }
1996 }
1997
1998 #[test]
1999 fn truncated_poster_labels_use_pdf_safe_ascii_ellipsis() {
2000 let font = load_label_font().expect("test font");
2001 let text = truncate_text_to_width(&font, "settings_table_model.ex", 12.0, 85.0)
2002 .expect("truncated label");
2003 assert!(text.is_ascii());
2004 assert!(text.ends_with("..."));
2005 }
2006
2007 #[test]
2008 fn unavailable_gpu_capabilities_fall_back_but_render_failures_do_not() {
2009 assert!(gpu_is_unavailable(&anyhow::anyhow!(
2010 "no compatible GPU adapter is available"
2011 )));
2012 assert!(gpu_is_unavailable(&anyhow::anyhow!(
2013 "adapter does not support blendable RGBA16Float density textures"
2014 )));
2015 assert!(gpu_is_unavailable(&anyhow::anyhow!(
2016 "adapter does not support 4x multisampled RGBA16Float density textures"
2017 )));
2018 assert!(!gpu_is_unavailable(&anyhow::anyhow!("GPU readback failed")));
2019 }
2020
2021 #[test]
2022 fn child_label_moves_below_an_overlapping_parent_label() {
2023 let container = Rect {
2024 x0: 0.0,
2025 y0: 0.0,
2026 x1: 200.0,
2027 y1: 100.0,
2028 };
2029 let parent = label_bounds(5.0, 16.0, 70.0, 11.0);
2030 let (baseline, child) =
2031 place_label(container, 5.0, 14.0, 9.0, 60.0, 3.0, &[parent]).unwrap();
2032
2033 assert!(baseline > 16.0);
2034 assert!(!child.overlaps(parent, 3.0));
2035 assert!(label_fits(container, child));
2036 }
2037
2038 #[test]
2039 fn label_is_omitted_when_no_collision_free_band_fits() {
2040 let container = Rect {
2041 x0: 0.0,
2042 y0: 0.0,
2043 x1: 100.0,
2044 y1: 24.0,
2045 };
2046 let parent = label_bounds(4.0, 13.0, 70.0, 10.0);
2047
2048 assert!(place_label(container, 4.0, 12.0, 9.0, 60.0, 3.0, &[parent]).is_none());
2049 }
2050
2051 #[test]
2052 fn small_file_parcels_receive_abbreviated_micro_labels() {
2053 let Some(font) = load_label_font() else {
2054 return;
2055 };
2056 let parcel = Rect {
2057 x0: 0.0,
2058 y0: 0.0,
2059 x1: 42.0,
2060 y1: 12.0,
2061 };
2062 let label = fit_file_label(&font, "a_very_long_source_filename.ex", parcel, 1.0, &[])
2063 .expect("small but readable parcel should have a label");
2064
2065 assert!(label.text.ends_with("..."));
2066 assert!(label.size >= 1.5);
2067 assert!(measure_text(&font, &label.text, label.size) <= parcel.width() as f32);
2068 }
2069
2070 #[test]
2071 fn microscopic_parcels_receive_a_compact_zoom_label() {
2072 let Some(font) = load_label_font() else {
2073 return;
2074 };
2075 let parcel = Rect {
2076 x0: 0.0,
2077 y0: 0.0,
2078 x1: 4.0,
2079 y1: 4.0,
2080 };
2081
2082 let label = fit_file_label(&font, "tiny.ex", parcel, 1.0, &[])
2083 .expect("even a microscopic parcel should retain a zoom label");
2084 assert!(!label.text.is_empty());
2085 }
2086
2087 #[test]
2088 fn narrow_tall_parcels_use_vertical_labels() {
2089 let Some(font) = load_label_font() else {
2090 return;
2091 };
2092 let parcel = Rect {
2093 x0: 0.0,
2094 y0: 0.0,
2095 x1: 12.0,
2096 y1: 70.0,
2097 };
2098 let label = fit_file_label(&font, "formatter.ex", parcel, 1.0, &[])
2099 .expect("tall parcel should have a rotated label");
2100
2101 assert!(matches!(label.placement, LabelPlacement::Vertical { .. }));
2102 }
2103
2104 #[test]
2105 fn density_exposure_preserves_small_graphs_and_lowers_large_graphs() {
2106 let options = RenderOptions::default();
2107 assert_eq!(effective_call_opacity(2_500, &options), 34);
2108 assert_eq!(effective_call_opacity(21_307, &options), 12);
2109
2110 let fixed = RenderOptions {
2111 density_aware_exposure: false,
2112 ..options
2113 };
2114 assert_eq!(effective_call_opacity(21_307, &fixed), 34);
2115 }
2116
2117 #[test]
2118 fn optical_density_is_order_independent_in_light_and_dark_themes() {
2119 let first = [Point { x: 4.0, y: 8.0 }, Point { x: 60.0, y: 55.0 }];
2120 let second = [Point { x: 5.0, y: 56.0 }, Point { x: 59.0, y: 7.0 }];
2121 for theme in [Theme::Architect, Theme::Night] {
2122 let palette = Palette::for_theme(theme);
2123 let mut forward = OpticalDensityLayer::new(64, 64).unwrap();
2124 forward.deposit_pencil_call(
2125 &first,
2126 palette.direction_source,
2127 palette.direction_target,
2128 34,
2129 1.4,
2130 11,
2131 );
2132 forward.deposit_pencil_call(
2133 &second,
2134 palette.direction_target,
2135 palette.direction_source,
2136 34,
2137 1.4,
2138 22,
2139 );
2140 let mut reverse = OpticalDensityLayer::new(64, 64).unwrap();
2141 reverse.deposit_pencil_call(
2142 &second,
2143 palette.direction_target,
2144 palette.direction_source,
2145 34,
2146 1.4,
2147 22,
2148 );
2149 reverse.deposit_pencil_call(
2150 &first,
2151 palette.direction_source,
2152 palette.direction_target,
2153 34,
2154 1.4,
2155 11,
2156 );
2157
2158 assert_eq!(
2159 forward.resolve().unwrap().data(),
2160 reverse.resolve().unwrap().data()
2161 );
2162 }
2163 }
2164
2165 #[test]
2166 fn repeated_routes_deposit_more_optical_density_in_every_theme() {
2167 let points = [Point { x: 4.0, y: 32.0 }, Point { x: 60.0, y: 32.0 }];
2168 for theme in [Theme::Architect, Theme::Night] {
2169 let palette = Palette::for_theme(theme);
2170 let mut single = OpticalDensityLayer::new(64, 64).unwrap();
2171 single.deposit_pencil_call(
2172 &points,
2173 palette.direction_source,
2174 palette.direction_target,
2175 34,
2176 1.4,
2177 11,
2178 );
2179 let single = single.resolve().unwrap();
2180 let mut double = OpticalDensityLayer::new(64, 64).unwrap();
2181 for _ in 0..2 {
2182 double.deposit_pencil_call(
2183 &points,
2184 palette.direction_source,
2185 palette.direction_target,
2186 34,
2187 1.4,
2188 11,
2189 );
2190 }
2191 let double = double.resolve().unwrap();
2192 let alpha = |pixmap: &Pixmap| {
2193 pixmap
2194 .data()
2195 .chunks_exact(4)
2196 .map(|pixel| u64::from(pixel[3]))
2197 .sum::<u64>()
2198 };
2199 assert!(alpha(&double) > alpha(&single));
2200 }
2201 }
2202}