Compare commits
22 Commits
085a5e9cc0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0383b4e8cc | ||
| a1ae6fc282 | |||
|
|
a465c5c88f | ||
|
|
39e055eb0e | ||
|
|
d06077a257 | ||
|
|
1ff006bc3c | ||
|
|
f406b36c5f | ||
|
|
181a0512bd | ||
|
|
c7af3e320b | ||
|
|
b71e2b32e6 | ||
|
|
8c43984652 | ||
|
|
fb5ce525bb | ||
|
|
c28428a2f3 | ||
|
|
4fb2ad7757 | ||
|
|
a2b83744db | ||
|
|
eae81bb052 | ||
|
|
898ceb5726 | ||
|
|
838becdd70 | ||
|
|
9cf760e7a6 | ||
|
|
6437261a65 | ||
|
|
994c78cc26 | ||
|
|
2e21946300 |
24
.env
Normal file
24
.env
Normal file
@@ -0,0 +1,24 @@
|
||||
# Photobooth configuration, loaded from the directory the app is started from.
|
||||
# Variables already set in the environment (e.g. by systemd) take precedence.
|
||||
# Every variable is optional; the values below are the built-in defaults.
|
||||
|
||||
# Thermal printer (ESC/POS). Set to an empty value to disable printing.
|
||||
# A device path for USB/serial printers, or tcp://host[:port] for network
|
||||
# printers (port defaults to 9100).
|
||||
PHOTOBOOTH_PRINTER=/dev/usb/lp0
|
||||
|
||||
# Printable width in dots: 576 for 80 mm paper (384 for 58 mm).
|
||||
PHOTOBOOTH_PRINTER_DOTS=576
|
||||
|
||||
# Mid-tone brightening before dithering, offsetting thermal dot gain
|
||||
# (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 ~
|
||||
# and GS s); the Birch 0CP-Q3 in the booth misparses either one and then prints
|
||||
# the photo as two metres of text, so leave both empty unless the printer is
|
||||
# known to understand them.
|
||||
PHOTOBOOTH_PRINTER_DENSITY=
|
||||
|
||||
PHOTOBOOTH_PRINTER_SPEED=
|
||||
8
Cargo.lock
generated
8
Cargo.lock
generated
@@ -991,6 +991,12 @@ dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dotenvy"
|
||||
version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "downcast-rs"
|
||||
version = "1.2.1"
|
||||
@@ -5444,6 +5450,8 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
name = "winf-photobooth-app"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dotenvy",
|
||||
"opencv",
|
||||
"slint",
|
||||
"slint-build",
|
||||
|
||||
@@ -4,6 +4,8 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] }
|
||||
dotenvy = "0.15.7"
|
||||
opencv = "0.101.1"
|
||||
slint = {
|
||||
version = "1.18.1",
|
||||
|
||||
@@ -21,3 +21,52 @@ Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models
|
||||
SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
|
||||
|
||||
`src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.65 hand confidence, and checks all five fingers for extension using 3D landmarks. Finger extension tolerates natural curvature and a relaxed thumb while rejecting curled fingers and fists. Rejected poses reset the dwell/progress timer; the outline persists for up to 750 ms after the last accepted sample to avoid flicker. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance.
|
||||
|
||||
# Capture face counting
|
||||
|
||||
Faces are detected with OpenCV YuNet (`face_detection_yunet_2023mar.onnx`),
|
||||
replacing the Haar face and eye cascades. The 228 KiB ONNX model is embedded in
|
||||
the executable, loaded once, and run with OpenCV DNN on CPU. OpenCV 4.8 or newer
|
||||
with DNN and FaceDetectorYN buffer loading is required (tested with 4.10).
|
||||
|
||||
Source: https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
|
||||
|
||||
Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
|
||||
|
||||
SHA-256: `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4`
|
||||
|
||||
License: MIT, reproduced in `YUNET_LICENSE`.
|
||||
|
||||
Images retain their aspect ratio, with the longest edge resized to 320 px and
|
||||
black padding to 320×320. Confidence threshold is 0.8, NMS threshold 0.3 and top K
|
||||
500. Predicted eye and nose landmarks filter strongly turned faces: the nose
|
||||
projection must fall within the central 70% of the eye line, with eye separation
|
||||
at least 23% of the face width. This tolerates roll and mirrored coordinates and
|
||||
does not depend on a separate eye detector. It estimates frontal head orientation,
|
||||
not eye gaze. Small, occluded or strongly tilted faces can still be missed;
|
||||
validate group-photo accuracy and timings on the target kiosk.
|
||||
|
||||
The camera copies and queues the clean mirrored frame after the countdown,
|
||||
then immediately resumes the feed. A dedicated capture worker loads YuNet,
|
||||
counts faces once, and calls the print hook sequentially. The bounded job channel
|
||||
uses nonblocking submission; the next countdown waits until the worker is idle.
|
||||
Accepted jobs are drained at shutdown. Lighting stays on until the frame snapshot
|
||||
has been copied and queued, rather than waiting for face counting or printing.
|
||||
Debug logs retain
|
||||
candidate boxes, confidence, accepted/rejected counts, intended copies and timing.
|
||||
The count is passed to an intentionally empty `print_picture` hook. There is no
|
||||
printer command, image encoding, file output or physical printing yet.
|
||||
|
||||
Face rectangles and live face inference are enabled only in debug builds
|
||||
(`cargo run`); release builds (`cargo run --release`) have neither. The debug
|
||||
worker samples at most twice per second, drops samples while busy, and expires
|
||||
results after 1.5 seconds. Green (`#84bf65`) means accepted; blue (`#4caee3`) means
|
||||
rejected for head orientation. Rectangles use mirrored camera coordinates and
|
||||
share the preview crop, but never enter capture or detector input. Counts are
|
||||
always recomputed on the captured frame and can differ from the last live sample.
|
||||
All model loading and inference happen on background workers: palm/hand pose,
|
||||
capture-time faces/print hook, and debug-only live faces. Camera and UI threads
|
||||
never wait for inference or print scheduling. OpenCV uses one inference thread
|
||||
per worker to reduce contention on the dual-core kiosk. This removes direct
|
||||
blocking; actual feed timing still depends on CPU load and camera behavior and
|
||||
needs measurement on the kiosk.
|
||||
|
||||
21
models/YUNET_LICENSE
Normal file
21
models/YUNET_LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Shiqi Yu <shiqi.yu@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
Binary file not shown.
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);
|
||||
}
|
||||
}
|
||||
222
src/capture.rs
222
src/capture.rs
@@ -1,4 +1,14 @@
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use opencv::prelude::MatTraitConst;
|
||||
|
||||
#[derive(Default)]
|
||||
enum Phase {
|
||||
@@ -25,7 +35,7 @@ impl Sequence {
|
||||
pub fn tick(&mut self, complete: bool, hand_present: bool, now: Instant) -> bool {
|
||||
match self.phase {
|
||||
Phase::Tracking if complete => self.phase = Phase::Countdown(now),
|
||||
Phase::Countdown(start) if now.duration_since(start) >= Duration::from_secs(3) => {
|
||||
Phase::Countdown(start) if now.duration_since(start) >= Duration::from_secs(5) => {
|
||||
self.phase = Phase::AwaitingRelease;
|
||||
return true;
|
||||
}
|
||||
@@ -44,10 +54,10 @@ impl Sequence {
|
||||
Phase::Countdown(start) => {
|
||||
let elapsed = now.duration_since(start).as_secs_f32();
|
||||
Presentation {
|
||||
countdown: (3 - elapsed as i32).clamp(1, 3),
|
||||
countdown: (5 - elapsed as i32).clamp(1, 5),
|
||||
// The monitor lights the room: hold white illumination until
|
||||
// the countdown completes and take_picture() returns.
|
||||
flash_opacity: 0.75,
|
||||
// the clean frame is captured and queued after the countdown.
|
||||
flash_opacity: 0.95,
|
||||
awaiting_release: false,
|
||||
}
|
||||
}
|
||||
@@ -60,14 +70,180 @@ impl Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_picture() {
|
||||
// TODO: Take a picture here after the countdown. No capture or file writes yet.
|
||||
/// Single background pipeline for capture-time inference and future print scheduling.
|
||||
/// At most one job is active and one is queued; submission never waits on work.
|
||||
pub struct Worker {
|
||||
sender: Option<std::sync::mpsc::SyncSender<opencv::core::Mat>>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
pending: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
pub fn new() -> Self {
|
||||
Self::spawn(|| {
|
||||
// Load and own the model on the worker too.
|
||||
let mut detector = crate::faces::Detector::new();
|
||||
let printer = crate::printer::Printer::from_env();
|
||||
match &printer {
|
||||
Some(printer) => eprintln!("[capture INFO] Printing to {printer:?}"),
|
||||
None => eprintln!("[capture INFO] PHOTOBOOTH_PRINTER is empty; printing disabled"),
|
||||
}
|
||||
move |frame| match &mut detector {
|
||||
Ok(detector) => {
|
||||
if let Err(error) = take_picture(&frame, detector, printer.as_ref()) {
|
||||
eprintln!("[capture ERROR] Face counting failed: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => eprintln!("[capture ERROR] Face model unavailable: {error}"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn spawn<F, P>(initialize: F) -> Self
|
||||
where
|
||||
F: FnOnce() -> P + Send + 'static,
|
||||
P: FnMut(opencv::core::Mat) + 'static,
|
||||
{
|
||||
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
|
||||
let pending = Arc::new(AtomicUsize::new(0));
|
||||
let worker_pending = Arc::clone(&pending);
|
||||
let thread = std::thread::spawn(move || {
|
||||
let mut process = initialize();
|
||||
while let Ok(frame) = receiver.recv() {
|
||||
process(frame);
|
||||
worker_pending.fetch_sub(1, Ordering::Release);
|
||||
}
|
||||
});
|
||||
Self {
|
||||
sender: Some(sender),
|
||||
thread: Some(thread),
|
||||
pending,
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes ownership of a clean frame snapshot. Returns it when the bounded
|
||||
/// queue is full/disconnected, allowing the caller to report rejection.
|
||||
pub fn submit(
|
||||
&self,
|
||||
frame: opencv::core::Mat,
|
||||
) -> Result<(), std::sync::mpsc::TrySendError<opencv::core::Mat>> {
|
||||
self.pending.fetch_add(1, Ordering::Relaxed);
|
||||
let result = self.sender.as_ref().unwrap().try_send(frame);
|
||||
if result.is_err() {
|
||||
self.pending.fetch_sub(1, Ordering::Release);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn is_idle(&self) -> bool {
|
||||
self.pending.load(Ordering::Acquire) == 0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
// Only shutdown waits: drain accepted jobs before releasing their frames.
|
||||
self.sender.take();
|
||||
if self.thread.take().unwrap().join().is_err() {
|
||||
eprintln!("[capture ERROR] Capture/print worker panicked");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on copies per capture so a misdetection cannot waste a paper roll.
|
||||
const MAX_COPIES: usize = 5;
|
||||
|
||||
/// Count the faces in the captured, clean selfie frame and print one copy each.
|
||||
/// Print failures are reported but never abort the worker.
|
||||
pub fn take_picture(
|
||||
frame: &opencv::core::Mat,
|
||||
detector: &mut crate::faces::Detector,
|
||||
printer: Option<&crate::printer::Printer>,
|
||||
) -> opencv::Result<()> {
|
||||
let faces = detector.count(frame)?;
|
||||
let copies = faces.min(MAX_COPIES);
|
||||
eprintln!(
|
||||
"[capture DEBUG] faces={faces} requested_copies={copies} printing={}",
|
||||
if printer.is_some() {
|
||||
"enabled"
|
||||
} else {
|
||||
"disabled"
|
||||
}
|
||||
);
|
||||
if let Some(printer) = printer
|
||||
&& let Err(error) = printer.print(frame, copies)
|
||||
{
|
||||
eprintln!("[capture ERROR] Printing failed: {error}");
|
||||
}
|
||||
|
||||
// Asynchronously write the photo to /dev/shm/latest.png if /dev/shm exists
|
||||
let shm_path = Path::new("/dev/shm");
|
||||
if shm_path.exists() && shm_path.is_dir() {
|
||||
let output_path = shm_path.join("latest.png");
|
||||
let frame_clone = frame.try_clone()?;
|
||||
thread::spawn(move || {
|
||||
if let Err(error) = opencv::imgcodecs::imwrite(
|
||||
output_path.to_str().unwrap_or("latest.png"),
|
||||
&frame_clone,
|
||||
&opencv::core::Vector::new(),
|
||||
) {
|
||||
eprintln!("[capture ERROR] Failed to write to /dev/shm/latest.png: {error}");
|
||||
} else {
|
||||
eprintln!("[capture DEBUG] Wrote photo to /dev/shm/latest.png");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn slow_processing_never_blocks_submission_and_shutdown_drains_jobs() {
|
||||
use opencv::{
|
||||
core::{CV_8UC1, Mat, Scalar},
|
||||
prelude::*,
|
||||
};
|
||||
use std::sync::mpsc::{self, TrySendError};
|
||||
let caller = std::thread::current().id();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
let (processed_tx, processed_rx) = mpsc::channel();
|
||||
let worker = Worker::spawn(move || {
|
||||
assert_ne!(std::thread::current().id(), caller);
|
||||
let mut first = true;
|
||||
move |frame: Mat| {
|
||||
if first {
|
||||
started_tx.send(()).unwrap();
|
||||
release_rx.recv().unwrap();
|
||||
first = false;
|
||||
}
|
||||
processed_tx
|
||||
.send(*frame.at_2d::<u8>(0, 0).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let frame =
|
||||
|value| Mat::new_rows_cols_with_default(1, 1, CV_8UC1, Scalar::all(value)).unwrap();
|
||||
assert!(worker.is_idle());
|
||||
worker.submit(frame(1.0)).unwrap();
|
||||
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(!worker.is_idle());
|
||||
// The first job is deliberately blocked, but enqueueing and rejecting
|
||||
// excess jobs must both return before it is allowed to finish.
|
||||
worker.submit(frame(2.0)).unwrap();
|
||||
assert!(matches!(
|
||||
worker.submit(frame(3.0)),
|
||||
Err(TrySendError::Full(_))
|
||||
));
|
||||
release_tx.send(()).unwrap();
|
||||
drop(worker);
|
||||
assert_eq!(processed_rx.into_iter().collect::<Vec<_>>(), vec![1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flash_countdown_and_single_capture_then_release() {
|
||||
let start = Instant::now();
|
||||
@@ -76,42 +252,52 @@ mod tests {
|
||||
assert!(sequence.tracking());
|
||||
assert!(!sequence.tick(true, true, start));
|
||||
assert!(!sequence.tracking());
|
||||
assert_eq!(sequence.presentation(start).countdown, 3);
|
||||
assert_eq!(sequence.presentation(start).flash_opacity, 0.75);
|
||||
assert_eq!(sequence.presentation(start).countdown, 5);
|
||||
assert_eq!(sequence.presentation(start).flash_opacity, 0.95);
|
||||
assert_eq!(
|
||||
sequence
|
||||
.presentation(start + Duration::from_millis(200))
|
||||
.flash_opacity,
|
||||
0.75
|
||||
0.95
|
||||
);
|
||||
for (ms, number) in [(999, 3), (1000, 2), (1999, 2), (2000, 1), (2999, 1)] {
|
||||
for (ms, number) in [
|
||||
(999, 5),
|
||||
(1000, 4),
|
||||
(1999, 4),
|
||||
(2000, 3),
|
||||
(2999, 3),
|
||||
(3000, 2),
|
||||
(3999, 2),
|
||||
(4000, 1),
|
||||
(4999, 1),
|
||||
] {
|
||||
let now = start + Duration::from_millis(ms);
|
||||
// Lowering the hand must not cancel an already-started countdown.
|
||||
assert!(!sequence.tick(false, false, now));
|
||||
assert_eq!(sequence.presentation(now).countdown, number);
|
||||
assert_eq!(sequence.presentation(now).flash_opacity, 0.75);
|
||||
assert_eq!(sequence.presentation(now).flash_opacity, 0.95);
|
||||
}
|
||||
assert!(sequence.tick(true, true, start + Duration::from_secs(3)));
|
||||
assert!(sequence.tick(true, true, start + Duration::from_secs(5)));
|
||||
assert!(
|
||||
sequence
|
||||
.presentation(start + Duration::from_secs(3))
|
||||
.presentation(start + Duration::from_secs(5))
|
||||
.awaiting_release
|
||||
);
|
||||
assert_eq!(
|
||||
sequence
|
||||
.presentation(start + Duration::from_secs(3))
|
||||
.presentation(start + Duration::from_secs(5))
|
||||
.countdown,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
sequence
|
||||
.presentation(start + Duration::from_secs(3))
|
||||
.presentation(start + Duration::from_secs(5))
|
||||
.flash_opacity,
|
||||
0.0
|
||||
);
|
||||
assert!(!sequence.tick(true, true, start + Duration::from_secs(4)));
|
||||
assert!(!sequence.tick(true, true, start + Duration::from_secs(6)));
|
||||
assert!(!sequence.tracking());
|
||||
assert!(!sequence.tick(false, false, start + Duration::from_secs(5)));
|
||||
assert!(!sequence.tick(false, false, start + Duration::from_secs(7)));
|
||||
assert!(sequence.tracking());
|
||||
}
|
||||
|
||||
|
||||
297
src/faces.rs
Normal file
297
src/faces.rs
Normal file
@@ -0,0 +1,297 @@
|
||||
//! Lightweight YuNet detection, shared by capture and debug-only live preview.
|
||||
use opencv::{
|
||||
core::{self, Mat, Point2f, Rect, Size, Vector},
|
||||
dnn, imgproc, objdetect,
|
||||
prelude::*,
|
||||
};
|
||||
use std::time::Instant;
|
||||
|
||||
pub struct Face {
|
||||
#[cfg_attr(not(debug_assertions), allow(dead_code))]
|
||||
pub bounds: Rect,
|
||||
pub accepted: bool,
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
/// BGR colors match the UI: green counts toward prints, blue is rejected.
|
||||
pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> {
|
||||
let thickness = (frame.cols().min(frame.rows()) / 240).max(1);
|
||||
for face in faces {
|
||||
let color = if face.accepted {
|
||||
core::Scalar::new(101.0, 191.0, 132.0, 0.0)
|
||||
} else {
|
||||
core::Scalar::new(227.0, 174.0, 76.0, 0.0)
|
||||
};
|
||||
imgproc::rectangle(frame, face.bounds, color, thickness, imgproc::LINE_8, 0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct Detector {
|
||||
net: core::Ptr<objdetect::FaceDetectorYN>,
|
||||
}
|
||||
|
||||
impl Detector {
|
||||
pub fn new() -> opencv::Result<Self> {
|
||||
let bytes = Vector::from_slice(include_bytes!(
|
||||
"../models/face_detection_yunet_2023mar.onnx"
|
||||
));
|
||||
Ok(Self {
|
||||
net: objdetect::FaceDetectorYN::create_1(
|
||||
"onnx",
|
||||
&bytes,
|
||||
&Vector::new(),
|
||||
Size::new(320, 320),
|
||||
0.8,
|
||||
0.3,
|
||||
500,
|
||||
dnn::DNN_BACKEND_OPENCV,
|
||||
dnn::DNN_TARGET_CPU,
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn count(&mut self, frame: &Mat) -> opencv::Result<usize> {
|
||||
Ok(self
|
||||
.detect(frame, true)?
|
||||
.iter()
|
||||
.filter(|face| face.accepted)
|
||||
.count())
|
||||
}
|
||||
|
||||
pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result<Vec<Face>> {
|
||||
let start = Instant::now();
|
||||
if frame.empty() {
|
||||
return Err(opencv::Error::new(
|
||||
core::StsBadArg,
|
||||
"Empty face detection image",
|
||||
));
|
||||
}
|
||||
// Aspect-preserving resize and padding keep inference at 320x320.
|
||||
let scale = 320.0 / frame.cols().max(frame.rows()) as f64;
|
||||
let width = (frame.cols() as f64 * scale).round() as i32;
|
||||
let height = (frame.rows() as f64 * scale).round() as i32;
|
||||
let mut resized = Mat::default();
|
||||
imgproc::resize(
|
||||
frame,
|
||||
&mut resized,
|
||||
Size::new(width, height),
|
||||
0.0,
|
||||
0.0,
|
||||
imgproc::INTER_LINEAR,
|
||||
)?;
|
||||
let mut padded = Mat::default();
|
||||
core::copy_make_border(
|
||||
&resized,
|
||||
&mut padded,
|
||||
0,
|
||||
320 - height,
|
||||
0,
|
||||
320 - width,
|
||||
core::BORDER_CONSTANT,
|
||||
core::Scalar::all(0.0),
|
||||
)?;
|
||||
let mut rows = Mat::default();
|
||||
self.net.detect(&padded, &mut rows)?;
|
||||
let mut faces = Vec::new();
|
||||
for row in 0..rows.rows() {
|
||||
let value = |col| rows.at_2d::<f32>(row, col).copied();
|
||||
let x = value(0)?;
|
||||
let y = value(1)?;
|
||||
let w = value(2)?;
|
||||
let h = value(3)?;
|
||||
let eye_a = Point2f::new(value(4)?, value(5)?);
|
||||
let eye_b = Point2f::new(value(6)?, value(7)?);
|
||||
let nose = Point2f::new(value(8)?, value(9)?);
|
||||
let accepted = facing_camera(eye_a, eye_b, nose, w);
|
||||
let bounds = map_bounds(x, y, w, h, Size::new(width, height), frame.size()?);
|
||||
if bounds.width <= 0 || bounds.height <= 0 {
|
||||
continue;
|
||||
}
|
||||
if debug {
|
||||
eprintln!(
|
||||
"[capture DEBUG] detector=yunet face={bounds:?} confidence={:.3} facing_camera={accepted}",
|
||||
value(14)?
|
||||
);
|
||||
}
|
||||
faces.push(Face { bounds, accepted });
|
||||
}
|
||||
if debug {
|
||||
let count = faces.iter().filter(|face| face.accepted).count();
|
||||
eprintln!(
|
||||
"[capture DEBUG] detector=yunet candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis=320x320",
|
||||
faces.len(),
|
||||
faces.len() - count,
|
||||
start.elapsed().as_millis()
|
||||
);
|
||||
}
|
||||
Ok(faces)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_bounds(x: f32, y: f32, w: f32, h: f32, input: Size, output: Size) -> Rect {
|
||||
let sx = output.width as f32 / input.width as f32;
|
||||
let sy = output.height as f32 / input.height as f32;
|
||||
let left = (x * sx).floor().clamp(0.0, output.width as f32) as i32;
|
||||
let top = (y * sy).floor().clamp(0.0, output.height as f32) as i32;
|
||||
let right = ((x + w) * sx).ceil().clamp(0.0, output.width as f32) as i32;
|
||||
let bottom = ((y + h) * sy).ceil().clamp(0.0, output.height as f32) as i32;
|
||||
Rect::new(left, top, (right - left).max(0), (bottom - top).max(0))
|
||||
}
|
||||
|
||||
// Project the nose onto the eye line: rotation and selfie mirroring do not
|
||||
// change the test. Reject strongly offset noses and compressed eye separation.
|
||||
// This estimates frontal head orientation, not where a person's eyes are looking.
|
||||
fn facing_camera(a: Point2f, b: Point2f, nose: Point2f, width: f32) -> bool {
|
||||
let dx = b.x - a.x;
|
||||
let dy = b.y - a.y;
|
||||
let distance_sq = dx * dx + dy * dy;
|
||||
let nose_position = ((nose.x - a.x) * dx + (nose.y - a.y) * dy) / distance_sq;
|
||||
width.is_finite()
|
||||
&& width > 0.0
|
||||
&& distance_sq.is_finite()
|
||||
&& distance_sq.sqrt() >= width * 0.23
|
||||
&& (0.15..=0.85).contains(&nose_position)
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub struct LivePreview {
|
||||
sender: Option<std::sync::mpsc::SyncSender<Mat>>,
|
||||
result: std::sync::Arc<std::sync::Mutex<(Instant, Vec<Face>)>>,
|
||||
worker: Option<std::thread::JoinHandle<()>>,
|
||||
last_sample: Instant,
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
impl LivePreview {
|
||||
pub fn new() -> opencv::Result<Self> {
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
let (sender, receiver) = mpsc::sync_channel::<Mat>(0);
|
||||
let result = Arc::new(Mutex::new((Instant::now(), Vec::new())));
|
||||
let worker_result = Arc::clone(&result);
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut detector = match Detector::new() {
|
||||
Ok(detector) => detector,
|
||||
Err(error) => {
|
||||
eprintln!("[faces ERROR] Could not load debug face model: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
while let Ok(frame) = receiver.recv() {
|
||||
let started = Instant::now();
|
||||
let faces = detector.detect(&frame, false).unwrap_or_else(|error| {
|
||||
eprintln!("[faces ERROR] Live detection failed: {error}");
|
||||
Vec::new()
|
||||
});
|
||||
*worker_result.lock().unwrap() = (started, faces);
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
sender: Some(sender),
|
||||
result,
|
||||
worker: Some(worker),
|
||||
last_sample: Instant::now() - std::time::Duration::from_millis(500),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn sample(&mut self, frame: &Mat) -> opencv::Result<()> {
|
||||
if self.last_sample.elapsed() >= std::time::Duration::from_millis(500) {
|
||||
// Drop samples while inference is busy: no backlog on the old kiosk CPU.
|
||||
let _ = self.sender.as_ref().unwrap().try_send(frame.try_clone()?);
|
||||
self.last_sample = Instant::now();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn draw(&self, frame: &mut Mat) -> opencv::Result<()> {
|
||||
let result = self.result.lock().unwrap();
|
||||
if result.0.elapsed() < std::time::Duration::from_millis(1500) {
|
||||
draw(frame, &result.1)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
impl Drop for LivePreview {
|
||||
fn drop(&mut self) {
|
||||
self.sender.take();
|
||||
if self.worker.take().unwrap().join().is_err() {
|
||||
eprintln!("[faces ERROR] Live detection worker panicked");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(debug_assertions)]
|
||||
#[test]
|
||||
fn overlay_draws_all_candidates_in_status_colors_without_filling_faces() -> opencv::Result<()> {
|
||||
let mut frame =
|
||||
Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(0.0))?;
|
||||
draw(
|
||||
&mut frame,
|
||||
&[
|
||||
Face {
|
||||
bounds: Rect::new(50, 60, 100, 100),
|
||||
accepted: true,
|
||||
},
|
||||
Face {
|
||||
bounds: Rect::new(200, 60, 100, 100),
|
||||
accepted: false,
|
||||
},
|
||||
],
|
||||
)?;
|
||||
assert_eq!(
|
||||
*frame.at_2d::<core::Vec3b>(60, 50)?,
|
||||
core::Vec3b::from([101, 191, 132])
|
||||
);
|
||||
assert_eq!(
|
||||
*frame.at_2d::<core::Vec3b>(60, 200)?,
|
||||
core::Vec3b::from([227, 174, 76])
|
||||
);
|
||||
assert_eq!(
|
||||
*frame.at_2d::<core::Vec3b>(100, 100)?,
|
||||
core::Vec3b::from([0, 0, 0])
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_orientation_tolerates_roll_and_mirroring_but_rejects_profiles() {
|
||||
let a = Point2f::new(20.0, 30.0);
|
||||
let b = Point2f::new(70.0, 40.0);
|
||||
let nose = Point2f::new(42.0, 60.0);
|
||||
assert!(facing_camera(a, b, nose, 100.0));
|
||||
assert!(facing_camera(b, a, nose, 100.0));
|
||||
assert!(!facing_camera(a, b, Point2f::new(75.0, 50.0), 100.0));
|
||||
assert!(!facing_camera(a, Point2f::new(30.0, 30.0), nose, 100.0));
|
||||
assert!(!facing_camera(a, a, nose, 100.0));
|
||||
assert!(!facing_camera(a, b, Point2f::new(f32::NAN, 50.0), 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_scale_back_to_selfie_frame_and_clip_padding() {
|
||||
let input = Size::new(320, 240);
|
||||
let output = Size::new(640, 480);
|
||||
assert_eq!(
|
||||
map_bounds(150.0, 50.0, 80.0, 90.0, input, output),
|
||||
Rect::new(300, 100, 160, 180)
|
||||
);
|
||||
assert_eq!(
|
||||
map_bounds(-10.0, 220.0, 50.0, 60.0, input, output),
|
||||
Rect::new(0, 440, 80, 40)
|
||||
);
|
||||
assert_eq!(map_bounds(20.0, 250.0, 50.0, 40.0, input, output).height, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_yunet_runs_on_blank_capture() -> opencv::Result<()> {
|
||||
let mut detector = Detector::new()?;
|
||||
let frame =
|
||||
Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(128.0))?;
|
||||
assert_eq!(detector.count(&frame)?, 0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
55
src/main.rs
55
src/main.rs
@@ -20,11 +20,15 @@ use slint::{Rgb8Pixel, SharedPixelBuffer};
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
mod artwork;
|
||||
mod camera;
|
||||
mod capture;
|
||||
mod diagnostics;
|
||||
mod faces;
|
||||
mod hand_pose;
|
||||
mod palm;
|
||||
mod printer;
|
||||
mod quotes;
|
||||
|
||||
struct PreviewFrame {
|
||||
buffer: SharedPixelBuffer<Rgb8Pixel>,
|
||||
@@ -33,6 +37,16 @@ struct PreviewFrame {
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Load `.env` before any thread starts, since it sets process variables.
|
||||
// Values already present in the real environment take precedence.
|
||||
match dotenvy::dotenv() {
|
||||
Ok(path) => eprintln!("[config INFO] Loaded {}", path.display()),
|
||||
Err(error) if error.not_found() => {}
|
||||
Err(error) => eprintln!("[config ERROR] Could not load .env: {error}"),
|
||||
}
|
||||
// One OpenCV inference thread per worker leaves CPU time for the camera/UI
|
||||
// on the dual-core kiosk instead of each model spawning two busy threads.
|
||||
core::set_num_threads(1)?;
|
||||
if let Err(error) = diagnostics::log_runtime() {
|
||||
eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
|
||||
}
|
||||
@@ -44,7 +58,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
|
||||
mirror_frame(&mut frame)?;
|
||||
|
||||
let mut detector = palm::Detector::new()?;
|
||||
let capture_worker = capture::Worker::new();
|
||||
#[cfg(debug_assertions)]
|
||||
let mut live_faces = faces::LivePreview::new()?;
|
||||
let ui = AppWindow::new()?;
|
||||
|
||||
ui.window()
|
||||
@@ -65,6 +81,13 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
// A rendezvous channel drops samples while inference is busy, avoiding a backlog.
|
||||
let (detection_tx, detection_rx) = mpsc::sync_channel::<Mat>(0);
|
||||
let detection_worker = thread::spawn(move || {
|
||||
let mut detector = match palm::Detector::new() {
|
||||
Ok(detector) => detector,
|
||||
Err(error) => {
|
||||
eprintln!("[detection ERROR] Could not load palm/hand models: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut inference_log = diagnostics::SlowLog::new(
|
||||
"palm + open-hand detection",
|
||||
palm::DETECTION_INTERVAL,
|
||||
@@ -114,15 +137,33 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let _ = detection_tx.try_send(frame.try_clone()?);
|
||||
last_detection = now;
|
||||
}
|
||||
let mut tracker = tracker.lock().unwrap();
|
||||
let hand_detected = tracker.has_palm(now);
|
||||
if sequence.tick(tracker.complete(now), hand_detected, now) {
|
||||
capture::take_picture();
|
||||
#[cfg(debug_assertions)]
|
||||
live_faces.sample(&frame)?;
|
||||
let mut tracker_guard = tracker.lock().unwrap();
|
||||
let hand_detected = tracker_guard.has_palm(now);
|
||||
// Wait to start another countdown while a capture/print job is
|
||||
// pending. The live preview and palm tracking keep running.
|
||||
let take_picture = sequence.tick(
|
||||
tracker_guard.complete(now) && capture_worker.is_idle(),
|
||||
hand_detected,
|
||||
now,
|
||||
);
|
||||
if take_picture {
|
||||
// The snapshot is the capture: lighting can end after this copy.
|
||||
// Face counting and thermal printing run on their own worker.
|
||||
let snapshot = frame.try_clone()?;
|
||||
if let Err(error) = capture_worker.submit(snapshot) {
|
||||
eprintln!("[capture ERROR] Capture not queued: {error}");
|
||||
}
|
||||
}
|
||||
if sequence.tracking() {
|
||||
tracker.draw(&mut frame, now)?;
|
||||
tracker_guard.draw(&mut frame, now)?;
|
||||
}
|
||||
drop(tracker);
|
||||
drop(tracker_guard);
|
||||
// Draw only after capture and palm sampling so printed photos and
|
||||
// detector inputs never contain debug rectangles.
|
||||
#[cfg(debug_assertions)]
|
||||
live_faces.draw(&mut frame)?;
|
||||
let preview = PreviewFrame {
|
||||
buffer: frame_to_buffer(&frame)?,
|
||||
hand_detected,
|
||||
|
||||
790
src/printer.rs
Normal file
790
src/printer.rs
Normal file
@@ -0,0 +1,790 @@
|
||||
//! ESC/POS thermal printing for captured photos.
|
||||
//!
|
||||
//! Configuration (environment variables or the committed `.env`; read once at
|
||||
//! startup):
|
||||
//! - `PHOTOBOOTH_PRINTER`: where to send print data. Either a device path such as
|
||||
//! `/dev/usb/lp0` (USB printer class) or a raw network printer as
|
||||
//! `tcp://host[:port]` (port defaults to 9100). Defaults to `/dev/usb/lp0`;
|
||||
//! set it to an empty value to disable printing.
|
||||
//! - `PHOTOBOOTH_PRINTER_DOTS`: printable width in dots, rounded down to a multiple
|
||||
//! 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.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),
|
||||
//! `silent` (180 mm/s) or `high` (200 mm/s) (SII `GS s n`). Unset by default.
|
||||
//!
|
||||
//! Both head settings belong to the SII RP-D10 command set and are only sent
|
||||
//! when configured, because a printer that does not implement them loses sync
|
||||
//! and prints the raster data that follows as text - metres of it. The tested
|
||||
//! Birch 0CP-Q3 does exactly that with either command, so leave both unset
|
||||
//! unless the printer is known to understand them. They are sent with every
|
||||
//! 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. 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
|
||||
//! dithered, in that order: scaling a dithered image would ruin the pattern.
|
||||
//!
|
||||
//! Serial printers must have their baud rate set beforehand (for example with
|
||||
//! `stty -F /dev/ttyUSB0 9600`); this module only writes bytes.
|
||||
|
||||
use std::{
|
||||
fs::OpenOptions,
|
||||
io::Write,
|
||||
net::{TcpStream, ToSocketAddrs},
|
||||
path::PathBuf,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use chrono::Local;
|
||||
use opencv::{
|
||||
core::{self, Mat, Size},
|
||||
imgproc,
|
||||
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.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;
|
||||
const CLAHE_TILES: i32 = 8;
|
||||
/// Unsharp mask: blur radius in dots and how much of the detail to add back.
|
||||
const SHARPEN_SIGMA: f64 = 1.0;
|
||||
const SHARPEN_AMOUNT: f64 = 0.5;
|
||||
const DEFAULT_NETWORK_PORT: u16 = 9100;
|
||||
const NETWORK_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Raster rows per `GS v 0` command, 4.5 KiB per band at 576 dots.
|
||||
const BAND_ROWS: usize = 64;
|
||||
const FEED_LINES: u8 = 4;
|
||||
/// Caption printed around every photo.
|
||||
const EVENT_TITLE: &str = "WINFNACHTEN";
|
||||
const EVENT_PLACE: &str = "WINF Treitlstraße 3";
|
||||
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";
|
||||
/// 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);
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Target {
|
||||
Device(PathBuf),
|
||||
Network(String),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(match value.strip_prefix("tcp://") {
|
||||
Some(address) if address.contains(':') => Self::Network(address.to_owned()),
|
||||
Some(address) => Self::Network(format!("{address}:{DEFAULT_NETWORK_PORT}")),
|
||||
None => Self::Device(PathBuf::from(value)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum print speeds of the SII `GS s n` command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Speed {
|
||||
High,
|
||||
Quality,
|
||||
Low,
|
||||
Silent,
|
||||
}
|
||||
|
||||
impl Speed {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"high" => Some(Self::High),
|
||||
"quality" => Some(Self::Quality),
|
||||
"low" => Some(Self::Low),
|
||||
"silent" => Some(Self::Silent),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
Self::High => 0,
|
||||
Self::Quality => 1,
|
||||
Self::Low => 2,
|
||||
Self::Silent => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Head settings sent before each job; `None` leaves the printer's own setting.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Head {
|
||||
density: Option<u8>,
|
||||
speed: Option<Speed>,
|
||||
}
|
||||
|
||||
impl Head {
|
||||
/// Either command is sent only when its variable holds a valid value, so
|
||||
/// that printers which do not implement them never see them.
|
||||
fn from_values(density: Option<&str>, speed: Option<&str>) -> Self {
|
||||
Self {
|
||||
density: density
|
||||
.and_then(|value| value.trim().parse::<u8>().ok())
|
||||
.filter(|density| DENSITY_RANGE.contains(density)),
|
||||
speed: speed.and_then(Speed::parse),
|
||||
}
|
||||
}
|
||||
|
||||
fn commands(&self) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
if let Some(density) = self.density {
|
||||
bytes.extend([0x12, b'~', density]); // DC2 ~ n: print density in %
|
||||
}
|
||||
if let Some(speed) = self.speed {
|
||||
bytes.extend([0x1D, b's', speed.code()]); // GS s n: print speed
|
||||
}
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Printer {
|
||||
target: Target,
|
||||
dots: usize,
|
||||
gamma: f32,
|
||||
head: Head,
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
/// Returns `None` only when `PHOTOBOOTH_PRINTER` is explicitly empty.
|
||||
pub fn from_env() -> Option<Self> {
|
||||
Self::from_values(
|
||||
std::env::var("PHOTOBOOTH_PRINTER").ok().as_deref(),
|
||||
std::env::var("PHOTOBOOTH_PRINTER_DOTS").ok().as_deref(),
|
||||
std::env::var("PHOTOBOOTH_PRINTER_GAMMA").ok().as_deref(),
|
||||
)
|
||||
.map(|printer| Self {
|
||||
head: Head::from_values(
|
||||
std::env::var("PHOTOBOOTH_PRINTER_DENSITY").ok().as_deref(),
|
||||
std::env::var("PHOTOBOOTH_PRINTER_SPEED").ok().as_deref(),
|
||||
),
|
||||
..printer
|
||||
})
|
||||
}
|
||||
|
||||
fn from_values(printer: Option<&str>, dots: Option<&str>, gamma: Option<&str>) -> Option<Self> {
|
||||
let target = Target::parse(printer.unwrap_or(DEFAULT_PRINTER))?;
|
||||
let dots = dots
|
||||
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||
.map_or(DEFAULT_DOTS, |dots| dots / 8 * 8)
|
||||
.max(8);
|
||||
let gamma = gamma
|
||||
.and_then(|value| value.trim().parse::<f32>().ok())
|
||||
.filter(|gamma| gamma.is_finite() && *gamma > 0.0)
|
||||
.unwrap_or(DEFAULT_GAMMA);
|
||||
Some(Self {
|
||||
target,
|
||||
dots,
|
||||
gamma,
|
||||
head: Head::from_values(None, None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Prints `copies` identical cut-separated copies of the (BGR) frame.
|
||||
pub fn print(&self, frame: &Mat, copies: usize) -> Result<(), String> {
|
||||
if copies == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
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(),
|
||||
clock_seed(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Sends the job one write at a time, pacing them to the print head.
|
||||
fn send(&self, job: &[Vec<u8>]) -> Result<(), String> {
|
||||
let mut sink: Box<dyn Write> = match &self.target {
|
||||
Target::Device(path) => Box::new(
|
||||
// Opened per job so an unplugged and re-attached printer recovers.
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|error| format!("open {}: {error}", path.display()))?,
|
||||
),
|
||||
Target::Network(address) => {
|
||||
let socket = address
|
||||
.to_socket_addrs()
|
||||
.map_err(|error| format!("resolve {address}: {error}"))?
|
||||
.next()
|
||||
.ok_or_else(|| format!("resolve {address}: no address"))?;
|
||||
let stream = TcpStream::connect_timeout(&socket, NETWORK_TIMEOUT)
|
||||
.map_err(|error| format!("connect {address}: {error}"))?;
|
||||
stream
|
||||
.set_write_timeout(Some(NETWORK_TIMEOUT * 2))
|
||||
.map_err(|error| format!("configure {address}: {error}"))?;
|
||||
Box::new(stream)
|
||||
}
|
||||
};
|
||||
for (index, write) in job.iter().enumerate() {
|
||||
if index > 0 {
|
||||
std::thread::sleep(PACE);
|
||||
}
|
||||
sink.write_all(write)
|
||||
.and_then(|()| sink.flush())
|
||||
.map_err(|error| format!("write: {error}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 1-bit bitmap, row-major, most significant bit first; a set bit is a black dot.
|
||||
struct Bitmap {
|
||||
width_bytes: usize,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
fn render(frame: &Mat, dots: usize, gamma: f32) -> opencv::Result<Bitmap> {
|
||||
let rows = (frame.rows() as usize * dots / frame.cols().max(1) as usize).max(1);
|
||||
let mut gray = Mat::default();
|
||||
imgproc::cvt_color_def(frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
|
||||
// Resize to the exact head width first; everything after works per dot.
|
||||
let mut resized = Mat::default();
|
||||
imgproc::resize(
|
||||
&gray,
|
||||
&mut resized,
|
||||
Size::new(dots as i32, rows as i32),
|
||||
0.0,
|
||||
0.0,
|
||||
imgproc::INTER_AREA,
|
||||
)?;
|
||||
// Local contrast equalization keeps faces from sinking into the shadows.
|
||||
let mut equalized = Mat::default();
|
||||
imgproc::create_clahe(CLAHE_CLIP_LIMIT, Size::new(CLAHE_TILES, CLAHE_TILES))?
|
||||
.apply(&resized, &mut equalized)?;
|
||||
// Unsharp mask: original + amount * (original - blurred).
|
||||
let mut blurred = Mat::default();
|
||||
imgproc::gaussian_blur_def(&equalized, &mut blurred, Size::new(0, 0), SHARPEN_SIGMA)?;
|
||||
let mut sharpened = Mat::default();
|
||||
core::add_weighted_def(
|
||||
&equalized,
|
||||
1.0 + SHARPEN_AMOUNT,
|
||||
&blurred,
|
||||
-SHARPEN_AMOUNT,
|
||||
0.0,
|
||||
&mut sharpened,
|
||||
)?;
|
||||
let sharpened = sharpened.try_clone()?; // contiguous bytes
|
||||
let curve = gamma_curve(gamma);
|
||||
let brightened: Vec<u8> = sharpened
|
||||
.data_bytes()?
|
||||
.iter()
|
||||
.map(|&value| curve[usize::from(value)])
|
||||
.collect();
|
||||
Ok(Bitmap {
|
||||
width_bytes: dots / 8,
|
||||
data: dither(&brightened, dots, rows),
|
||||
})
|
||||
}
|
||||
|
||||
/// Lookup table lifting mid-tones, since thermal dot gain darkens them again.
|
||||
fn gamma_curve(gamma: f32) -> [u8; 256] {
|
||||
std::array::from_fn(|value| (255.0 * (value as f32 / 255.0).powf(1.0 / gamma)).round() as u8)
|
||||
}
|
||||
|
||||
/// Atkinson error diffusion: thermal heads only print black or nothing.
|
||||
///
|
||||
/// Only 6/8 of the error is passed on, which keeps highlights open and gives
|
||||
/// the lighter look that suits thermal paper better than Floyd-Steinberg.
|
||||
fn dither(gray: &[u8], width: usize, rows: usize) -> Vec<u8> {
|
||||
let stride = width / 8;
|
||||
let mut packed = vec![0u8; stride * rows];
|
||||
// Error rows are padded (one cell left, two right) to avoid edge branches;
|
||||
// cell `x + 1` belongs to pixel `x`.
|
||||
let mut errors = [(); 3].map(|()| vec![0f32; width + 3]);
|
||||
for y in 0..rows {
|
||||
for x in 0..width {
|
||||
let wanted = f32::from(gray[y * width + x]) + errors[0][x + 1];
|
||||
let black = wanted < 128.0;
|
||||
if black {
|
||||
packed[y * stride + x / 8] |= 0x80 >> (x % 8);
|
||||
}
|
||||
let share = (wanted - if black { 0.0 } else { 255.0 }) / 8.0;
|
||||
errors[0][x + 2] += share;
|
||||
errors[0][x + 3] += share;
|
||||
errors[1][x] += share;
|
||||
errors[1][x + 1] += share;
|
||||
errors[1][x + 2] += share;
|
||||
errors[2][x + 1] += share;
|
||||
}
|
||||
errors.rotate_left(1);
|
||||
errors[2].fill(0.0);
|
||||
}
|
||||
packed
|
||||
}
|
||||
|
||||
/// Encodes the job as a sequence of writes: one per raster band, then one feed
|
||||
/// and cut per copy.
|
||||
///
|
||||
/// Every band is re-initialized and carries exactly one raster command. The
|
||||
/// tested Birch 0CP-Q3 only keeps sync when `GS v 0` follows `ESC @` directly:
|
||||
/// given several bands in one initialized stream it abandons the image and
|
||||
/// prints the remaining dot data as text, about two metres of it per photo.
|
||||
fn encode(
|
||||
bitmap: &Bitmap,
|
||||
head: &Head,
|
||||
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
|
||||
write.extend(head.commands());
|
||||
write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density
|
||||
write.extend((bitmap.width_bytes as u16).to_le_bytes());
|
||||
write.extend((rows as u16).to_le_bytes());
|
||||
write.extend(band);
|
||||
job.push(write);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
'ö' => 0x94,
|
||||
'ü' => 0x81,
|
||||
'Ä' => 0x8E,
|
||||
'Ö' => 0x99,
|
||||
'Ü' => 0x9A,
|
||||
'ß' => 0xE1,
|
||||
'·' => 0xFA,
|
||||
ascii if ascii.is_ascii() => ascii as u8,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.push(b'\n');
|
||||
}
|
||||
|
||||
/// Starts a write with `ESC @` and the head settings, then centres the text.
|
||||
fn centered(head: &Head) -> Vec<u8> {
|
||||
let mut write = vec![0x1B, b'@']; // ESC @: initialize
|
||||
write.extend(head.commands());
|
||||
write.extend([0x1B, b'a', 1]); // ESC a n: centre the following lines
|
||||
write
|
||||
}
|
||||
|
||||
/// Emphasizes the next line: double width and height, bold.
|
||||
const LARGE: [u8; 6] = [0x1D, b'!', 0x11, 0x1B, b'E', 1]; // GS ! n, ESC E n
|
||||
const SMALL: [u8; 6] = [0x1D, b'!', 0x00, 0x1B, b'E', 0];
|
||||
|
||||
fn header(head: &Head) -> Vec<u8> {
|
||||
let mut write = centered(head);
|
||||
write.extend(LARGE);
|
||||
text_line(&mut write, EVENT_TITLE);
|
||||
write.extend(SMALL);
|
||||
text_line(&mut write, EVENT_PLACE);
|
||||
write.extend([0x1B, b'd', 1]); // a blank line between caption and photo
|
||||
write
|
||||
}
|
||||
|
||||
/// Which quote the next slip gets. The clock is random enough for a joke, and
|
||||
/// saves pulling in a generator.
|
||||
fn first_quote() -> usize {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |since| since.subsec_nanos() as usize)
|
||||
% QUOTES.len()
|
||||
}
|
||||
|
||||
/// 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);
|
||||
text_line(&mut write, KEEPSAKE_DE);
|
||||
write.extend(SMALL);
|
||||
text_line(&mut write, KEEPSAKE_EN);
|
||||
write.extend([0x1B, b'd', 1]);
|
||||
text_line(&mut write, stamp);
|
||||
write.extend([0x1B, b'd', 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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const STAMP: &str = "14.11.2026, 15:42";
|
||||
|
||||
/// Every line the booth prints, large or small.
|
||||
fn printed_lines() -> impl Iterator<Item = &'static str> {
|
||||
[EVENT_TITLE, EVENT_PLACE, KEEPSAKE_DE, KEEPSAKE_EN, STAMP]
|
||||
.into_iter()
|
||||
.chain(QUOTES.iter().flat_map(|quote| quote.iter().copied()))
|
||||
}
|
||||
|
||||
fn contains_line(write: &[u8], line: &str) -> bool {
|
||||
let mut needle = Vec::new();
|
||||
text_line(&mut needle, line);
|
||||
write.windows(needle.len()).any(|window| window == needle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printed_lines_fit_an_80_mm_line() {
|
||||
// Font A is 12 dots wide, so 48 columns; the large lines take two each.
|
||||
let columns = DEFAULT_DOTS / 12;
|
||||
for line in [EVENT_TITLE, KEEPSAKE_DE] {
|
||||
assert!(line.chars().count() <= columns / 2, "{line}");
|
||||
}
|
||||
for line in printed_lines().filter(|line| ![EVENT_TITLE, KEEPSAKE_DE].contains(line)) {
|
||||
assert!(line.chars().count() <= columns, "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_text_is_sent_in_the_printers_code_page() {
|
||||
let mut write = Vec::new();
|
||||
text_line(&mut write, "schönste Prüfung, Fächer, Straße");
|
||||
assert_eq!(write, b"sch\x94nste Pr\x81fung, F\x84cher, Stra\xE1e\n");
|
||||
// No printed line needs a character the code page lacks.
|
||||
for line in printed_lines() {
|
||||
assert!(
|
||||
line.chars().all(|character| code_page(character).is_some()),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_are_picked_from_the_list_and_vary() {
|
||||
let picked: std::collections::BTreeSet<usize> = (0..1000).map(|_| first_quote()).collect();
|
||||
assert!(picked.last().is_some_and(|last| *last < QUOTES.len()));
|
||||
// Not all of them on a coarse clock, but a slip must not be predictable.
|
||||
assert!(picked.len() > 1, "{picked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_device_and_network_targets() {
|
||||
assert_eq!(Target::parse(" "), None);
|
||||
assert_eq!(
|
||||
Target::parse("/dev/usb/lp0"),
|
||||
Some(Target::Device("/dev/usb/lp0".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
Target::parse("tcp://192.168.0.5"),
|
||||
Some(Target::Network("192.168.0.5:9100".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
Target::parse("tcp://printer.local:9101"),
|
||||
Some(Target::Network("printer.local:9101".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unset_variables_fall_back_to_80mm_usb_printer() {
|
||||
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.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);
|
||||
assert_eq!(dots(" 390 "), 384);
|
||||
// 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.7);
|
||||
assert_eq!(gamma("bright"), 2.7);
|
||||
// An explicitly empty printer disables printing.
|
||||
assert!(Printer::from_values(Some(""), None, None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_commands_are_sent_only_when_configured() {
|
||||
// Unset, empty, out-of-range and unknown values all send nothing.
|
||||
for (density, speed) in [
|
||||
(None, None),
|
||||
(Some(""), Some(" ")),
|
||||
(Some("140"), Some("fast")),
|
||||
] {
|
||||
let head = Head::from_values(density, speed);
|
||||
assert_eq!(head, Head::default(), "{density:?} {speed:?}");
|
||||
assert!(head.commands().is_empty(), "{density:?} {speed:?}");
|
||||
}
|
||||
// Valid values are sent as the SII commands.
|
||||
let head = Head::from_values(Some(" 70 "), Some("Low"));
|
||||
assert_eq!(head.commands(), [0x12, b'~', 70, 0x1D, b's', 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_head_settings_precede_every_raster_band() {
|
||||
let bitmap = Bitmap {
|
||||
width_bytes: 1,
|
||||
data: vec![0; BAND_ROWS + 1],
|
||||
};
|
||||
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
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamma_curve_lifts_mid_tones_and_keeps_endpoints() {
|
||||
let curve = gamma_curve(2.0);
|
||||
assert_eq!((curve[0], curve[255]), (0, 255));
|
||||
assert_eq!(curve[64], 128); // sqrt(0.25) = 0.5
|
||||
assert!(curve.windows(2).all(|pair| pair[0] <= pair[1]));
|
||||
assert_eq!(gamma_curve(1.0), std::array::from_fn(|value| value as u8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dithers_extremes_and_packs_msb_first() {
|
||||
assert_eq!(dither(&[0; 16], 16, 1), vec![0xFF, 0xFF]);
|
||||
assert_eq!(dither(&[255; 16], 16, 1), vec![0x00, 0x00]);
|
||||
let mut half = [255u8; 8];
|
||||
half[0] = 0;
|
||||
assert_eq!(dither(&half, 8, 1), vec![0x80]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mid_gray_prints_roughly_half_the_dots() {
|
||||
let packed = dither(&[128; 64 * 64], 64, 64);
|
||||
let black: u32 = packed.iter().map(|byte| byte.count_ones()).sum();
|
||||
assert!((1800..2300).contains(&black), "black dots: {black}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_one_initialized_raster_command_per_write() {
|
||||
let bitmap = Bitmap {
|
||||
width_bytes: 2,
|
||||
data: vec![0xAA; 2 * (BAND_ROWS + 1)],
|
||||
};
|
||||
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!(
|
||||
©[2][..10],
|
||||
[0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0]
|
||||
);
|
||||
assert_eq!(copy[2].len(), 10 + 2 * BAND_ROWS);
|
||||
assert_eq!(
|
||||
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 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[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!(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}");
|
||||
let cuts = job
|
||||
.iter()
|
||||
.filter(|write| write.ends_with(&[0x1D, b'V', 66, 3]))
|
||||
.count();
|
||||
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!"],
|
||||
];
|
||||
@@ -61,7 +61,7 @@ fn check_transitions(repaint: RepaintBufferType, buffer_count: usize) {
|
||||
let instructions = frames.render(&ui, &window);
|
||||
for _ in 0..2 {
|
||||
ui.set_countdown(3);
|
||||
ui.set_flash_opacity(0.75);
|
||||
ui.set_flash_opacity(0.95);
|
||||
for _ in 0..3 {
|
||||
frames.render(&ui, &window);
|
||||
}
|
||||
|
||||
@@ -142,6 +142,35 @@ export component AppWindow inherits Window {
|
||||
active: root.hand-detected;
|
||||
}
|
||||
}
|
||||
if root.flash-opacity > 0: Rectangle {
|
||||
// Keep the portrait below the central countdown and most of the
|
||||
// monitor white so it continues to provide light for the photo.
|
||||
width: min(360px * root.ui-scale, root.width * 0.65, root.height * 0.36);
|
||||
height: self.width * 200 / 360 + 40px * root.ui-scale;
|
||||
x: (root.width - self.width) / 2;
|
||||
y: root.height - self.height - root.inset - root.safe-area-insets.bottom;
|
||||
background: transparent;
|
||||
pose-label := Text {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: parent.width;
|
||||
height: 32px * root.ui-scale;
|
||||
text: "Pose!";
|
||||
color: #20302b77;
|
||||
font-size: 26px * root.ui-scale;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Image {
|
||||
x: 0px;
|
||||
y: pose-label.y + pose-label.height + 8px * root.ui-scale;
|
||||
width: parent.width;
|
||||
height: parent.height - self.y;
|
||||
source: @image-url("assets/photo-pose.svg");
|
||||
image-fit: contain;
|
||||
}
|
||||
}
|
||||
if root.countdown > 0: Text {
|
||||
width: root.width;
|
||||
height: root.height;
|
||||
|
||||
27
ui/assets/photo-pose.svg
Normal file
27
ui/assets/photo-pose.svg
Normal file
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="360" height="200" viewBox="0 0 360 200" fill="none" stroke="#20302b" stroke-opacity="0.467" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Round portrait proportions: peace sign and hand on hip. -->
|
||||
<ellipse cx="91" cy="48" rx="29" ry="31" transform="rotate(-12 91 48)"/>
|
||||
<path d="M78 80C65 82 62 98 55 99S40 87 34 81M30 92C40 110 51 122 62 117L69 113C65 129 63 139 71 145C82 153 109 153 118 145C124 139 120 123 118 114L133 125L121 136C115 142 123 151 130 146L149 132C157 126 154 118 148 113L117 88Q109 82 105 82"/>
|
||||
<path d="M34 81Q42 72 38 63L37 45C37 39 29 39 29 45L29 61L22 45C19 39 12 43 15 49L24 70C15 61 9 69 15 76L30 92M73 147L68 174Q50 175 51 184Q52 190 62 190L75 190Q82 190 84 182L92 158L103 174L98 180Q91 190 100 193Q105 195 110 190L124 179Q130 174 125 167L113 149"/>
|
||||
<!-- A different pose: arms arched overhead and a leg kicked sideways. -->
|
||||
<ellipse cx="267" cy="72" rx="30" ry="29" transform="rotate(15 267 72)"/>
|
||||
<!-- A single body outline keeps the hips and kicked leg free of seams.
|
||||
Both raised arms stay clear of the head. -->
|
||||
<path d="M232 68
|
||||
C229 61 225 45 230 35
|
||||
Q235 27 229 23 Q223 19 218 27
|
||||
C209 42 215 61 226 80
|
||||
C233 93 245 103 255 104
|
||||
C245 115 241 131 248 145
|
||||
L244 173 Q227 175 229 183
|
||||
Q230 190 240 189 L250 188
|
||||
Q259 187 260 179 L266 155
|
||||
L301 172 Q309 176 316 169
|
||||
L337 149 Q344 142 338 137
|
||||
Q332 132 326 139 L308 154
|
||||
L287 134 C285 121 284 112 279 104
|
||||
C289 100 301 89 309 75
|
||||
C320 57 324 37 315 24
|
||||
Q310 17 304 21 Q298 25 303 33
|
||||
C308 44 306 57 303 64"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
Reference in New Issue
Block a user