kallo-core 0.1.0

Reference film model: characteristic curves and development kinetics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Generates `FILM_STOCKS` from the `.kalofilm` files at build time.
//!
//! The film data used to be compiled into `emulsion.rs` and `measured.rs` as
//! Rust literals, which put a CC BY-SA work inside MIT/Apache-2.0 program text and
//! made the licence boundary a matter of reading intent. It is now data: the
//! films are the same `.kalofilm` files the renderer can load, the build reads
//! them, and the crate contains no digitised film numbers at all.
//!
//! This runs at build time rather than at load time on purpose: the tables are
//! still `const` arrays, so nothing about the renderer's performance or its API
//! changes. The files come from the `kallo-data` crate, which carries a copy of
//! the repository's `data/` directory so that a build from crates.io needs no
//! checkout.
//!
//! The header parser is deliberately strict and small: the header is written by
//! `pack_film.py`, the same generator that wrote these files, so it contains
//! exactly the subset of TOML parsed here — sections, `key = value`, plain
//! strings, numbers and numeric arrays.

use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;

const GRID_LEN: usize = 71;
const MAGIC: &[u8; 8] = b"KALOFILM";
const PAPER_MAGIC: &[u8; 8] = b"KALOPAPR";

fn main() {
    let mut films: Vec<Film> = kallo_data::FILMS
        .iter()
        .map(|source| read(source.name, source.bytes))
        .filter(|film| film.kind == Kind::Film)
        .collect();
    let mut papers: Vec<Film> = kallo_data::PAPERS
        .iter()
        .map(|source| read(source.name, source.bytes))
        .filter(|film| film.kind == Kind::Paper)
        .collect();
    assert!(!films.is_empty(), "the data crate carries no films");
    films.sort_by(|a, b| a.header.get("", "id").cmp(b.header.get("", "id")));
    papers.sort_by(|a, b| a.header.get("", "id").cmp(b.header.get("", "id")));

    let mut code = String::new();
    code.push_str("// @generated by build.rs from the `.kalofilm` files. Do not edit.\n\n");
    code.push_str("/// A zero mask: a reversal has no orange mask, and the format says so by\n");
    code.push_str("/// omitting the table.\n");
    code.push_str("pub(crate) const NO_MASK: [f64; GRID_LEN] = [0.0; GRID_LEN];\n\n");
    code.push_str(
        "/// The VISION3 500T digitisation, the dye and mask set every negative without\n",
    );
    code.push_str("/// its own borrows. Read from that film's own file.\n");
    code.push_str("pub(crate) const FILM_DYES: [[f64; GRID_LEN]; 3] = DYES_VISION3_500T;\n");
    code.push_str("pub(crate) const FILM_MASK: [f64; GRID_LEN] = MASK_VISION3_500T;\n\n");
    code.push_str("/// The paper spectra the same way: the metallic sheet's set is the\n");
    code.push_str("/// compiled default, and E-4021's set is the one its two papers share.\n");
    code.push_str(
        "pub(crate) const PAPER_DYES: [[f64; GRID_LEN]; 3] = DYES_ENDURA_PREMIER_METALLIC;\n",
    );
    code.push_str(
        "pub(crate) const PAPER_LAYERS: [[f64; GRID_LEN]; 3] = LAYERS_ENDURA_PREMIER_METALLIC;\n",
    );
    code.push('\n');

    for (index, film) in films.iter().enumerate() {
        film.emit_tables(&mut code, index);
    }

    code.push_str("/// Every film stock, in id order.\n");
    code.push_str("#[allow(clippy::approx_constant)] // a measurement can sit near pi\n");
    code.push_str("pub static FILM_STOCKS: &[FilmStock] = &[\n");
    for (index, film) in films.iter().enumerate() {
        film.emit_stock(&mut code, index);
    }
    code.push_str("];\n");

    for (index, paper) in papers.iter().enumerate() {
        paper.emit_paper_tables(&mut code, index);
    }
    code.push_str("/// Every paper stock, in id order.\n");
    code.push_str("pub static PAPER_STOCKS: &[PaperStock] = &[\n");
    for (index, paper) in papers.iter().enumerate() {
        paper.emit_paper(&mut code, index);
    }
    code.push_str("];\n");

    let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR")).join("film_stocks.rs");
    fs::write(&out, code).expect("write the generated film table");

    // The data files themselves are watched by `kallo-data`'s build script, and
    // a rebuild of that crate reruns this one.
    println!("cargo:rerun-if-changed=build.rs");
}

/// The header of one `.kalofilm`, split into its sections.
struct Header {
    sections: BTreeMap<String, BTreeMap<String, String>>,
}

/// A header string, escaped for the Rust literal it is about to become.
///
/// The provenance sentences are prose and carry quotes and the odd backslash;
/// a note that does not survive the trip into the binary is a note the renderer
/// cannot repeat, which is the one thing this data is for.
fn escaped(text: &str) -> String {
    text.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The order the model reads a stock's fields in, and therefore the order a
/// record shows them: shape first, texture last.
const MEASURED_ORDER: [&str; 7] = [
    "curves", "layers", "dyes", "mask", "mtf", "grain", "cl_layer",
];

impl Header {
    fn get(&self, section: &str, key: &str) -> &str {
        let value = self
            .sections
            .get(section)
            .and_then(|values| values.get(key))
            .map(String::as_str)
            .unwrap_or_else(|| panic!("header has no `{section}.{key}`"));
        // A string value arrives quoted; a number or an array does not, and
        // trimming a quote that is not there is a no-op.
        value.trim_matches('"')
    }

    fn number(&self, section: &str, key: &str) -> f64 {
        self.get(section, key)
            .parse()
            .unwrap_or_else(|_| panic!("`{section}.{key}` is not a number"))
    }

    fn numbers(&self, section: &str, key: &str) -> Vec<f64> {
        let text = self.get(section, key);
        let inner = text
            .strip_prefix('[')
            .and_then(|rest| rest.strip_suffix(']'))
            .unwrap_or_else(|| panic!("`{section}.{key}` is not an array"));
        inner
            .split(',')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .map(|part| part.parse().expect("an array of numbers"))
            .collect()
    }

    fn optional(&self, section: &str, key: &str) -> Option<&str> {
        self.sections
            .get(section)
            .and_then(|values| values.get(key))
            .map(String::as_str)
    }

    /// A value with its quotes taken off, if the header has one.
    fn maybe(&self, section: &str, key: &str) -> Option<&str> {
        self.optional(section, key)
            .map(|value| value.trim_matches('"'))
    }
}

struct Film {
    header: Header,
    tables: BTreeMap<String, Vec<Vec<f64>>>,
    kind: Kind,
}

fn read(name: &str, bytes: &[u8]) -> Film {
    assert!(bytes.len() >= 16, "{name}: shorter than a header");
    let magic = &bytes[..8];
    assert!(
        magic == MAGIC || magic == PAPER_MAGIC,
        "{name}: neither a kalofilm nor a kalopaper"
    );
    let kind = if magic == PAPER_MAGIC {
        Kind::Paper
    } else {
        Kind::Film
    };
    let header_length = u32::from_le_bytes(bytes[12..16].try_into().expect("four bytes")) as usize;
    let header_text = std::str::from_utf8(&bytes[16..16 + header_length]).expect("utf-8 header");
    let header = parse_header(header_text, name);

    let mut tables = BTreeMap::new();
    let mut offset = 16 + header_length;
    let names = header.get("", "tables");
    let names = names
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(names);
    for name in names.split(',') {
        let name = name.trim().trim_matches('"').to_string();
        let rows = if name == "mask" || name == "cl_sensitivity" {
            1
        } else {
            3
        };
        let bytes_needed = rows * GRID_LEN * 8;
        let mut table = Vec::with_capacity(rows);
        for row in 0..rows {
            let mut values = Vec::with_capacity(GRID_LEN);
            for column in 0..GRID_LEN {
                let start = offset + (row * GRID_LEN + column) * 8;
                let value =
                    f64::from_le_bytes(bytes[start..start + 8].try_into().expect("eight bytes"));
                values.push(value);
            }
            table.push(values);
        }
        offset += bytes_needed;
        tables.insert(name, table);
    }
    Film {
        header,
        tables,
        kind,
    }
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Kind {
    Film,
    Paper,
}

fn parse_header(text: &str, name: &str) -> Header {
    let mut sections: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
    sections.insert(String::new(), BTreeMap::new());
    let mut current = String::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(name) = line
            .strip_prefix('[')
            .and_then(|rest| rest.strip_suffix(']'))
        {
            current = name.trim().to_string();
            sections.entry(current.clone()).or_default();
            continue;
        }
        let (key, value) = line
            .split_once('=')
            .unwrap_or_else(|| panic!("{name}: unparseable header line {line:?}"));
        sections
            .entry(current.clone())
            .or_default()
            .insert(key.trim().to_string(), value.trim().to_string());
    }
    Header { sections }
}

impl Film {
    fn id(&self) -> &str {
        self.header.get("", "id")
    }

    fn ident(&self) -> String {
        self.id()
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() {
                    c.to_ascii_uppercase()
                } else {
                    '_'
                }
            })
            .collect()
    }

    fn table(&self, name: &str) -> Option<&Vec<Vec<f64>>> {
        self.tables.get(name)
    }

    fn emit_tables(&self, code: &mut String, index: usize) {
        let ident = self.ident();
        if let Some(layers) = self.table("layers") {
            emit_matrix(code, &format!("LAYERS_{ident}"), layers);
        }
        if let Some(dyes) = self.table("dyes") {
            emit_matrix(code, &format!("DYES_{ident}"), dyes);
        }
        if let Some(mask) = self.table("mask") {
            emit_row(code, &format!("MASK_{ident}"), &mask[0]);
        }
        if let Some(cl) = self.table("cl_sensitivity") {
            emit_row(code, &format!("CL_{ident}"), &cl[0]);
        }
        let _ = index;
    }

    fn emit_stock(&self, code: &mut String, index: usize) {
        let ident = self.ident();
        let process = match self.header.get("", "process") {
            "negative" => "FilmProcess::Negative",
            "reversal" => "FilmProcess::Reversal",
            "monochrome" => "FilmProcess::Monochrome",
            other => panic!("unknown process {other:?}"),
        };
        let label = self.header.get("", "label");
        let short = escaped(self.header.maybe("", "short").unwrap_or(label));
        let note = escaped(self.header.get("provenance", "note"));
        let sigma = self.header.numbers("character", "sigma_um");
        let sigma = if sigma.iter().all(|value| *value == 0.0) {
            "None".to_string()
        } else {
            format!("Some([{:.5}, {:.5}, {:.5}])", sigma[0], sigma[1], sigma[2])
        };
        let base = self.header.numbers("character", "base_density");
        let grains = self.header.numbers("character", "grains_per_um2");
        let time = self.header.number("development", "reference_time_min");
        let temp = self.header.number("development", "reference_temp_c");

        writeln!(code, "    FilmStock {{").unwrap();
        writeln!(code, "        id: \"{}\",", self.id()).unwrap();
        writeln!(code, "        short: \"{short}\",").unwrap();
        writeln!(code, "        process: {process},").unwrap();
        writeln!(code, "        extra_cyan: None,").unwrap();
        match self.table("cl_sensitivity") {
            Some(_) => {
                writeln!(
                    code,
                    "        cl_layer: Some(crate::dye::InhibitorLayer {{ sensitivity: &CL_{ident} }}),"
                )
                .unwrap();
            }
            None => writeln!(code, "        cl_layer: None,").unwrap(),
        }
        writeln!(code, "        label: \"{label}\",").unwrap();
        writeln!(code, "        note: \"{note}\",").unwrap();
        writeln!(code, "        channels: [").unwrap();
        for channel in ["red", "green", "blue"] {
            let section = format!("curve.{channel}");
            let d_min = self.header.number(&section, "d_min");
            let d_max = self.header.number(&section, "d_max");
            let gamma = self.header.number(&section, "gamma");
            let log_e0 = self.header.number(&section, "log_e0");
            let shared: f64 = self
                .header
                .optional(&section, "transition")
                .map(|value| value.parse().expect("a number"))
                .unwrap_or(4.0);
            let toe: f64 = self
                .header
                .optional(&section, "toe_transition")
                .map_or(shared, |value| value.parse().expect("a number"));
            let shoulder: f64 = self
                .header
                .optional(&section, "shoulder_transition")
                .map_or(shared, |value| value.parse().expect("a number"));
            if (toe - shoulder).abs() < f64::EPSILON {
                writeln!(
                    code,
                    "            curve({d_min:.5}, {d_max:.5}, {gamma:.5}, {log_e0:.5}).with_transition({toe:.1}),"
                )
                .unwrap();
            } else {
                writeln!(
                    code,
                    "            curve({d_min:.5}, {d_max:.5}, {gamma:.5}, {log_e0:.5}).with_corners({toe:.1}, {shoulder:.1}),"
                )
                .unwrap();
            }
        }
        writeln!(code, "        ],").unwrap();
        writeln!(
            code,
            "        base_density: [{:.4}, {:.4}, {:.4}],",
            base[0], base[1], base[2]
        )
        .unwrap();
        writeln!(
            code,
            "        grains_per_um2: [{:.4}, {:.4}, {:.4}],",
            grains[0], grains[1], grains[2]
        )
        .unwrap();
        writeln!(code, "        layers: &LAYERS_{ident},").unwrap();
        writeln!(code, "        dyes: &DYES_{ident},").unwrap();
        match self.table("mask") {
            Some(_) => writeln!(code, "        mask: &MASK_{ident},").unwrap(),
            None => writeln!(code, "        mask: &NO_MASK,").unwrap(),
        }
        writeln!(code, "        sigma_um: {sigma},").unwrap();
        writeln!(code, "        reference_time_min: {time:.4},").unwrap();
        writeln!(code, "        reference_temp_c: {temp:.4},").unwrap();
        self.emit_provenance(code);
        self.emit_measured(code);
        writeln!(code, "    }},").unwrap();
        let _ = index;
    }

    /// The sheet behind a stock, as fields the binary can carry.
    fn emit_provenance(&self, code: &mut String) {
        let field = |key: &str| escaped(self.header.maybe("provenance", key).unwrap_or(""));
        writeln!(code, "        provenance: Provenance {{").unwrap();
        for name in ["publication", "page", "retrieved", "checksum"] {
            writeln!(code, "            {name}: \"{}\",", field(name)).unwrap();
        }
        writeln!(code, "        }},").unwrap();
    }

    /// What each field admits to: measured, borrowed, placeholder or none.
    ///
    /// The order is [`MEASURED_ORDER`]'s, and any field the order does not name
    /// follows in the file's own order — a stock that grew a field should not
    /// need two edits to be visible.
    fn emit_measured(&self, code: &mut String) {
        let Some(section) = self.header.sections.get("measured") else {
            writeln!(code, "        measured: &[],").unwrap();
            return;
        };
        let mut names: Vec<&str> = MEASURED_ORDER
            .iter()
            .copied()
            .filter(|name| section.contains_key(*name))
            .collect();
        for name in section.keys() {
            if !names.contains(&name.as_str()) {
                names.push(name.as_str());
            }
        }
        writeln!(code, "        measured: &[").unwrap();
        for name in names {
            let value = escaped(section[name].trim_matches('"'));
            writeln!(code, "            (\"{name}\", \"{value}\"),").unwrap();
        }
        writeln!(code, "        ],").unwrap();
    }

    fn emit_paper_tables(&self, code: &mut String, _index: usize) {
        let ident = self.ident();
        if let Some(dyes) = self.table("dyes") {
            emit_matrix(code, &format!("DYES_{ident}"), dyes);
        }
        if let Some(layers) = self.table("layers") {
            emit_matrix(code, &format!("LAYERS_{ident}"), layers);
        }
    }

    fn emit_paper(&self, code: &mut String, _index: usize) {
        let ident = self.ident();
        let label = self.header.get("", "label");
        let short = escaped(self.header.maybe("", "short").unwrap_or(label));
        let note = escaped(self.header.get("provenance", "note"));
        // A file that predates the key is a colour paper: that is the path the
        // model renders when nothing says otherwise, and it is what every paper
        // before POLYMAX II RC was.
        let emulsion = match self.header.maybe("", "emulsion").unwrap_or("colour") {
            "colour" => "PaperEmulsion::Colour",
            "silver" => "PaperEmulsion::Silver",
            other => panic!("unknown paper emulsion {other:?}"),
        };
        let d_min = self.header.number("curve", "d_min");
        let d_max = self.header.number("curve", "d_max");
        let gamma = self.header.number("curve", "gamma");
        let log_e0 = self.header.number("curve", "log_e0");
        let transition = self
            .header
            .optional("curve", "transition")
            .map_or(7.0, |value| value.parse().expect("a number"));
        let target = self.header.number("character", "target_mid_reflectance");
        writeln!(code, "    PaperStock {{").unwrap();
        writeln!(code, "        id: \"{}\",", self.id()).unwrap();
        writeln!(code, "        short: \"{short}\",").unwrap();
        writeln!(code, "        emulsion: {emulsion},").unwrap();
        writeln!(code, "        label: \"{label}\",").unwrap();
        writeln!(code, "        note: \"{note}\",").unwrap();
        writeln!(
            code,
            "        channel: curve({d_min:.5}, {d_max:.5}, {gamma:.5}, {log_e0:.5}).with_transition({transition:.1}),"
        )
        .unwrap();
        writeln!(code, "        target_mid_reflectance: {target:.2},").unwrap();
        writeln!(code, "        dyes: &DYES_{ident},").unwrap();
        writeln!(code, "        layers: &LAYERS_{ident},").unwrap();
        self.emit_provenance(code);
        self.emit_measured(code);
        writeln!(code, "    }},").unwrap();
    }
}

fn emit_matrix(code: &mut String, name: &str, rows: &[Vec<f64>]) {
    writeln!(code, "#[allow(clippy::approx_constant)]").unwrap();
    writeln!(code, "const {name}: [[f64; GRID_LEN]; 3] = [").unwrap();
    for row in rows {
        emit_row(code, "", row);
    }
    writeln!(code, "];\n").unwrap();
}

fn emit_row(code: &mut String, name: &str, row: &[f64]) {
    if name.is_empty() {
        code.push_str("    [");
    } else {
        writeln!(code, "#[allow(clippy::approx_constant)]").unwrap();
        write!(code, "const {name}: [f64; GRID_LEN] = [").unwrap();
    }
    for (index, value) in row.iter().enumerate() {
        if index > 0 {
            code.push_str(", ");
        }
        write!(code, "{value:.5}").unwrap();
    }
    if name.is_empty() {
        code.push_str("],\n");
    } else {
        code.push_str("];\n\n");
    }
}