Compare commits
4 Commits
printer-ca
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0383b4e8cc | ||
| a1ae6fc282 | |||
|
|
a465c5c88f | ||
|
|
39e055eb0e |
4
.env
4
.env
@@ -11,8 +11,8 @@ PHOTOBOOTH_PRINTER=/dev/usb/lp0
|
||||
PHOTOBOOTH_PRINTER_DOTS=576
|
||||
|
||||
# Mid-tone brightening before dithering, offsetting thermal dot gain
|
||||
# (1.8-2.5 is typical; 1 disables it).
|
||||
PHOTOBOOTH_PRINTER_GAMMA=2.0
|
||||
# (1.8-3.0 is typical; 1 disables it).
|
||||
PHOTOBOOTH_PRINTER_GAMMA=2.7
|
||||
|
||||
# Head energy in percent of rated (70-130) and print speed: quality (120 mm/s),
|
||||
# low (150), silent (180) or high (200). Both are SII RP-D10 commands (DC2 ~
|
||||
|
||||
311
src/artwork.rs
Normal file
311
src/artwork.rs
Normal file
@@ -0,0 +1,311 @@
|
||||
//! Christmas pixel art that frames the photo on every printed slip.
|
||||
//!
|
||||
//! Above the photo stands a snowy scene of fir trees and presents under
|
||||
//! falling snow; below it hang Christmas ornaments on strings of different
|
||||
//! lengths. Both strips are solid next to the photo and thin out away from it,
|
||||
//! and the motifs are arranged at random, so every slip gets its own.
|
||||
|
||||
/// Lines of pixels in a strip.
|
||||
pub const ROWS: usize = 12;
|
||||
/// Pixels across the paper that a strip aims for; the printer picks the pixel
|
||||
/// size that comes closest (6 dots on 80 mm paper, 4 on 58 mm).
|
||||
pub const CELLS_ACROSS: usize = 96;
|
||||
|
||||
/// A strip's pixels, line by line from top to bottom as printed.
|
||||
pub type Lines = [Vec<bool>; ROWS];
|
||||
|
||||
/// Hand-drawn motif, `#` for a black pixel; every row is equally wide.
|
||||
type Sprite = &'static [&'static str];
|
||||
|
||||
/// Fir tree with a star on top, a trunk and two baubles left blank.
|
||||
const BIG_TREE: Sprite = &[
|
||||
".....#.....",
|
||||
"....###....",
|
||||
".....#.....",
|
||||
"....###....",
|
||||
"...#####...",
|
||||
"....###....",
|
||||
"...##.##...",
|
||||
"..#######..",
|
||||
".#########.",
|
||||
"####.######",
|
||||
"....###....",
|
||||
];
|
||||
const SMALL_TREE: Sprite = &[
|
||||
"...#...", //
|
||||
"..###..", "...#...", "..###..", ".##.##.", "..###..", ".#####.", "#######", "...#...",
|
||||
];
|
||||
/// Present with a bow and a ribbon left blank.
|
||||
const PRESENT: Sprite = &[
|
||||
".##.##.", //
|
||||
"...#...", "#######", "###.###", "###.###", "###.###",
|
||||
];
|
||||
const SMALL_PRESENT: Sprite = &[
|
||||
".#.#.", //
|
||||
"..#..", "#####", "##.##", "##.##",
|
||||
];
|
||||
/// Round bauble with its cap and a highlight.
|
||||
const BAUBLE: Sprite = &[
|
||||
"...#...", //
|
||||
"..###..", ".#####.", "##.####", "#######", ".#####.", "..###..",
|
||||
];
|
||||
const STAR: Sprite = &[
|
||||
"...#...", //
|
||||
"..###..", "#######", ".#####.", "..###..", ".##.##.", "##...##",
|
||||
];
|
||||
const BELL: Sprite = &[
|
||||
"...#...", //
|
||||
"..###..", ".#####.", ".#####.", ".#####.", "#######", "...#...",
|
||||
];
|
||||
const SNOWFLAKE: Sprite = &[
|
||||
"#.#.#", //
|
||||
".###.", "#####", ".###.", "#.#.#",
|
||||
];
|
||||
const FLAKE: Sprite = &["#"];
|
||||
|
||||
/// What stands on the snow above the photo, with how often each turns up.
|
||||
const STANDING: [(Sprite, u64); 4] = [
|
||||
(BIG_TREE, 35),
|
||||
(SMALL_TREE, 30),
|
||||
(PRESENT, 20),
|
||||
(SMALL_PRESENT, 15),
|
||||
];
|
||||
/// What hangs below the photo; every one has its hook in the middle of its
|
||||
/// top row.
|
||||
const HANGING: [Sprite; 4] = [BAUBLE, STAR, BELL, SNOWFLAKE];
|
||||
|
||||
/// Trees and presents on a solid line of snow, the last line, with snow
|
||||
/// falling in the free sky above them.
|
||||
pub fn scenery(seed: u64, columns: usize) -> Lines {
|
||||
let mut state = seed;
|
||||
let mut lines = blank(columns);
|
||||
lines[ROWS - 1].fill(true);
|
||||
let mut left = (next(&mut state) % 4) as usize;
|
||||
loop {
|
||||
let sprite = weighted(&mut state, &STANDING);
|
||||
if left + width(sprite) > columns {
|
||||
break;
|
||||
}
|
||||
stamp(&mut lines, sprite, left, ROWS - 1 - sprite.len());
|
||||
left += width(sprite) + 2 + (next(&mut state) % 5) as usize;
|
||||
}
|
||||
// Flakes keep a pixel of free space around them, so they never touch the
|
||||
// trees, the presents, the snow or each other.
|
||||
for top in 0..ROWS {
|
||||
for left in 0..columns {
|
||||
if chance(&mut state, 3) {
|
||||
let flake = if chance(&mut state, 25) {
|
||||
SNOWFLAKE
|
||||
} else {
|
||||
FLAKE
|
||||
};
|
||||
if is_free(&lines, flake, left, top) {
|
||||
stamp(&mut lines, flake, left, top);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Ornaments hanging on strings from a solid line, the first line.
|
||||
pub fn ornaments(seed: u64, columns: usize) -> Lines {
|
||||
let mut state = seed;
|
||||
let mut lines = blank(columns);
|
||||
lines[0].fill(true);
|
||||
let mut left = (next(&mut state) % 4) as usize;
|
||||
loop {
|
||||
let sprite = HANGING[(next(&mut state) % HANGING.len() as u64) as usize];
|
||||
if left + width(sprite) > columns {
|
||||
break;
|
||||
}
|
||||
// From one line of string up to as much as still fits.
|
||||
let longest = ROWS - 1 - sprite.len();
|
||||
let string = 1 + (next(&mut state) % longest as u64) as usize;
|
||||
for line in &mut lines[1..=string] {
|
||||
line[left + width(sprite) / 2] = true;
|
||||
}
|
||||
stamp(&mut lines, sprite, left, 1 + string);
|
||||
left += width(sprite) + 2 + (next(&mut state) % 4) as usize;
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn blank(columns: usize) -> Lines {
|
||||
std::array::from_fn(|_| vec![false; columns])
|
||||
}
|
||||
|
||||
fn width(sprite: Sprite) -> usize {
|
||||
sprite[0].len()
|
||||
}
|
||||
|
||||
fn stamp(lines: &mut Lines, sprite: Sprite, left: usize, top: usize) {
|
||||
for (row, pixels) in sprite.iter().enumerate() {
|
||||
for (column, pixel) in pixels.bytes().enumerate() {
|
||||
if pixel == b'#' {
|
||||
lines[top + row][left + column] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the sprite fits at this place with a free pixel all around it.
|
||||
fn is_free(lines: &Lines, sprite: Sprite, left: usize, top: usize) -> bool {
|
||||
let columns = lines[0].len();
|
||||
if top + sprite.len() > ROWS || left + width(sprite) > columns {
|
||||
return false;
|
||||
}
|
||||
let rows = top.saturating_sub(1)..(top + sprite.len() + 1).min(ROWS);
|
||||
let around = left.saturating_sub(1)..(left + width(sprite) + 1).min(columns);
|
||||
lines[rows]
|
||||
.iter()
|
||||
.all(|line| line[around.clone()].iter().all(|pixel| !pixel))
|
||||
}
|
||||
|
||||
fn weighted(state: &mut u64, choices: &[(Sprite, u64)]) -> Sprite {
|
||||
let total: u64 = choices.iter().map(|(_, weight)| weight).sum();
|
||||
let mut roll = next(state) % total;
|
||||
for &(sprite, weight) in choices {
|
||||
if roll < weight {
|
||||
return sprite;
|
||||
}
|
||||
roll -= weight;
|
||||
}
|
||||
unreachable!("the roll is below the total weight")
|
||||
}
|
||||
|
||||
fn chance(state: &mut u64, percent: u64) -> bool {
|
||||
next(state) % 100 < percent
|
||||
}
|
||||
|
||||
/// SplitMix64: a few lines, well mixed, and good enough for decoration.
|
||||
fn next(state: &mut u64) -> u64 {
|
||||
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut mixed = *state;
|
||||
mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
mixed ^ (mixed >> 31)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const WIDTHS: [usize; 4] = [8, 16, 96, 100];
|
||||
|
||||
/// Sizes of the 8-connected groups of black pixels, with whether each one
|
||||
/// reaches into `line`.
|
||||
fn groups(lines: &Lines, line: usize) -> Vec<(usize, bool)> {
|
||||
let columns = lines[0].len();
|
||||
let mut seen = vec![vec![false; columns]; ROWS];
|
||||
let mut found = Vec::new();
|
||||
for row in 0..ROWS {
|
||||
for column in 0..columns {
|
||||
if !lines[row][column] || seen[row][column] {
|
||||
continue;
|
||||
}
|
||||
let (mut size, mut reaches) = (0, false);
|
||||
let mut todo = vec![(row, column)];
|
||||
seen[row][column] = true;
|
||||
while let Some((y, x)) = todo.pop() {
|
||||
size += 1;
|
||||
reaches |= y == line;
|
||||
for ny in y.saturating_sub(1)..=(y + 1).min(ROWS - 1) {
|
||||
for nx in x.saturating_sub(1)..=(x + 1).min(columns - 1) {
|
||||
if lines[ny][nx] && !seen[ny][nx] {
|
||||
seen[ny][nx] = true;
|
||||
todo.push((ny, nx));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found.push((size, reaches));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn pixels(sprite: Sprite) -> usize {
|
||||
sprite.iter().map(|row| row.matches('#').count()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprites_are_rectangular_and_fit_the_strip() {
|
||||
let standing = STANDING.map(|(sprite, _)| sprite);
|
||||
for sprite in standing.into_iter().chain(HANGING).chain([FLAKE]) {
|
||||
assert!(sprite.iter().all(|row| row.len() == width(sprite)));
|
||||
assert!(
|
||||
sprite
|
||||
.iter()
|
||||
.all(|row| row.chars().all(|c| "#.".contains(c)))
|
||||
);
|
||||
}
|
||||
// Standing on the snow, with nothing above the tallest tree.
|
||||
assert!(standing.iter().all(|sprite| sprite.len() < ROWS));
|
||||
// Hanging on at least one line of string, hooked in the middle.
|
||||
for sprite in HANGING {
|
||||
assert!(sprite.len() + 2 <= ROWS);
|
||||
assert_eq!(sprite[0].as_bytes()[width(sprite) / 2], b'#');
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_next_to_the_photo_is_solid() {
|
||||
for columns in WIDTHS {
|
||||
for seed in 0..200 {
|
||||
let above = scenery(seed, columns);
|
||||
let below = ornaments(seed, columns);
|
||||
assert!(above[ROWS - 1].iter().all(|pixel| *pixel));
|
||||
assert!(below[0].iter().all(|pixel| *pixel));
|
||||
assert!(above.iter().chain(&below).all(|line| line.len() == columns));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trees_and_presents_stand_on_the_snow_and_only_flakes_float() {
|
||||
for seed in 0..200 {
|
||||
let lines = scenery(seed, 96);
|
||||
let groups = groups(&lines, ROWS - 1);
|
||||
let (ground, _) = groups.iter().find(|(_, grounded)| *grounded).unwrap();
|
||||
// Several trees and presents on 96 pixels of snow.
|
||||
assert!(*ground > 96 + 4 * pixels(SMALL_PRESENT), "seed {seed}");
|
||||
// Everything else is a single flake.
|
||||
let flakes: Vec<_> = groups.iter().filter(|(_, grounded)| !grounded).collect();
|
||||
assert!(
|
||||
flakes
|
||||
.iter()
|
||||
.all(|(size, _)| [1, pixels(SNOWFLAKE)].contains(size)),
|
||||
"seed {seed}: {flakes:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ornaments_all_hang_from_the_line() {
|
||||
for columns in WIDTHS {
|
||||
for seed in 0..200 {
|
||||
let lines = ornaments(seed, columns);
|
||||
assert!(groups(&lines, 0).iter().all(|(_, hanging)| *hanging));
|
||||
}
|
||||
}
|
||||
// And there are several of them.
|
||||
let lines = ornaments(1, 96);
|
||||
let hooked = (0..96).filter(|column| lines[1][*column]).count();
|
||||
assert!(hooked >= 5, "{hooked} ornaments");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_seed_gives_one_picture_and_seeds_give_many() {
|
||||
assert_eq!(scenery(7, 96), scenery(7, 96));
|
||||
assert_eq!(ornaments(7, 96), ornaments(7, 96));
|
||||
let distinct = |picture: fn(u64, usize) -> Lines| {
|
||||
(0..1000)
|
||||
.map(|seed| picture(seed, 96))
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len()
|
||||
};
|
||||
assert_eq!(distinct(scenery), 1000);
|
||||
assert_eq!(distinct(ornaments), 1000);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ use slint::{Rgb8Pixel, SharedPixelBuffer};
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
mod artwork;
|
||||
mod camera;
|
||||
mod capture;
|
||||
mod diagnostics;
|
||||
@@ -27,6 +28,7 @@ mod faces;
|
||||
mod hand_pose;
|
||||
mod palm;
|
||||
mod printer;
|
||||
mod quotes;
|
||||
|
||||
struct PreviewFrame {
|
||||
buffer: SharedPixelBuffer<Rgb8Pixel>,
|
||||
|
||||
285
src/printer.rs
285
src/printer.rs
@@ -10,7 +10,7 @@
|
||||
//! of 8. Defaults to 576 (80 mm paper); use 384 for 58 mm paper.
|
||||
//! - `PHOTOBOOTH_PRINTER_GAMMA`: mid-tone brightening applied before dithering
|
||||
//! to offset the dot gain of thermal paper (`out = in^(1/gamma)`). Defaults to
|
||||
//! 2.0; typical values are 1.8-2.5, and 1 disables it.
|
||||
//! 2.7; typical values are 1.8-3.0, and 1 disables it.
|
||||
//! - `PHOTOBOOTH_PRINTER_DENSITY`: thermal head energy in percent of the rated
|
||||
//! energy, 70-130 (SII `DC2 ~ n`). Unset by default.
|
||||
//! - `PHOTOBOOTH_PRINTER_SPEED`: `quality` (120 mm/s), `low` (150 mm/s),
|
||||
@@ -24,11 +24,14 @@
|
||||
//! band and are not stored by the printer (no memory switch writes).
|
||||
//!
|
||||
//! Each photo is captioned with the event name and place above it, and a
|
||||
//! keepsake line, the capture date and time and one of `QUOTES` below it, in
|
||||
//! German with the English directly underneath. The timestamp is the system
|
||||
//! clock in local time, so the booth's clock has to be right for it to mean
|
||||
//! anything. Text goes out in the printer's own code page (PC437), since it
|
||||
//! prints UTF-8 bytes as separate glyphs; see `code_page`.
|
||||
//! keepsake line, the capture date and time and one of `QUOTES` below it. The
|
||||
//! captions are in German with the English directly underneath, the quotes in
|
||||
//! English only. Christmas pixel art (see `artwork`) frames the photo: fir
|
||||
//! trees and presents in the snow above it and ornaments hanging below it,
|
||||
//! arranged differently on every slip. The timestamp is the system clock in
|
||||
//! local time, so the booth's clock has to be right for it to mean anything.
|
||||
//! Text goes out in the printer's own code page (PC437), since it prints UTF-8
|
||||
//! bytes as separate glyphs; see `code_page`.
|
||||
//!
|
||||
//! Each photo is converted to gray, resized to the exact dot width, contrast
|
||||
//! equalized (CLAHE), slightly sharpened, gamma brightened and finally Atkinson
|
||||
@@ -52,9 +55,14 @@ use opencv::{
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
artwork::{self, CELLS_ACROSS, ROWS},
|
||||
quotes::QUOTES,
|
||||
};
|
||||
|
||||
const DEFAULT_PRINTER: &str = "/dev/usb/lp0";
|
||||
const DEFAULT_DOTS: usize = 576;
|
||||
const DEFAULT_GAMMA: f32 = 2.0;
|
||||
const DEFAULT_GAMMA: f32 = 2.7;
|
||||
const DENSITY_RANGE: std::ops::RangeInclusive<u8> = 70..=130;
|
||||
/// CLAHE settings: contrast limit and tiles across the image.
|
||||
const CLAHE_CLIP_LIMIT: f64 = 2.0;
|
||||
@@ -74,42 +82,6 @@ const KEEPSAKE_DE: &str = "Ich war dabei!";
|
||||
const KEEPSAKE_EN: &str = "I was there!";
|
||||
/// Capture time, written the German way and the same in both languages.
|
||||
const STAMP_FORMAT: &str = "%d.%m.%Y, %H:%M";
|
||||
/// One is printed per slip. Each line is short enough for a single 80 mm line;
|
||||
/// on 58 mm paper the longer ones wrap.
|
||||
const QUOTES: [[&str; 2]; 8] = [
|
||||
[
|
||||
"Analysis bestanden. Wunder gibt es doch.",
|
||||
"Passed Analysis. Miracles do happen.",
|
||||
],
|
||||
[
|
||||
"Im Freihaus gibt es Kaffee und Hoffnung.",
|
||||
"The Freihaus serves coffee and hope.",
|
||||
],
|
||||
[
|
||||
"TISS sagt nein. Mein Herz sagt auch nein.",
|
||||
"TISS says no. So does my heart.",
|
||||
],
|
||||
[
|
||||
"WINF: zwei Fächer, eine Deadline.",
|
||||
"WINF: two subjects, one deadline.",
|
||||
],
|
||||
[
|
||||
"Karlsplatz: der schönste Umweg zur Uni.",
|
||||
"Karlsplatz: the prettiest detour to class.",
|
||||
],
|
||||
[
|
||||
"Prüfungswoche: Schlafen ist optional.",
|
||||
"Exam week: sleeping is optional.",
|
||||
],
|
||||
[
|
||||
"Die Bibliothek kennt alle meine Ausreden.",
|
||||
"The library has heard all my excuses.",
|
||||
],
|
||||
[
|
||||
"Mathe ist einfach, sagt die Mathematik.",
|
||||
"Maths is easy, says maths.",
|
||||
],
|
||||
];
|
||||
/// Pause between writes, leaving the head time to drain a band (8 mm of paper)
|
||||
/// before the next one arrives.
|
||||
const PACE: Duration = Duration::from_millis(100);
|
||||
@@ -246,7 +218,14 @@ impl Printer {
|
||||
let bitmap =
|
||||
render(frame, self.dots, self.gamma).map_err(|error| format!("render: {error}"))?;
|
||||
let stamp = Local::now().format(STAMP_FORMAT).to_string();
|
||||
self.send(&encode(&bitmap, &self.head, copies, &stamp, first_quote()))
|
||||
self.send(&encode(
|
||||
&bitmap,
|
||||
&self.head,
|
||||
copies,
|
||||
&stamp,
|
||||
first_quote(),
|
||||
clock_seed(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Sends the job one write at a time, pacing them to the print head.
|
||||
@@ -383,10 +362,33 @@ fn encode(
|
||||
copies: usize,
|
||||
stamp: &str,
|
||||
first_quote: usize,
|
||||
seed: u64,
|
||||
) -> Vec<Vec<u8>> {
|
||||
let mut job = Vec::new();
|
||||
for copy in 0..copies {
|
||||
// A scene above the photo and ornaments below it, new for every copy.
|
||||
let dots = bitmap.width_bytes * 8;
|
||||
let seed = seed.wrapping_add(2 * copy as u64);
|
||||
job.push(header(head));
|
||||
raster_bands(&mut job, &pixel_strip(dots, seed, Side::Above), head);
|
||||
raster_bands(&mut job, bitmap, head);
|
||||
raster_bands(
|
||||
&mut job,
|
||||
&pixel_strip(dots, seed.wrapping_add(1), Side::Below),
|
||||
head,
|
||||
);
|
||||
job.push(footer(
|
||||
head,
|
||||
stamp,
|
||||
"ES[(first_quote + copy) % QUOTES.len()],
|
||||
));
|
||||
job.push(finish(head));
|
||||
}
|
||||
job
|
||||
}
|
||||
|
||||
/// Appends the bitmap as one write per band of `BAND_ROWS` rows.
|
||||
fn raster_bands(job: &mut Vec<Vec<u8>>, bitmap: &Bitmap, head: &Head) {
|
||||
for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) {
|
||||
let rows = band.len() / bitmap.width_bytes;
|
||||
let mut write = vec![0x1B, b'@']; // ESC @: initialize
|
||||
@@ -397,14 +399,48 @@ fn encode(
|
||||
write.extend(band);
|
||||
job.push(write);
|
||||
}
|
||||
job.push(footer(head, stamp, "ES[(first_quote + copy) % QUOTES.len()]));
|
||||
}
|
||||
job
|
||||
}
|
||||
|
||||
/// The German letters in the captions as single PC437 bytes, the code page the
|
||||
/// booth's printer starts in. Anything else non-ASCII would need a wider table
|
||||
/// or `ESC t`, so a test keeps the printed text within this set.
|
||||
/// Which side of the photo a pixel strip goes on.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Side {
|
||||
/// Trees and presents standing on the snow, the strip's bottom line.
|
||||
Above,
|
||||
/// Ornaments hanging from the strip's solid top line.
|
||||
Below,
|
||||
}
|
||||
|
||||
/// The random Christmas pixel strip across the whole paper, `ROWS` lines of
|
||||
/// pixels with the solid line next to the photo. Pixels are 6 dots on 80 mm
|
||||
/// paper and 4 on 58 mm.
|
||||
fn pixel_strip(dots: usize, seed: u64, side: Side) -> Bitmap {
|
||||
let cell = (dots / CELLS_ACROSS).max(1);
|
||||
let columns = dots / cell;
|
||||
let left = (dots - columns * cell) / 2;
|
||||
let stride = dots / 8;
|
||||
let lines = match side {
|
||||
Side::Above => artwork::scenery(seed, columns),
|
||||
Side::Below => artwork::ornaments(seed, columns),
|
||||
};
|
||||
let mut data = vec![0u8; stride * ROWS * cell];
|
||||
for y in 0..ROWS * cell {
|
||||
for x in 0..columns * cell {
|
||||
if lines[y / cell][x / cell] {
|
||||
let dot = left + x;
|
||||
data[y * stride + dot / 8] |= 0x80 >> (dot % 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
Bitmap {
|
||||
width_bytes: stride,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// The German letters and the middle dot in the captions as single PC437 bytes,
|
||||
/// the code page the booth's printer starts in. Anything else non-ASCII would
|
||||
/// need a wider table or `ESC t`, so a test keeps the printed text within this
|
||||
/// set.
|
||||
fn code_page(character: char) -> Option<u8> {
|
||||
Some(match character {
|
||||
'ä' => 0x84,
|
||||
@@ -414,6 +450,7 @@ fn code_page(character: char) -> Option<u8> {
|
||||
'Ö' => 0x99,
|
||||
'Ü' => 0x9A,
|
||||
'ß' => 0xE1,
|
||||
'·' => 0xFA,
|
||||
ascii if ascii.is_ascii() => ascii as u8,
|
||||
_ => return None,
|
||||
})
|
||||
@@ -421,7 +458,10 @@ fn code_page(character: char) -> Option<u8> {
|
||||
|
||||
/// Appends one line of text, encoded for the printer.
|
||||
fn text_line(write: &mut Vec<u8>, line: &str) {
|
||||
write.extend(line.chars().map(|character| code_page(character).unwrap_or(b'?')));
|
||||
write.extend(
|
||||
line.chars()
|
||||
.map(|character| code_page(character).unwrap_or(b'?')),
|
||||
);
|
||||
write.push(b'\n');
|
||||
}
|
||||
|
||||
@@ -456,7 +496,14 @@ fn first_quote() -> usize {
|
||||
% QUOTES.len()
|
||||
}
|
||||
|
||||
fn footer(head: &Head, stamp: &str, quote: &[&str; 2]) -> Vec<u8> {
|
||||
/// Seed for the pixel strips of one job, from the clock like the quote.
|
||||
fn clock_seed() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |since| since.as_nanos() as u64)
|
||||
}
|
||||
|
||||
fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec<u8> {
|
||||
let mut write = centered(head);
|
||||
write.extend([0x1B, b'd', 1]);
|
||||
write.extend(LARGE);
|
||||
@@ -466,8 +513,16 @@ fn footer(head: &Head, stamp: &str, quote: &[&str; 2]) -> Vec<u8> {
|
||||
write.extend([0x1B, b'd', 1]);
|
||||
text_line(&mut write, stamp);
|
||||
write.extend([0x1B, b'd', 1]);
|
||||
text_line(&mut write, quote[0]);
|
||||
text_line(&mut write, quote[1]);
|
||||
for line in quote {
|
||||
text_line(&mut write, line);
|
||||
}
|
||||
write
|
||||
}
|
||||
|
||||
/// Feeds the slip past the cutter and cuts it.
|
||||
fn finish(head: &Head) -> Vec<u8> {
|
||||
let mut write = vec![0x1B, b'@']; // ESC @: initialize
|
||||
write.extend(head.commands());
|
||||
write.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines
|
||||
write.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut
|
||||
write
|
||||
@@ -483,7 +538,7 @@ mod tests {
|
||||
fn printed_lines() -> impl Iterator<Item = &'static str> {
|
||||
[EVENT_TITLE, EVENT_PLACE, KEEPSAKE_DE, KEEPSAKE_EN, STAMP]
|
||||
.into_iter()
|
||||
.chain(QUOTES.iter().flatten().copied())
|
||||
.chain(QUOTES.iter().flat_map(|quote| quote.iter().copied()))
|
||||
}
|
||||
|
||||
fn contains_line(write: &[u8], line: &str) -> bool {
|
||||
@@ -520,10 +575,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn quotes_are_picked_from_the_list_and_vary() {
|
||||
let picked: std::collections::BTreeSet<usize> =
|
||||
(0..1000).map(|_| first_quote()).collect();
|
||||
let picked: std::collections::BTreeSet<usize> = (0..1000).map(|_| first_quote()).collect();
|
||||
assert!(picked.last().is_some_and(|last| *last < QUOTES.len()));
|
||||
// Not all eight on a coarse clock, but a slip must not be predictable.
|
||||
// Not all of them on a coarse clock, but a slip must not be predictable.
|
||||
assert!(picked.len() > 1, "{picked:?}");
|
||||
}
|
||||
|
||||
@@ -549,7 +603,7 @@ mod tests {
|
||||
let printer = Printer::from_values(None, None, None).unwrap();
|
||||
assert_eq!(printer.target, Target::Device("/dev/usb/lp0".into()));
|
||||
assert_eq!(printer.dots, 576);
|
||||
assert_eq!(printer.gamma, 2.0);
|
||||
assert_eq!(printer.gamma, 2.7);
|
||||
// Unparsable widths fall back; valid ones are rounded to whole bytes.
|
||||
let dots = |value| Printer::from_values(None, Some(value), None).unwrap().dots;
|
||||
assert_eq!(dots("wide"), 576);
|
||||
@@ -557,8 +611,8 @@ mod tests {
|
||||
// Gamma must be a positive number.
|
||||
let gamma = |value| Printer::from_values(None, None, Some(value)).unwrap().gamma;
|
||||
assert_eq!(gamma(" 2.4 "), 2.4);
|
||||
assert_eq!(gamma("0"), 2.0);
|
||||
assert_eq!(gamma("bright"), 2.0);
|
||||
assert_eq!(gamma("0"), 2.7);
|
||||
assert_eq!(gamma("bright"), 2.7);
|
||||
// An explicitly empty printer disables printing.
|
||||
assert!(Printer::from_values(Some(""), None, None).is_none());
|
||||
}
|
||||
@@ -586,11 +640,15 @@ mod tests {
|
||||
width_bytes: 1,
|
||||
data: vec![0; BAND_ROWS + 1],
|
||||
};
|
||||
let job = encode(&bitmap, &Head::from_values(Some("85"), Some("quality")), 1, STAMP, 0);
|
||||
for band in &job[1..3] {
|
||||
let head = Head::from_values(Some("85"), Some("quality"));
|
||||
let job = encode(&bitmap, &head, 1, STAMP, 0, 0);
|
||||
// Strip, the two photo bands and the other strip.
|
||||
for band in &job[1..5] {
|
||||
assert_eq!(
|
||||
&band[..12],
|
||||
[0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0]
|
||||
[
|
||||
0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -626,41 +684,100 @@ mod tests {
|
||||
width_bytes: 2,
|
||||
data: vec![0xAA; 2 * (BAND_ROWS + 1)],
|
||||
};
|
||||
let job = encode(&bitmap, &Head::default(), 2, STAMP, 0);
|
||||
// Per copy: the caption, a full band, the leftover row, then the footer.
|
||||
assert_eq!(job.len(), 2 * 4);
|
||||
for copy in job.chunks(4) {
|
||||
let job = encode(&bitmap, &Head::default(), 2, STAMP, 0, 0);
|
||||
// Per copy: the caption, a pixel strip, the photo's full band and
|
||||
// leftover row, a pixel strip, the footer and the cut.
|
||||
assert_eq!(job.len(), 2 * 7);
|
||||
for copy in job.chunks(7) {
|
||||
assert_eq!(
|
||||
©[1][..10],
|
||||
©[2][..10],
|
||||
[0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0]
|
||||
);
|
||||
assert_eq!(copy[1].len(), 10 + 2 * BAND_ROWS);
|
||||
assert_eq!(copy[2].len(), 10 + 2 * BAND_ROWS);
|
||||
assert_eq!(
|
||||
copy[2],
|
||||
[vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2]].concat()
|
||||
copy[3],
|
||||
[
|
||||
vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0],
|
||||
vec![0xAA; 2]
|
||||
]
|
||||
.concat()
|
||||
);
|
||||
}
|
||||
// Every write initializes first, so no dot data is read as commands.
|
||||
assert!(job.iter().all(|write| write.starts_with(&[0x1B, b'@'])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_the_photo_with_christmas_pixel_art() {
|
||||
for dots in [384, 576] {
|
||||
let cell = dots / CELLS_ACROSS;
|
||||
for side in [Side::Above, Side::Below] {
|
||||
let strip = pixel_strip(dots, 42, side);
|
||||
assert_eq!(strip.width_bytes, dots / 8);
|
||||
assert_eq!(strip.data.len(), dots / 8 * ROWS * cell);
|
||||
let lit = |row: usize, dot: usize| {
|
||||
strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0
|
||||
};
|
||||
// Dots lit in each line of pixels, from the photo outward.
|
||||
let mut counts: Vec<usize> = (0..ROWS)
|
||||
.map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count())
|
||||
.collect();
|
||||
if matches!(side, Side::Above) {
|
||||
counts.reverse();
|
||||
}
|
||||
// The line next to the photo spans the paper, and there is
|
||||
// more than that line.
|
||||
assert_eq!(counts[0], dots);
|
||||
assert!(counts[1..].iter().all(|count| *count < dots), "{counts:?}");
|
||||
assert!(counts[1..].iter().sum::<usize>() > dots, "{counts:?}");
|
||||
// Pixels are solid squares: every dot row of a line is the same.
|
||||
for line in 0..ROWS {
|
||||
for dot_row in 1..cell {
|
||||
for dot in 0..dots {
|
||||
assert_eq!(lit(line * cell, dot), lit(line * cell + dot_row, dot));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Caption, strip, photo, strip, footer, cut. At 576 dots each strip is
|
||||
// 72 rows, a full band and 8 more, around the photo's single row.
|
||||
let bitmap = Bitmap {
|
||||
width_bytes: 72,
|
||||
data: vec![0xFF; 72],
|
||||
};
|
||||
let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5);
|
||||
assert_eq!(job.len(), 8);
|
||||
let raster = |rows: u8| [0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, rows, 0];
|
||||
for strip in [1, 4] {
|
||||
assert!(job[strip].starts_with(&raster(BAND_ROWS as u8)));
|
||||
assert!(job[strip + 1].starts_with(&raster(8)));
|
||||
}
|
||||
assert_eq!(&job[3][..10], raster(1));
|
||||
assert!(job[7].ends_with(&[0x1D, b'V', 66, 3]));
|
||||
// Nothing is printed after the quote but the feed and the cut.
|
||||
assert!(job[6].windows(2).all(|pair| pair != [0x1D, b'v']));
|
||||
// The next copy gets a different scene.
|
||||
let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5);
|
||||
assert_ne!(two[1], two[9]);
|
||||
assert_ne!(two[4], two[12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_the_photo_and_cuts_once_per_copy() {
|
||||
let bitmap = Bitmap {
|
||||
width_bytes: 1,
|
||||
data: vec![0; 1],
|
||||
};
|
||||
let job = encode(&bitmap, &Head::default(), 2, STAMP, 6);
|
||||
let last = QUOTES.len() - 1;
|
||||
let job = encode(&bitmap, &Head::default(), 2, STAMP, last, 0);
|
||||
assert!(contains_line(&job[0], EVENT_TITLE) && contains_line(&job[0], EVENT_PLACE));
|
||||
assert!(contains_line(&job[2], KEEPSAKE_DE) && contains_line(&job[2], KEEPSAKE_EN));
|
||||
assert!(contains_line(&job[2], STAMP));
|
||||
assert!(contains_line(&job[4], KEEPSAKE_DE) && contains_line(&job[4], KEEPSAKE_EN));
|
||||
assert!(contains_line(&job[4], STAMP));
|
||||
// Consecutive copies get consecutive quotes, wrapping round the list.
|
||||
assert!(contains_line(&job[2], QUOTES[6][0]) && contains_line(&job[2], QUOTES[6][1]));
|
||||
assert!(contains_line(&job[5], QUOTES[7][0]) && contains_line(&job[5], QUOTES[7][1]));
|
||||
assert!(
|
||||
encode(&bitmap, &Head::default(), 1, STAMP, QUOTES.len() - 1)[2]
|
||||
.ends_with(&footer(&Head::default(), STAMP, "ES[QUOTES.len() - 1])[1..])
|
||||
);
|
||||
assert!(QUOTES[last].iter().all(|line| contains_line(&job[4], line)));
|
||||
assert!(QUOTES[0].iter().all(|line| contains_line(&job[10], line)));
|
||||
assert!(job[4].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..]));
|
||||
// The real stamp is as wide as the one used here.
|
||||
let now = Local::now().format(STAMP_FORMAT).to_string();
|
||||
assert!(now.is_ascii() && now.len() == STAMP.len(), "{now}");
|
||||
@@ -671,9 +788,3 @@ mod tests {
|
||||
assert_eq!(cuts, 2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
89
src/quotes.rs
Normal file
89
src/quotes.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
//! Quotes printed under each photo, one per slip.
|
||||
|
||||
/// One is printed per slip, one printed line per entry, in English. Each line
|
||||
/// is short enough for a single 80 mm line (longer quotes are split by hand); on
|
||||
/// 58 mm paper the longer ones wrap.
|
||||
pub const QUOTES: &[&[&str]] = &[
|
||||
// The good times.
|
||||
&["Good times, good people."],
|
||||
&["Glad you came."],
|
||||
&["A night to remember."],
|
||||
&["Here for the good times."],
|
||||
&["Made it out tonight."],
|
||||
&["Look at us go."],
|
||||
&["This one's a keeper."],
|
||||
&["Smile, you earned it."],
|
||||
&["Friends first, deadlines later."],
|
||||
&["Great company, as always."],
|
||||
&["Not bad for a weeknight."],
|
||||
&["Still better than studying."],
|
||||
&["Zero regrets."],
|
||||
&["Camera loves us."],
|
||||
&["Nailed it."],
|
||||
&["The good old days, right now."],
|
||||
&["Best seats in the house."],
|
||||
&["Proof that we have a social life."],
|
||||
&["Group project, actually fun."],
|
||||
&["Exams can wait."],
|
||||
&["We clean up nicely."],
|
||||
&["Told you it would be fun."],
|
||||
&["Save the date, we're doing this again."],
|
||||
&["You had to be there. Luckily, we were."],
|
||||
&["Photo or it didn't happen."],
|
||||
&["Passed with distinction."],
|
||||
&["Attendance: voluntary. Mood: excellent."],
|
||||
&["See you at the next one."],
|
||||
// Winfnachten.
|
||||
&["Merry Winfnachten!"],
|
||||
&["Winfnachten: the most wonderful night", "of the semester."],
|
||||
&["All I want for Winfnachten is to pass my exams."],
|
||||
&["Winfnachten spirit: confirmed."],
|
||||
&["On the nice list. Mostly."],
|
||||
&["Dear Santa, I studied. Sort of."],
|
||||
&["Have yourself a merry little Winfnachten."],
|
||||
&["See you next Winfnachten."],
|
||||
// winf.at.
|
||||
&["Check out what's next at winf.at"],
|
||||
&["More events, more photos: winf.at"],
|
||||
&["Liked tonight? There's more at winf.at"],
|
||||
&["Find your next event at winf.at"],
|
||||
&["Brought to you by FSWinf · winf.at"],
|
||||
&["Your student body at TU Wien: winf.at"],
|
||||
&["Stay in the loop: winf.at"],
|
||||
&["This photo was made by volunteers.", "Meet them at winf.at"],
|
||||
// Studying at TU Wien.
|
||||
&["Questions about your studies? Ask us: winf.at"],
|
||||
&["Stuck on your study plan? We can help: winf.at"],
|
||||
&["Need a place to study?", "Visit our study room: winf.at"],
|
||||
&["New at TU Wien? Start here: winf.at"],
|
||||
&["First semester? Join our E-Tuts: winf.at"],
|
||||
&[
|
||||
"Business Informatics or Data Science?",
|
||||
"We've got you: winf.at",
|
||||
],
|
||||
// Getting involved.
|
||||
&["Want to help run the next one? Join us: winf.at"],
|
||||
&[
|
||||
"Come to a Fachschaft meeting.",
|
||||
"Everyone's welcome: winf.at",
|
||||
],
|
||||
&["We're students, just like you. Say hi: winf.at"],
|
||||
&["Got ideas for the next event? Tell us: winf.at"],
|
||||
// The receipt.
|
||||
&["Receipt for one great night."],
|
||||
&["Proof of attendance."],
|
||||
&["Keep this receipt. No returns on good memories."],
|
||||
&["Thank you for celebrating with us."],
|
||||
&["Paid in full: one great evening."],
|
||||
&["Total: priceless."],
|
||||
&["Memories: 1x. Regrets: 0x."],
|
||||
&["Items: good friends, good times.", "Total: worth it."],
|
||||
&["No refunds. No regrets."],
|
||||
&["Valid forever."],
|
||||
&[
|
||||
"This receipt is not tax deductible.",
|
||||
"Sorry, business students.",
|
||||
],
|
||||
&["Customer copy. The memories are yours."],
|
||||
&["Thank you, come again!"],
|
||||
];
|
||||
Reference in New Issue
Block a user