Skip to main content

fprint_mindtct/
maps.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Block-map generation — a faithful port of stock NBIS `mindtct/src/lib/mindtct/maps.c`
6//! (`gen_image_maps` L126), plus the DFT analysis it drives (`dft.c`), the TRUE/FALSE map
7//! morphology it calls (`morph.c`), and the direction helpers it shares with `util.c`
8//! (`closest_dir_dist`) and `block.c` (`find_valid_block`, `set_margin_blocks`).
9//!
10//! [`gen_image_maps`] turns a padded, 6-bit fingerprint image into four `map_w × map_h` block maps:
11//!
12//! * **Direction Map** — the dominant integer ridge-flow direction of each block (`-1` = INVALID),
13//!   chosen by a DFT power analysis over `num_directions` rotated windows and then cleaned up by a
14//!   fixed sequence of neighbor-consistency passes.
15//! * **Low Contrast Map** — blocks whose 10th/90th-percentile intensity spread is too small.
16//! * **Low Ridge Flow Map** — blocks where the DFT analysis found no significant flow.
17//! * **High Curvature Map** — blocks near cores/deltas, flagged by vorticity or curvature.
18//!
19//! ## Bit-exactness
20//!
21//! Every float lives in `f64` and every rounding goes through [`sround`] / [`trunc_dbl_precision`]
22//! exactly where stock does — never elsewhere. Two libm-sensitive spots are kept **raw** as stock
23//! keeps them (see `docs/mindtct-algorithm.md` §Bit-exactness):
24//!
25//! * [`dft_power`] multiplies integer row sums by the *un-truncated* DFT-wave samples
26//!   ([`init_dftwaves`](crate::init::init_dftwaves) stores them raw) and accumulates in `f64`.
27//! * [`average_8nbr_dir`] runs `atan2`/`fmod` on raw `f64` — the cos/sin it accumulates come from the
28//!   *quantized* [`init_dir2rad`](crate::init::init_dir2rad) table, but the angle math itself is not
29//!   quantized; only the final `avr` (direction) and the `dir_strength` are truncated, as in stock.
30//!
31//! The scan orders — block raster order, the 8-neighbor visiting order, and the concentric-square
32//! walk of [`remove_incon_dirs`] — are reproduced verbatim, because the stable bubble sorts and the
33//! removal side effects make the result order-dependent.
34
35use crate::block::{block_offsets, low_contrast_block};
36use crate::consts::{DIR_STRENGTH_MIN, TRUNC_SCALE};
37use crate::init::{DftWave, DftWaves, Dir2Rad, RotGrids};
38use crate::num::{bubble_sort_double_dec_2, sround, trunc_dbl_precision};
39use crate::params::LfsParms;
40
41/// `INVALID_DIR` (`lfs.h` L320) — the sentinel for a block with no assigned direction.
42const INVALID_DIR: i32 = -1;
43
44/// `TRUE` / `FALSE` (`lfs.h`) as the `int` map flags stock stores.
45const TRUE: i32 = 1;
46const FALSE: i32 = 0;
47
48/// `MIN_POWER_SUM` (`lfs.h` L419) — the floor placed on a direction's total DFT power before it is
49/// used as the denominator of the normalized power, so [`get_max_norm`] never divides by zero.
50/// Not in `consts` (it is neither an `lfsparms` field nor read outside the DFT stage), so it is a
51/// local `const` at the stock value.
52const MIN_POWER_SUM: f64 = 10.0;
53
54/// The four block maps produced by [`gen_image_maps`], with their shared block-grid dimensions.
55///
56/// Mirrors the stock C out-parameters (`odmap`/`olcmap`/`olfmap`/`ohcmap`/`omw`/`omh`). Every map is
57/// `map_w * map_h` long in row-major block order.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub(crate) struct ImageMaps {
60    /// Per-block ridge-flow direction: `-1` (INVALID) or a direction index in `0..num_directions`.
61    pub(crate) direction_map: Vec<i32>,
62    /// Per-block low-contrast flag (`1`/`0`).
63    pub(crate) low_contrast_map: Vec<i32>,
64    /// Per-block low-ridge-flow flag (`1`/`0`).
65    pub(crate) low_flow_map: Vec<i32>,
66    /// Per-block high-curvature flag (`1`/`0`).
67    pub(crate) high_curve_map: Vec<i32>,
68    /// Block-grid width (blocks).
69    pub(crate) map_w: i32,
70    /// Block-grid height (blocks).
71    pub(crate) map_h: i32,
72}
73
74// =====================================================================================================
75// DFT analysis (dft.c)
76// =====================================================================================================
77
78/// `sum_rot_block_rows` (dft.c L159) — accumulate a vector of pixel row sums by sampling the block at
79/// `blkoffset` through one direction's rotated grid offsets.
80///
81/// For each of `blocksize` rows the sum runs across `blocksize` columns, reading
82/// `pdata[blkoffset + grid_offsets[gi]]` (the offset is signed and already scaled by the padded
83/// width). Row sums are integer sums of 6-bit pixels, matching stock's `int` accumulation.
84fn sum_rot_block_rows(
85    rowsums: &mut [i32],
86    pdata: &[u8],
87    blkoffset: i32,
88    grid_offsets: &[i32],
89    blocksize: i32,
90) {
91    let mut gi = 0usize;
92    for iy in 0..blocksize {
93        // Sums accumulate along the rotated rows of the grid, so start each row at 0.
94        rowsums[iy as usize] = 0;
95        for _ix in 0..blocksize {
96            let idx = (blkoffset + grid_offsets[gi]) as usize;
97            rowsums[iy as usize] += i32::from(pdata[idx]);
98            gi += 1;
99        }
100    }
101}
102
103/// `dft_power` (dft.c L198) — the DFT power of one wave form applied to a row-sum vector.
104///
105/// Accumulates `cospart`/`sinpart` as `f64` sums of `rowsums[i] * wave.cos[i]` (resp. `sin`) — the
106/// wave samples are the *raw, un-truncated* `f64` from [`init_dftwaves`](crate::init::init_dftwaves),
107/// kept verbatim. Power is `cospart² + sinpart²`.
108fn dft_power(rowsums: &[i32], wave: &DftWave, wavelen: i32) -> f64 {
109    let mut cospart = 0.0_f64;
110    let mut sinpart = 0.0_f64;
111    for ((&r, &c), &s) in rowsums
112        .iter()
113        .zip(wave.cos.iter())
114        .zip(wave.sin.iter())
115        .take(wavelen as usize)
116    {
117        // Multiply each rotated row sum by its corresponding cos/sin point in the DFT wave.
118        cospart += f64::from(r) * c;
119        sinpart += f64::from(r) * s;
120    }
121    (cospart * cospart) + (sinpart * sinpart)
122}
123
124/// `dft_dir_powers` (dft.c L102) — the full `nwaves × ngrids` power matrix for a block.
125///
126/// For each direction, [`sum_rot_block_rows`] samples the block through that grid, then every DFT
127/// wave is applied to the row sums. Returns `powers[w][dir]`. (Stock asserts the grid is square; the
128/// V2 geometry guarantees it, so the padded image always covers every sample and no bounds check is
129/// needed — the offsets are precomputed against the padded width.)
130fn dft_dir_powers(
131    pdata: &[u8],
132    blkoffset: i32,
133    dftwaves: &DftWaves,
134    dftgrids: &RotGrids,
135) -> Vec<Vec<f64>> {
136    let nwaves = dftwaves.nwaves as usize;
137    let ngrids = dftgrids.ngrids as usize;
138    let mut powers = vec![vec![0.0_f64; ngrids]; nwaves];
139    let mut rowsums = vec![0i32; dftgrids.grid_w as usize];
140
141    for (dir, grid) in dftgrids.grids.iter().enumerate().take(ngrids) {
142        sum_rot_block_rows(&mut rowsums, pdata, blkoffset, grid, dftgrids.grid_w);
143        for (w, wave) in dftwaves.waves.iter().enumerate().take(nwaves) {
144            powers[w][dir] = dft_power(&rowsums, wave, dftwaves.wavelen);
145        }
146    }
147    powers
148}
149
150/// `get_max_norm` (dft.c L297) — max power, its direction, and the normalized power for one wave.
151///
152/// The normalized power is `powmax / (max(powsum, MIN_POWER_SUM) / ndirs)`. The max scan keeps the
153/// *first* direction on ties (strict `>`), exactly as stock.
154fn get_max_norm(power_vector: &[f64], ndirs: i32) -> (f64, i32, f64) {
155    let mut max_v = power_vector[0];
156    let mut max_i = 0i32;
157    let mut powsum = power_vector[0];
158    for dir in 1..ndirs {
159        powsum += power_vector[dir as usize];
160        if power_vector[dir as usize] > max_v {
161            max_v = power_vector[dir as usize];
162            max_i = dir;
163        }
164    }
165    // Non-zero minimum on the denominator avoids possible division by zero.
166    let powmean = powsum.max(MIN_POWER_SUM) / f64::from(ndirs);
167    (max_v, max_i, max_v / powmean)
168}
169
170/// `sort_dft_waves` (dft.c L350) — rank wave indices by normalized squared max power, descending.
171///
172/// `pownorms2[i] = powmaxs[i] * pownorms[i]`; the ranking uses the *stable* decreasing bubble sort so
173/// equal keys keep their input order (equal keys are never swapped). Returns the ranked index list.
174fn sort_dft_waves(powmaxs: &[f64], pownorms: &[f64]) -> Vec<i32> {
175    let nstats = powmaxs.len();
176    let mut wis: Vec<i32> = (0..nstats as i32).collect();
177    let mut pownorms2: Vec<f64> = (0..nstats).map(|i| powmaxs[i] * pownorms[i]).collect();
178    bubble_sort_double_dec_2(&mut pownorms2, &mut wis);
179    wis
180}
181
182/// `dft_power_stats` (dft.c L257) — derive `(wis, powmaxs, powmax_dirs, pownorms)` for waves `fw..tw`.
183///
184/// Statistics are computed for every wave except the lowest frequency (the caller passes `fw = 1`),
185/// so the arrays are `tw - fw` long and index `i` corresponds to original wave `fw + i`.
186fn dft_power_stats(
187    powers: &[Vec<f64>],
188    fw: i32,
189    tw: i32,
190    ndirs: i32,
191) -> (Vec<i32>, Vec<f64>, Vec<i32>, Vec<f64>) {
192    let nstats = (tw - fw) as usize;
193    let mut powmaxs = vec![0.0_f64; nstats];
194    let mut powmax_dirs = vec![0i32; nstats];
195    let mut pownorms = vec![0.0_f64; nstats];
196
197    for (i, w) in (fw..tw).enumerate() {
198        let (pm, pd, pnorm) = get_max_norm(&powers[w as usize], ndirs);
199        powmaxs[i] = pm;
200        powmax_dirs[i] = pd;
201        pownorms[i] = pnorm;
202    }
203
204    let wis = sort_dft_waves(&powmaxs, &pownorms);
205    (wis, powmaxs, powmax_dirs, pownorms)
206}
207
208// =====================================================================================================
209// Direction selection (maps.c)
210// =====================================================================================================
211
212/// `primary_dir_test` (maps.c L1188) — the primary criteria for choosing a block direction.
213///
214/// Walks the ranked wave statistics (via `wis`) and returns the first direction whose max power,
215/// normalized power, and low-frequency power all pass their thresholds; else [`INVALID_DIR`].
216fn primary_dir_test(
217    powers: &[Vec<f64>],
218    wis: &[i32],
219    powmaxs: &[f64],
220    powmax_dirs: &[i32],
221    pownorms: &[f64],
222    lfsparms: &LfsParms,
223) -> i32 {
224    for &wi in wis {
225        let wi = wi as usize;
226        // 1. Max power large enough, 2. normalized max power large enough, and 3. the lowest-frequency
227        // wave's power at that direction is not too big.
228        if powmaxs[wi] > lfsparms.powmax_min
229            && pownorms[wi] > lfsparms.pownorm_min
230            && powers[0][powmax_dirs[wi] as usize] <= lfsparms.powmax_max
231        {
232            return powmax_dirs[wi];
233        }
234    }
235    INVALID_DIR
236}
237
238/// `secondary_fork_test` (maps.c L1272) — the fork criteria applied when the primary test fails.
239///
240/// Uses only the strongest wave (`wis[0]`). After a relaxed power/normalized-power/low-frequency
241/// gate, it looks `fork_interval` directions to each side (modulo `num_directions`) and requires
242/// **exactly one** of the two fork directions to exceed `fork_pct_powmax * powmax` — the XOR encoded
243/// by the stock's paired `<=`/`>` conditions. Returns the strongest direction, else [`INVALID_DIR`].
244fn secondary_fork_test(
245    powers: &[Vec<f64>],
246    wis: &[i32],
247    powmaxs: &[f64],
248    powmax_dirs: &[i32],
249    pownorms: &[f64],
250    lfsparms: &LfsParms,
251) -> i32 {
252    // Relax the normalized power threshold under fork conditions.
253    let fork_pownorm_min = lfsparms.fork_pct_pownorm * lfsparms.pownorm_min;
254    let w0 = wis[0] as usize;
255
256    if powmaxs[w0] > lfsparms.powmax_min
257        && pownorms[w0] >= fork_pownorm_min
258        && powers[0][powmax_dirs[w0] as usize] <= lfsparms.powmax_max
259    {
260        let dir = powmax_dirs[w0];
261        // Add / subtract FORK_INTERVALs modulo NDIRS (the `+ num_directions` keeps ldir non-negative).
262        let rdir = (dir + lfsparms.fork_interval) % lfsparms.num_directions;
263        let ldir =
264            (dir + lfsparms.num_directions - lfsparms.fork_interval) % lfsparms.num_directions;
265
266        // Forked-angle threshold is a fraction of the max directional power.
267        let fork_pow_thresh = powmaxs[w0] * lfsparms.fork_pct_powmax;
268
269        // wis indices are on [0..nstats); +1 maps back into the original power vectors.
270        let lp = powers[w0 + 1][ldir as usize];
271        let rp = powers[w0 + 1][rdir as usize];
272
273        // Exactly one of the two fork angles may exceed the relative power threshold.
274        if ((lp <= fork_pow_thresh) || (rp <= fork_pow_thresh))
275            && ((lp > fork_pow_thresh) || (rp > fork_pow_thresh))
276        {
277            return dir;
278        }
279    }
280    INVALID_DIR
281}
282
283// =====================================================================================================
284// Initial map generation (maps.c gen_initial_maps L247)
285// =====================================================================================================
286
287/// The three maps [`gen_initial_maps`] returns: `(direction_map, low_contrast_map, low_flow_map)`.
288type InitialMaps = (Vec<i32>, Vec<i32>, Vec<i32>);
289
290/// `gen_initial_maps` (maps.c L247) — the initial Direction, Low Contrast, and Low Ridge Flow maps.
291///
292/// For every block (raster order): shift the block offset to its surrounding window origin, clamp
293/// that origin so the low-contrast window never reads padded pixels, and test contrast. Low-contrast
294/// blocks flag the Low Contrast Map (their direction stays INVALID). Otherwise the DFT analysis runs
295/// and the primary then secondary tests pick a direction; if both fail the Low Ridge Flow Map is
296/// flagged. The Direction Map is initialized to [`INVALID_DIR`].
297fn gen_initial_maps(
298    blkoffs: &[i32],
299    mdims: (i32, i32),
300    pdata: &[u8],
301    dims: (i32, i32),
302    dftwaves: &DftWaves,
303    dftgrids: &RotGrids,
304    lfsparms: &LfsParms,
305) -> Result<InitialMaps, i32> {
306    let (mw, mh) = mdims;
307    let (pw, ph) = dims;
308    let bsize = (mw * mh) as usize;
309
310    let mut direction_map = vec![INVALID_DIR; bsize];
311    let mut low_contrast_map = vec![FALSE; bsize];
312    let mut low_flow_map = vec![FALSE; bsize];
313
314    // Window origin limits that avoid analyzing the padded borders for low contrast.
315    let xminlimit = dftgrids.pad;
316    let yminlimit = dftgrids.pad;
317    let xmaxlimit = pw - dftgrids.pad - lfsparms.windowsize - 1;
318    let ymaxlimit = ph - dftgrids.pad - lfsparms.windowsize - 1;
319
320    // A window origin must exist between the min and max limits. For an image with a dimension under
321    // `windowsize + 1` the max limit falls below the min — there is nowhere to place the
322    // `windowsize × windowsize` low-contrast window clear of the padding — and clamping to an inverted
323    // range would drive the origin negative, indexing a wrapped offset. Surface it as the size error
324    // the front-end already answers with an empty minutiae list, exactly as `block_offsets` rejects an
325    // image smaller than a single block.
326    if xmaxlimit < xminlimit || ymaxlimit < yminlimit {
327        return Err(-82);
328    }
329
330    for bi in 0..bsize {
331        // Adjust block offset from block origin to surrounding window origin.
332        let dft_offset = blkoffs[bi] - (lfsparms.windowoffset * pw) - lfsparms.windowoffset;
333
334        // Pixel coords of the window origin (dft_offset is always >= 0 for V2: pad > windowoffset).
335        let mut win_x = dft_offset % pw;
336        let mut win_y = dft_offset / pw;
337
338        // Keep the low-contrast window off the padded borders.
339        win_x = win_x.max(xminlimit).min(xmaxlimit);
340        win_y = win_y.max(yminlimit).min(ymaxlimit);
341        let low_contrast_offset = (win_y * pw) + win_x;
342
343        // If block is low contrast ...
344        if low_contrast_block(
345            low_contrast_offset,
346            lfsparms.windowsize,
347            pdata,
348            pw,
349            ph,
350            lfsparms,
351        )? {
352            low_contrast_map[bi] = TRUE;
353            // Direction Map's block is already INVALID.
354        } else {
355            // Sufficient contrast for DFT processing.
356            let powers = dft_dir_powers(pdata, low_contrast_offset, dftwaves, dftgrids);
357
358            // Power statistics, skipping the first applied DFT wave (fw = 1).
359            let (wis, powmaxs, powmax_dirs, pownorms) =
360                dft_power_stats(&powers, 1, dftwaves.nwaves, dftgrids.ngrids);
361
362            // Primary direction test.
363            let mut blkdir =
364                primary_dir_test(&powers, &wis, &powmaxs, &powmax_dirs, &pownorms, lfsparms);
365
366            if blkdir != INVALID_DIR {
367                direction_map[bi] = blkdir;
368            } else {
369                // Secondary (fork) direction test.
370                blkdir =
371                    secondary_fork_test(&powers, &wis, &powmaxs, &powmax_dirs, &pownorms, lfsparms);
372                if blkdir != INVALID_DIR {
373                    direction_map[bi] = blkdir;
374                } else {
375                    // Both tests failed: flag LOW RIDGE FLOW.
376                    low_flow_map[bi] = TRUE;
377                }
378            }
379        }
380    }
381
382    Ok((direction_map, low_contrast_map, low_flow_map))
383}
384
385// =====================================================================================================
386// TRUE/FALSE map morphology (morph.c)
387// =====================================================================================================
388
389/// `get_south8_2` (morph.c L170) — the pixel one row below, or `failcode` off the bottom edge.
390fn get_south8_2(img: &[u8], idx: usize, row: i32, iw: i32, ih: i32, failcode: u8) -> u8 {
391    if row >= ih - 1 {
392        failcode
393    } else {
394        img[idx + iw as usize]
395    }
396}
397
398/// `get_north8_2` (morph.c L194) — the pixel one row above, or `failcode` off the top edge.
399fn get_north8_2(img: &[u8], idx: usize, row: i32, iw: i32, failcode: u8) -> u8 {
400    if row < 1 {
401        failcode
402    } else {
403        img[idx - iw as usize]
404    }
405}
406
407/// `get_east8_2` (morph.c L218) — the pixel one column right, or `failcode` off the right edge.
408fn get_east8_2(img: &[u8], idx: usize, col: i32, iw: i32, failcode: u8) -> u8 {
409    if col >= iw - 1 {
410        failcode
411    } else {
412        img[idx + 1]
413    }
414}
415
416/// `get_west8_2` (morph.c L241) — the pixel one column left, or `failcode` off the left edge.
417fn get_west8_2(img: &[u8], idx: usize, col: i32, failcode: u8) -> u8 {
418    if col < 1 {
419        failcode
420    } else {
421        img[idx - 1]
422    }
423}
424
425/// `dilate_charimage_2` (morph.c L128) — set each false pixel true if any 4-neighbor is true.
426///
427/// Off-image neighbors use `failcode = 0` (treated as false), so dilation does not spill past the
428/// border. `out` starts as a copy of `inp` (already-true pixels are left alone).
429fn dilate_charimage_2(inp: &[u8], out: &mut [u8], iw: i32, ih: i32) {
430    out.copy_from_slice(inp);
431    let mut idx = 0usize;
432    for row in 0..ih {
433        for col in 0..iw {
434            if inp[idx] == 0
435                && (get_west8_2(inp, idx, col, 0) != 0
436                    || get_east8_2(inp, idx, col, iw, 0) != 0
437                    || get_north8_2(inp, idx, row, iw, 0) != 0
438                    || get_south8_2(inp, idx, row, iw, ih, 0) != 0)
439            {
440                out[idx] = 1;
441            }
442            idx += 1;
443        }
444    }
445}
446
447/// `erode_charimage_2` (morph.c L88) — set each true pixel false if any 4-neighbor is false.
448///
449/// Off-image neighbors use `failcode = 1` (treated as true), so border pixels are not eroded
450/// indiscriminately. `out` starts as a copy of `inp`.
451fn erode_charimage_2(inp: &[u8], out: &mut [u8], iw: i32, ih: i32) {
452    out.copy_from_slice(inp);
453    let mut idx = 0usize;
454    for row in 0..ih {
455        for col in 0..iw {
456            if inp[idx] != 0
457                && !(get_west8_2(inp, idx, col, 1) != 0
458                    && get_east8_2(inp, idx, col, iw, 1) != 0
459                    && get_north8_2(inp, idx, row, iw, 1) != 0
460                    && get_south8_2(inp, idx, row, iw, ih, 1) != 0)
461            {
462                out[idx] = 0;
463            }
464            idx += 1;
465        }
466    }
467}
468
469/// `morph_TF_map` (maps.c L661) — dilate twice then erode twice to fill voids in a TRUE/FALSE map.
470///
471/// The map's `1`/`0` `int` flags are copied into a byte image, run through
472/// `dilate → dilate → erode → erode` (bouncing between two buffers, exactly as stock), and copied
473/// back. This "closing" fills small holes in the Low Ridge Flow map.
474fn morph_tf_map(tfmap: &mut [i32], mw: i32, mh: i32) {
475    let n = (mw * mh) as usize;
476    let mut cimage: Vec<u8> = tfmap.iter().map(|&v| v as u8).collect();
477    let mut mimage: Vec<u8> = vec![0u8; n];
478
479    dilate_charimage_2(&cimage, &mut mimage, mw, mh); // c -> m
480    dilate_charimage_2(&mimage, &mut cimage, mw, mh); // m -> c
481    erode_charimage_2(&cimage, &mut mimage, mw, mh); //  c -> m
482    erode_charimage_2(&mimage, &mut cimage, mw, mh); //  m -> c
483
484    for (dst, &src) in tfmap.iter_mut().zip(cimage.iter()) {
485        *dst = i32::from(src);
486    }
487}
488
489// =====================================================================================================
490// Neighbor direction helpers (maps.c / util.c)
491// =====================================================================================================
492
493/// `average_8nbr_dir` (maps.c L1838) — the average of a block's 8 valid neighbor directions.
494///
495/// Returns `(avrdir, dir_strength, nvalid)`. Cos/sin of each valid neighbor's direction are summed
496/// (from the quantized [`Dir2Rad`] table) in the fixed order NW, N, NE, E, SE, S, SW, W, averaged,
497/// and the strength `cos² + sin²` is [`trunc_dbl_precision`]-quantized. If there are no valid
498/// neighbors, or the strength is below [`DIR_STRENGTH_MIN`], the direction is [`INVALID_DIR`] and the
499/// strength `0`. Otherwise `atan2`/`fmod` (raw `f64`) map the angle to `[0, 2π)`, `avr = θ/pi_factor`
500/// is truncated and [`sround`]ed, and taken modulo `ndirs`.
501fn average_8nbr_dir(
502    imap: &[i32],
503    mx: i32,
504    my: i32,
505    mw: i32,
506    mh: i32,
507    dir2rad: &Dir2Rad,
508) -> (i32, f64, i32) {
509    let e = mx + 1;
510    let w = mx - 1;
511    let n = my - 1;
512    let s = my + 1;
513
514    let mut nvalid = 0i32;
515    let mut cospart = 0.0_f64;
516    let mut sinpart = 0.0_f64;
517
518    // Accumulate a neighbor's direction if it is in bounds and valid.
519    let accum = |bx: i32, by: i32, nvalid: &mut i32, cospart: &mut f64, sinpart: &mut f64| {
520        let v = imap[(by * mw + bx) as usize];
521        if v != INVALID_DIR {
522            *cospart += dir2rad.cos[v as usize];
523            *sinpart += dir2rad.sin[v as usize];
524            *nvalid += 1;
525        }
526    };
527
528    // 1. NW  2. N  3. NE  4. E  5. SE  6. S  7. SW  8. W  (stock visiting order)
529    if (w >= 0) && (n >= 0) {
530        accum(w, n, &mut nvalid, &mut cospart, &mut sinpart);
531    }
532    if n >= 0 {
533        accum(mx, n, &mut nvalid, &mut cospart, &mut sinpart);
534    }
535    if (e < mw) && (n >= 0) {
536        accum(e, n, &mut nvalid, &mut cospart, &mut sinpart);
537    }
538    if e < mw {
539        accum(e, my, &mut nvalid, &mut cospart, &mut sinpart);
540    }
541    if (e < mw) && (s < mh) {
542        accum(e, s, &mut nvalid, &mut cospart, &mut sinpart);
543    }
544    if s < mh {
545        accum(mx, s, &mut nvalid, &mut cospart, &mut sinpart);
546    }
547    if (w >= 0) && (s < mh) {
548        accum(w, s, &mut nvalid, &mut cospart, &mut sinpart);
549    }
550    if w >= 0 {
551        accum(w, my, &mut nvalid, &mut cospart, &mut sinpart);
552    }
553
554    // No valid neighbors -> INVALID.
555    if nvalid == 0 {
556        return (INVALID_DIR, 0.0, 0);
557    }
558
559    // Average the accumulated cos/sin components.
560    cospart /= f64::from(nvalid);
561    sinpart /= f64::from(nvalid);
562
563    // Directional strength as squared hypotenuse, quantized for cross-architecture consistency.
564    let dir_strength = trunc_dbl_precision((cospart * cospart) + (sinpart * sinpart), TRUNC_SCALE);
565
566    // Strength too low -> INVALID.
567    if dir_strength < DIR_STRENGTH_MIN {
568        return (INVALID_DIR, 0.0, nvalid);
569    }
570
571    // Angle from arctan of the average components (raw f64 — libm-sensitive, kept as stock).
572    let mut theta = sinpart.atan2(cospart);
573    let pi2 = 2.0 * std::f64::consts::PI;
574    theta += pi2;
575    theta %= pi2;
576
577    // pi_factor sets the trig period to ndirs units; theta/pi_factor lands on [0..ndirs].
578    let pi_factor = pi2 / f64::from(dir2rad.ndirs);
579    let avr = trunc_dbl_precision(theta / pi_factor, TRUNC_SCALE);
580    let mut avrdir = sround(avr);
581
582    // Map values >= ndirs back onto [0..ndirs).
583    avrdir %= dir2rad.ndirs;
584    (avrdir, dir_strength, nvalid)
585}
586
587/// `num_valid_8nbrs` (maps.c L2044) — count the block's 8-neighbors that hold a valid direction.
588fn num_valid_8nbrs(imap: &[i32], mx: i32, my: i32, mw: i32, mh: i32) -> i32 {
589    let e = mx + 1;
590    let w = mx - 1;
591    let n = my - 1;
592    let s = my + 1;
593    let mut nvalid = 0i32;
594
595    let val = |bx: i32, by: i32| imap[(by * mw + bx) as usize];
596
597    if (w >= 0) && (n >= 0) && (val(w, n) >= 0) {
598        nvalid += 1;
599    }
600    if (n >= 0) && (val(mx, n) >= 0) {
601        nvalid += 1;
602    }
603    if (n >= 0) && (e < mw) && (val(e, n) >= 0) {
604        nvalid += 1;
605    }
606    if (e < mw) && (val(e, my) >= 0) {
607        nvalid += 1;
608    }
609    if (e < mw) && (s < mh) && (val(e, s) >= 0) {
610        nvalid += 1;
611    }
612    if (s < mh) && (val(mx, s) >= 0) {
613        nvalid += 1;
614    }
615    if (w >= 0) && (s < mh) && (val(w, s) >= 0) {
616        nvalid += 1;
617    }
618    if (w >= 0) && (val(w, my) >= 0) {
619        nvalid += 1;
620    }
621    nvalid
622}
623
624/// `closest_dir_dist` (util.c L602) — the shortest wrap-aware distance between two directions.
625///
626/// Returns `min(|dir2-dir1|, ndirs - |dir2-dir1|)`, or [`INVALID_DIR`] if either direction is
627/// invalid.
628fn closest_dir_dist(dir1: i32, dir2: i32, ndirs: i32) -> i32 {
629    if (dir1 >= 0) && (dir2 >= 0) {
630        let d1 = (dir2 - dir1).abs();
631        let d2 = ndirs - d1;
632        d1.min(d2)
633    } else {
634        INVALID_DIR
635    }
636}
637
638// =====================================================================================================
639// Inconsistent-direction removal (maps.c)
640// =====================================================================================================
641
642/// One concentric square walked by [`remove_incon_dirs`], by its four edge coordinates.
643#[derive(Clone, Copy)]
644struct ConcentricBox {
645    l: i32,
646    t: i32,
647    r: i32,
648    b: i32,
649}
650
651/// `remove_dir` (maps.c L1754) — whether a block's direction is too weak/inconsistent to keep.
652///
653/// Returns non-zero to remove: `1` when fewer than `rmv_valid_nbr_min` valid neighbors exist, `2`
654/// when the average neighbor direction is strong enough (`>= dir_strength_min`) yet the wrap-aware
655/// distance between it and the block's direction exceeds `dir_distance_max`.
656fn remove_dir(
657    imap: &[i32],
658    mx: i32,
659    my: i32,
660    mw: i32,
661    mh: i32,
662    dir2rad: &Dir2Rad,
663    lfsparms: &LfsParms,
664) -> i32 {
665    let (avrdir, dir_strength, nvalid) = average_8nbr_dir(imap, mx, my, mw, mh, dir2rad);
666
667    // Valid-neighbor test.
668    if nvalid < lfsparms.rmv_valid_nbr_min {
669        return 1;
670    }
671
672    // Only trust the average direction if it is strong enough.
673    if dir_strength >= lfsparms.dir_strength_min {
674        // Minimum absolute distance, accounting for wrap from 0 to NDIRS.
675        let cur = imap[(my * mw + mx) as usize];
676        let mut dist = (avrdir - cur).abs();
677        dist = dist.min(dir2rad.ndirs - dist);
678        if dist > lfsparms.dir_distance_max {
679            return 2;
680        }
681    }
682    0
683}
684
685/// One point of an edge walk: if it holds a valid direction that [`remove_dir`] rejects, set it
686/// INVALID and count it. Shared by the four edge routines to keep the removal side effect identical.
687fn test_and_remove(
688    imap: &mut [i32],
689    bx: i32,
690    by: i32,
691    mw: i32,
692    mh: i32,
693    dir2rad: &Dir2Rad,
694    lfsparms: &LfsParms,
695) -> i32 {
696    let idx = (by * mw + bx) as usize;
697    if imap[idx] != INVALID_DIR && remove_dir(imap, bx, by, mw, mh, dir2rad, lfsparms) != 0 {
698        imap[idx] = INVALID_DIR;
699        1
700    } else {
701        0
702    }
703}
704
705/// `test_top_edge` (maps.c L1514) — walk the box's top edge left→right, removing weak directions.
706fn test_top_edge(
707    bx: &ConcentricBox,
708    imap: &mut [i32],
709    mw: i32,
710    mh: i32,
711    dir2rad: &Dir2Rad,
712    lfsparms: &LfsParms,
713) -> i32 {
714    let sx = bx.l.max(0);
715    let ex = (bx.r - 1).min(mw - 1);
716    let mut nremoved = 0;
717    for cx in sx..=ex {
718        nremoved += test_and_remove(imap, cx, bx.t, mw, mh, dir2rad, lfsparms);
719    }
720    nremoved
721}
722
723/// `test_right_edge` (maps.c L1575) — walk the box's right edge top→bottom, removing weak directions.
724fn test_right_edge(
725    bx: &ConcentricBox,
726    imap: &mut [i32],
727    mw: i32,
728    mh: i32,
729    dir2rad: &Dir2Rad,
730    lfsparms: &LfsParms,
731) -> i32 {
732    let sy = bx.t.max(0);
733    let ey = (bx.b - 1).min(mh - 1);
734    let mut nremoved = 0;
735    for cy in sy..=ey {
736        nremoved += test_and_remove(imap, bx.r, cy, mw, mh, dir2rad, lfsparms);
737    }
738    nremoved
739}
740
741/// `test_bottom_edge` (maps.c L1635) — walk the box's bottom edge right→left, removing weak directions.
742fn test_bottom_edge(
743    bx: &ConcentricBox,
744    imap: &mut [i32],
745    mw: i32,
746    mh: i32,
747    dir2rad: &Dir2Rad,
748    lfsparms: &LfsParms,
749) -> i32 {
750    let sx = bx.r.min(mw - 1);
751    let ex = (bx.l - 1).max(0);
752    let mut nremoved = 0;
753    // Stock walks from sx down to ex inclusive (iptr--).
754    let mut cx = sx;
755    while cx >= ex {
756        nremoved += test_and_remove(imap, cx, bx.b, mw, mh, dir2rad, lfsparms);
757        cx -= 1;
758    }
759    nremoved
760}
761
762/// `test_left_edge` (maps.c L1696) — walk the box's left edge bottom→top, removing weak directions.
763fn test_left_edge(
764    bx: &ConcentricBox,
765    imap: &mut [i32],
766    mw: i32,
767    mh: i32,
768    dir2rad: &Dir2Rad,
769    lfsparms: &LfsParms,
770) -> i32 {
771    let sy = bx.b.min(mh - 1);
772    let ey = (bx.t - 1).max(0);
773    let mut nremoved = 0;
774    // Stock walks from sy up to ey inclusive (iptr -= mw).
775    let mut cy = sy;
776    while cy >= ey {
777        nremoved += test_and_remove(imap, bx.l, cy, mw, mh, dir2rad, lfsparms);
778        cy -= 1;
779    }
780    nremoved
781}
782
783/// `remove_incon_dirs` (maps.c L1409) — prune weak/inconsistent directions, center-outward.
784///
785/// Each pass starts at the map center, then grows concentric squares (top, right, bottom, left
786/// edges, each guarded by its boundary) removing directions [`remove_dir`] rejects. The removals are
787/// side effects visible to later tests in the same pass. Passes repeat until one completes with no
788/// removals (the stock `do { ... } while (nremoved)`).
789fn remove_incon_dirs(imap: &mut [i32], mw: i32, mh: i32, dir2rad: &Dir2Rad, lfsparms: &LfsParms) {
790    let cx = mw >> 1;
791    let cy = mh >> 1;
792
793    loop {
794        let mut nremoved = 0;
795
796        // Start at center.
797        nremoved += test_and_remove(imap, cx, cy, mw, mh, dir2rad, lfsparms);
798
799        // Initialize the concentric box just outside the center.
800        let mut bx = ConcentricBox {
801            l: cx - 1,
802            t: cy - 1,
803            r: cx + 1,
804            b: cy + 1,
805        };
806
807        // Grow boxes until ALL edges exceed the map bounds.
808        while (bx.l >= 0) || (bx.r < mw) || (bx.t >= 0) || (bx.b < mh) {
809            if bx.t >= 0 {
810                nremoved += test_top_edge(&bx, imap, mw, mh, dir2rad, lfsparms);
811            }
812            if bx.r < mw {
813                nremoved += test_right_edge(&bx, imap, mw, mh, dir2rad, lfsparms);
814            }
815            if bx.b < mh {
816                nremoved += test_bottom_edge(&bx, imap, mw, mh, dir2rad, lfsparms);
817            }
818            if bx.l >= 0 {
819                nremoved += test_left_edge(&bx, imap, mw, mh, dir2rad, lfsparms);
820            }
821            bx.l -= 1;
822            bx.t -= 1;
823            bx.r += 1;
824            bx.b += 1;
825        }
826
827        if nremoved == 0 {
828            break;
829        }
830    }
831}
832
833// =====================================================================================================
834// Smoothing and interpolation (maps.c)
835// =====================================================================================================
836
837/// `smooth_direction_map` (maps.c L783) — replace directions with their neighbor average where strong.
838///
839/// For each non-low-contrast block whose neighbor average is strong enough
840/// (`>= dir_strength_min`): a *valid* direction is overwritten when there are at least
841/// `rmv_valid_nbr_min` valid neighbors; an *invalid* one is filled when there are at least
842/// `smth_valid_nbr_min`. Runs in place in raster order (each write is visible to later blocks).
843fn smooth_direction_map(
844    direction_map: &mut [i32],
845    low_contrast_map: &[i32],
846    mw: i32,
847    mh: i32,
848    dir2rad: &Dir2Rad,
849    lfsparms: &LfsParms,
850) {
851    for my in 0..mh {
852        for mx in 0..mw {
853            let idx = (my * mw + mx) as usize;
854            // Skip LOW CONTRAST blocks (keep their INVALID direction).
855            if low_contrast_map[idx] != 0 {
856                continue;
857            }
858
859            let (avrdir, dir_strength, nvalid) =
860                average_8nbr_dir(direction_map, mx, my, mw, mh, dir2rad);
861
862            if dir_strength >= lfsparms.dir_strength_min {
863                if direction_map[idx] != INVALID_DIR {
864                    // Valid direction: overwrite if enough valid neighbors.
865                    if nvalid >= lfsparms.rmv_valid_nbr_min {
866                        direction_map[idx] = avrdir;
867                    }
868                } else {
869                    // Invalid direction: fill if enough valid neighbors.
870                    if nvalid >= lfsparms.smth_valid_nbr_min {
871                        direction_map[idx] = avrdir;
872                    }
873                }
874            }
875        }
876    }
877}
878
879/// `find_valid_block` (block.c L324) — search from `start` along `incr` for a valid direction.
880///
881/// Steps by `incr` (starting one step out), stopping unsuccessfully at a LOW CONTRAST block or the
882/// map boundary, and successfully at the first block with a valid direction — returned as
883/// `(dir, x, y)`.
884fn find_valid_block(
885    direction_map: &[i32],
886    low_contrast_map: &[i32],
887    start: (i32, i32),
888    dims: (i32, i32),
889    incr: (i32, i32),
890) -> Option<(i32, i32, i32)> {
891    let (mw, mh) = dims;
892    let mut x = start.0 + incr.0;
893    let mut y = start.1 + incr.1;
894
895    while (x >= 0) && (x < mw) && (y >= 0) && (y < mh) {
896        let idx = (y * mw + x) as usize;
897        // Stop unsuccessfully at a LOW CONTRAST block.
898        if low_contrast_map[idx] != 0 {
899            return None;
900        }
901        // Stop successfully at a block with valid direction.
902        let dir = direction_map[idx];
903        if dir >= 0 {
904            return Some((dir, x, y));
905        }
906        x += incr.0;
907        y += incr.1;
908    }
909    None
910}
911
912/// `interpolate_direction_map` (maps.c L481) — fill INVALID directions from valid N/E/S/W neighbors.
913///
914/// For each non-low-contrast INVALID block, the nearest valid block in each cardinal direction is
915/// found ([`find_valid_block`], stopping at low-contrast blocks). If at least `min_interpolate_nbrs`
916/// are found, their directions are combined in a distance-weighted average (weight `total_dist - dist`),
917/// [`trunc_dbl_precision`]-quantized and [`sround`]ed. Results are computed into a separate buffer
918/// read from the original map, then copied back — so no in-pass write affects another block.
919fn interpolate_direction_map(
920    direction_map: &mut [i32],
921    low_contrast_map: &[i32],
922    mw: i32,
923    mh: i32,
924    lfsparms: &LfsParms,
925) {
926    let mut omap = direction_map.to_vec();
927
928    for y in 0..mh {
929        for x in 0..mw {
930            let idx = (y * mw + x) as usize;
931
932            // Only interpolate non-low-contrast blocks with INVALID direction.
933            if (low_contrast_map[idx] == 0) && (direction_map[idx] == INVALID_DIR) {
934                let mut total_found = 0i32;
935                let mut total_dist = 0i32;
936
937                // North (0,-1): dist = y - nbr_y.
938                let north =
939                    find_valid_block(direction_map, low_contrast_map, (x, y), (mw, mh), (0, -1))
940                        .map(|(d, _nx, ny)| {
941                            let dist = y - ny;
942                            total_dist += dist;
943                            total_found += 1;
944                            (d, dist)
945                        });
946                // East (1,0): dist = nbr_x - x.
947                let east =
948                    find_valid_block(direction_map, low_contrast_map, (x, y), (mw, mh), (1, 0))
949                        .map(|(d, nx, _ny)| {
950                            let dist = nx - x;
951                            total_dist += dist;
952                            total_found += 1;
953                            (d, dist)
954                        });
955                // South (0,1): dist = nbr_y - y.
956                let south =
957                    find_valid_block(direction_map, low_contrast_map, (x, y), (mw, mh), (0, 1))
958                        .map(|(d, _nx, ny)| {
959                            let dist = ny - y;
960                            total_dist += dist;
961                            total_found += 1;
962                            (d, dist)
963                        });
964                // West (-1,0): dist = x - nbr_x.
965                let west =
966                    find_valid_block(direction_map, low_contrast_map, (x, y), (mw, mh), (-1, 0))
967                        .map(|(d, nx, _ny)| {
968                            let dist = x - nx;
969                            total_dist += dist;
970                            total_found += 1;
971                            (d, dist)
972                        });
973
974                if total_found >= lfsparms.min_interpolate_nbrs {
975                    // Weighted sum inversely related to distance: weight = total_dist - dist.
976                    let mut total_delta = 0i32;
977                    let weight =
978                        |nbr: Option<(i32, i32)>, total_delta: &mut i32| -> Option<(i32, i32)> {
979                            nbr.map(|(d, dist)| {
980                                let delta = total_dist - dist;
981                                *total_delta += delta;
982                                (d, delta)
983                            })
984                        };
985                    let n_w = weight(north, &mut total_delta);
986                    let e_w = weight(east, &mut total_delta);
987                    let s_w = weight(south, &mut total_delta);
988                    let w_w = weight(west, &mut total_delta);
989
990                    let mut avr_dir = 0.0_f64;
991                    let mut accum = |nbr: Option<(i32, i32)>| {
992                        if let Some((d, delta)) = nbr {
993                            avr_dir += f64::from(d) * (f64::from(delta) / f64::from(total_delta));
994                        }
995                    };
996                    accum(n_w);
997                    accum(e_w);
998                    accum(s_w);
999                    accum(w_w);
1000
1001                    // Truncate precision for cross-architecture consistency, then round.
1002                    avr_dir = trunc_dbl_precision(avr_dir, TRUNC_SCALE);
1003                    omap[idx] = sround(avr_dir);
1004                } else {
1005                    // Not enough neighbors: direction remains INVALID.
1006                    omap[idx] = direction_map[idx];
1007                }
1008            } else {
1009                // Otherwise, keep the current direction.
1010                omap[idx] = direction_map[idx];
1011            }
1012        }
1013    }
1014
1015    // Copy interpolated directions back into the input map.
1016    direction_map.copy_from_slice(&omap);
1017}
1018
1019// =====================================================================================================
1020// High-curvature map (maps.c gen_high_curve_map L881 + vorticity/curvature)
1021// =====================================================================================================
1022
1023/// `accum_nbr_vorticity` (maps.c L2401) — accumulate the signed turn between two neighbor directions.
1024///
1025/// When both directions are valid and distinct, the clockwise distance `dir2 - dir1` (wrapped to
1026/// `[0, ndirs)`) increments the measure if `<= ndirs/2` and decrements it otherwise.
1027fn accum_nbr_vorticity(vmeasure: &mut i32, dir1: i32, dir2: i32, ndirs: i32) {
1028    if (dir1 != dir2) && (dir1 >= 0) && (dir2 >= 0) {
1029        let mut dist = dir2 - dir1;
1030        if dist < 0 {
1031            dist += ndirs;
1032        }
1033        if dist > (ndirs >> 1) {
1034            *vmeasure -= 1;
1035        } else {
1036            *vmeasure += 1;
1037        }
1038    }
1039}
1040
1041/// Fetch the 8 neighbor directions of `(mx,my)` in stock order, each INVALID when out of bounds.
1042/// Returns `[nw, n, ne, e, se, s, sw, w]`, shared by [`vorticity`] and [`curvature`].
1043fn neighbor_dirs(imap: &[i32], mx: i32, my: i32, mw: i32, mh: i32) -> [i32; 8] {
1044    let e = mx + 1;
1045    let w = mx - 1;
1046    let n = my - 1;
1047    let s = my + 1;
1048    let at = |bx: i32, by: i32| imap[(by * mw + bx) as usize];
1049
1050    let nw = if (w >= 0) && (n >= 0) {
1051        at(w, n)
1052    } else {
1053        INVALID_DIR
1054    };
1055    let n_v = if n >= 0 { at(mx, n) } else { INVALID_DIR };
1056    let ne = if (n >= 0) && (e < mw) {
1057        at(e, n)
1058    } else {
1059        INVALID_DIR
1060    };
1061    let e_v = if e < mw { at(e, my) } else { INVALID_DIR };
1062    let se = if (e < mw) && (s < mh) {
1063        at(e, s)
1064    } else {
1065        INVALID_DIR
1066    };
1067    let s_v = if s < mh { at(mx, s) } else { INVALID_DIR };
1068    let sw = if (w >= 0) && (s < mh) {
1069        at(w, s)
1070    } else {
1071        INVALID_DIR
1072    };
1073    let w_v = if w >= 0 { at(w, my) } else { INVALID_DIR };
1074    [nw, n_v, ne, e_v, se, s_v, sw, w_v]
1075}
1076
1077/// `vorticity` (maps.c L2291) — cumulative curvature among a block's 8 neighbors, walked as a ring.
1078///
1079/// Accumulates [`accum_nbr_vorticity`] over the consecutive neighbor pairs
1080/// NW-N, N-NE, NE-E, E-SE, SE-S, S-SW, SW-W, W-NW.
1081fn vorticity(imap: &[i32], mx: i32, my: i32, mw: i32, mh: i32, ndirs: i32) -> i32 {
1082    let [nw, n, ne, e, se, s, sw, w] = neighbor_dirs(imap, mx, my, mw, mh);
1083    let mut vmeasure = 0i32;
1084    accum_nbr_vorticity(&mut vmeasure, nw, n, ndirs);
1085    accum_nbr_vorticity(&mut vmeasure, n, ne, ndirs);
1086    accum_nbr_vorticity(&mut vmeasure, ne, e, ndirs);
1087    accum_nbr_vorticity(&mut vmeasure, e, se, ndirs);
1088    accum_nbr_vorticity(&mut vmeasure, se, s, ndirs);
1089    accum_nbr_vorticity(&mut vmeasure, s, sw, ndirs);
1090    accum_nbr_vorticity(&mut vmeasure, sw, w, ndirs);
1091    accum_nbr_vorticity(&mut vmeasure, w, nw, ndirs);
1092    vmeasure
1093}
1094
1095/// `curvature` (maps.c L2451) — the largest [`closest_dir_dist`] between the block and any valid
1096/// neighbor, or `-1` if no valid neighbor exists.
1097fn curvature(imap: &[i32], mx: i32, my: i32, mw: i32, mh: i32, ndirs: i32) -> i32 {
1098    let nbrs = neighbor_dirs(imap, mx, my, mw, mh);
1099    let cur = imap[(my * mw + mx) as usize];
1100    let mut cmeasure = -1i32;
1101    for &nbr in &nbrs {
1102        let dist = closest_dir_dist(cur, nbr, ndirs);
1103        if dist > cmeasure {
1104            cmeasure = dist;
1105        }
1106    }
1107    cmeasure
1108}
1109
1110/// `gen_high_curve_map` (maps.c L881) — flag blocks near cores/deltas as high curvature.
1111///
1112/// A block with valid neighbors is flagged when: its direction is INVALID and it has at least
1113/// `vort_valid_nbr_min` valid neighbors with [`vorticity`] `>= highcurv_vorticity_min`; or its
1114/// direction is valid with [`curvature`] `>= highcurv_curvature_min`.
1115fn gen_high_curve_map(direction_map: &[i32], mw: i32, mh: i32, lfsparms: &LfsParms) -> Vec<i32> {
1116    let mapsize = (mw * mh) as usize;
1117    let mut high_curve_map = vec![FALSE; mapsize];
1118
1119    for by in 0..mh {
1120        for bx in 0..mw {
1121            let idx = (by * mw + bx) as usize;
1122            let nvalid = num_valid_8nbrs(direction_map, bx, by, mw, mh);
1123
1124            if nvalid > 0 {
1125                if direction_map[idx] == INVALID_DIR {
1126                    if nvalid >= lfsparms.vort_valid_nbr_min {
1127                        let vmeasure =
1128                            vorticity(direction_map, bx, by, mw, mh, lfsparms.num_directions);
1129                        if vmeasure >= lfsparms.highcurv_vorticity_min {
1130                            high_curve_map[idx] = TRUE;
1131                        }
1132                    }
1133                } else {
1134                    let cmeasure =
1135                        curvature(direction_map, bx, by, mw, mh, lfsparms.num_directions);
1136                    if cmeasure >= lfsparms.highcurv_curvature_min {
1137                        high_curve_map[idx] = TRUE;
1138                    }
1139                }
1140            }
1141        }
1142    }
1143    high_curve_map
1144}
1145
1146/// `set_margin_blocks` (block.c L373) — set the map's entire perimeter to `margin_value`.
1147fn set_margin_blocks(map: &mut [i32], mw: i32, mh: i32, margin_value: i32) {
1148    // Top and bottom rows.
1149    for x in 0..mw {
1150        map[x as usize] = margin_value;
1151        map[((mh - 1) * mw + x) as usize] = margin_value;
1152    }
1153    // Left and right columns (excluding the corners already set).
1154    for y in 1..mh - 1 {
1155        map[(y * mw) as usize] = margin_value;
1156        map[(y * mw + mw - 1) as usize] = margin_value;
1157    }
1158}
1159
1160// =====================================================================================================
1161// Top level (maps.c gen_image_maps L126)
1162// =====================================================================================================
1163
1164/// `gen_image_maps` (maps.c L126) — the full block-map pipeline over a padded, 6-bit image.
1165///
1166/// Steps, in the exact stock order (steps 3–7 are what make the Direction Map usable):
1167/// 1. block offsets, 2. [`gen_initial_maps`], `morph_TF_map` on the Low Flow map,
1168/// 3. [`remove_incon_dirs`], 4. [`smooth_direction_map`], 5. [`interpolate_direction_map`],
1169/// 6. [`remove_incon_dirs`] again, 7. [`smooth_direction_map`] again,
1170/// 8. [`set_margin_blocks`] to INVALID, 9. [`gen_high_curve_map`].
1171///
1172/// `pdata`/`pw`/`ph` are the padded image and its dimensions; the unpadded size is recovered as
1173/// `pw - 2*pad`. The DFT grid must be square (the V2 geometry guarantees `windowsize × windowsize`).
1174///
1175/// # Errors
1176/// Propagates the negative stock error codes from [`block_offsets`]/[`low_contrast_block`], plus
1177/// `-540` if the DFT grid is not square.
1178pub(crate) fn gen_image_maps(
1179    pdata: &[u8],
1180    pw: i32,
1181    ph: i32,
1182    dir2rad: &Dir2Rad,
1183    dftwaves: &DftWaves,
1184    dftgrids: &RotGrids,
1185    lfsparms: &LfsParms,
1186) -> Result<ImageMaps, i32> {
1187    // block_offsets assumes a square block/grid.
1188    if dftgrids.grid_w != dftgrids.grid_h {
1189        return Err(-540);
1190    }
1191
1192    // Unpadded image dimensions.
1193    let iw = pw - (dftgrids.pad << 1);
1194    let ih = ph - (dftgrids.pad << 1);
1195
1196    // 1. Block offsets.
1197    let bo = block_offsets(iw, ih, dftgrids.pad, lfsparms.blocksize)?;
1198    let (mw, mh) = (bo.map_w, bo.map_h);
1199
1200    // 2. Initial Direction / Low Contrast / Low Ridge Flow maps.
1201    let (mut direction_map, low_contrast_map, mut low_flow_map) = gen_initial_maps(
1202        &bo.offsets,
1203        (mw, mh),
1204        pdata,
1205        (pw, ph),
1206        dftwaves,
1207        dftgrids,
1208        lfsparms,
1209    )?;
1210
1211    morph_tf_map(&mut low_flow_map, mw, mh);
1212
1213    // 3. Remove inconsistent directions.
1214    remove_incon_dirs(&mut direction_map, mw, mh, dir2rad, lfsparms);
1215
1216    // 4. Smooth.
1217    smooth_direction_map(
1218        &mut direction_map,
1219        &low_contrast_map,
1220        mw,
1221        mh,
1222        dir2rad,
1223        lfsparms,
1224    );
1225
1226    // 5. Interpolate INVALID blocks from valid neighbors.
1227    interpolate_direction_map(&mut direction_map, &low_contrast_map, mw, mh, lfsparms);
1228
1229    // 6. Remove inconsistent directions again.
1230    remove_incon_dirs(&mut direction_map, mw, mh, dir2rad, lfsparms);
1231
1232    // 7. Smooth again.
1233    smooth_direction_map(
1234        &mut direction_map,
1235        &low_contrast_map,
1236        mw,
1237        mh,
1238        dir2rad,
1239        lfsparms,
1240    );
1241
1242    // 8. Set margin blocks to INVALID.
1243    set_margin_blocks(&mut direction_map, mw, mh, INVALID_DIR);
1244
1245    // 9. High Curvature Map from the interpolated Direction Map.
1246    let high_curve_map = gen_high_curve_map(&direction_map, mw, mh, lfsparms);
1247
1248    Ok(ImageMaps {
1249        direction_map,
1250        low_contrast_map,
1251        low_flow_map,
1252        high_curve_map,
1253        map_w: mw,
1254        map_h: mh,
1255    })
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261    use crate::consts::{DFT_COEFS, MAP_WINDOWSIZE_V2, NUM_DFT_WAVES, NUM_DIRECTIONS};
1262    use crate::init::{get_max_padding_V2, init_dftwaves, init_dir2rad, init_rotgrids, Relative2};
1263    use crate::params::LFSPARMS_V2;
1264
1265    // --- closest_dir_dist: wrap-aware direction distance --------------------------------------
1266    #[test]
1267    fn closest_dir_dist_wraps() {
1268        // ndirs = 16: 2 and 14 are 4 apart the short way (min(12, 4)).
1269        assert_eq!(closest_dir_dist(2, 14, 16), 4);
1270        assert_eq!(closest_dir_dist(0, 8, 16), 8);
1271        assert_eq!(closest_dir_dist(3, 3, 16), 0);
1272        // Either direction invalid -> INVALID.
1273        assert_eq!(closest_dir_dist(-1, 5, 16), -1);
1274        assert_eq!(closest_dir_dist(5, -1, 16), -1);
1275    }
1276
1277    // --- accum_nbr_vorticity: signed turn accumulation ----------------------------------------
1278    #[test]
1279    fn accum_nbr_vorticity_signs() {
1280        let mut v = 0;
1281        // Clockwise 2 (<= 8) increments.
1282        accum_nbr_vorticity(&mut v, 2, 4, 16);
1283        assert_eq!(v, 1);
1284        // Clockwise distance 3-8 = -5 -> +16 = 11 (> 8) decrements.
1285        accum_nbr_vorticity(&mut v, 8, 3, 16);
1286        assert_eq!(v, 0);
1287        // Equal or invalid: ignored.
1288        accum_nbr_vorticity(&mut v, 5, 5, 16);
1289        accum_nbr_vorticity(&mut v, -1, 5, 16);
1290        assert_eq!(v, 0);
1291    }
1292
1293    // --- num_valid_8nbrs: only in-bounds valid neighbors count --------------------------------
1294    #[test]
1295    fn num_valid_8nbrs_counts_in_bounds() {
1296        // 3x3 map, center at (1,1) surrounded by 8 valid dirs -> 8.
1297        let all_valid = vec![0i32; 9];
1298        assert_eq!(num_valid_8nbrs(&all_valid, 1, 1, 3, 3), 8);
1299        // Corner (0,0) has only 3 in-bounds neighbors.
1300        assert_eq!(num_valid_8nbrs(&all_valid, 0, 0, 3, 3), 3);
1301        // INVALID neighbors are not counted.
1302        let mut m = vec![INVALID_DIR; 9];
1303        m[4] = 0; // only center valid; corner (0,0) sees center as SE -> 1 valid.
1304        assert_eq!(num_valid_8nbrs(&m, 0, 0, 3, 3), 1);
1305    }
1306
1307    // --- set_margin_blocks: perimeter set, interior untouched ---------------------------------
1308    #[test]
1309    fn set_margin_blocks_sets_perimeter() {
1310        let mut m = vec![5i32; 16]; // 4x4 filled with 5.
1311        set_margin_blocks(&mut m, 4, 4, -1);
1312        #[rustfmt::skip]
1313        let expected = vec![
1314            -1, -1, -1, -1,
1315            -1,  5,  5, -1,
1316            -1,  5,  5, -1,
1317            -1, -1, -1, -1,
1318        ];
1319        assert_eq!(m, expected);
1320    }
1321
1322    // --- morph_tf_map: closing fills a single-block hole --------------------------------------
1323    #[test]
1324    fn morph_tf_map_closes_hole() {
1325        // 5x5 all TRUE with one FALSE hole in the center; dilate-dilate-erode-erode fills it.
1326        let mut map = vec![1i32; 25];
1327        map[12] = 0;
1328        morph_tf_map(&mut map, 5, 5);
1329        assert_eq!(map[12], 1, "center hole should be closed");
1330        // A fully-true map stays true.
1331        let mut full = vec![1i32; 25];
1332        morph_tf_map(&mut full, 5, 5);
1333        assert!(full.iter().all(|&v| v == 1));
1334    }
1335
1336    // --- get_max_norm: max, its direction, normalized power -----------------------------------
1337    #[test]
1338    fn get_max_norm_picks_first_max() {
1339        // Power peaks at dir 2; ties keep the first index.
1340        let pv = vec![1.0, 2.0, 9.0, 9.0, 1.0, 1.0, 1.0, 1.0];
1341        let (pm, pd, pnorm) = get_max_norm(&pv, 8);
1342        assert_eq!(pm, 9.0);
1343        assert_eq!(pd, 2); // first of the two 9.0 peaks
1344        let powsum: f64 = pv.iter().sum();
1345        assert!((pnorm - 9.0 / (powsum.max(MIN_POWER_SUM) / 8.0)).abs() < 1e-12);
1346    }
1347
1348    // --- Full pipeline on a flat image: every block is low contrast ---------------------------
1349    #[test]
1350    fn gen_image_maps_flat_image_is_all_low_contrast() {
1351        // Build the V2 tables and a flat, already-6-bit padded image.
1352        let p = &LFSPARMS_V2;
1353        let pad = get_max_padding_V2(
1354            p.windowsize,
1355            p.windowoffset,
1356            p.dirbin_grid_w,
1357            p.dirbin_grid_h,
1358        );
1359        assert_eq!(pad, 13);
1360
1361        let dir2rad = init_dir2rad(NUM_DIRECTIONS);
1362        let dftwaves = init_dftwaves(&DFT_COEFS, NUM_DFT_WAVES, MAP_WINDOWSIZE_V2);
1363
1364        // Unpadded 32x32 -> 4x4 blocks; padded to 58x58.
1365        let iw = 32i32;
1366        let ih = 32i32;
1367        let dftgrids = init_rotgrids(
1368            iw,
1369            Some(pad),
1370            p.start_dir_angle,
1371            NUM_DIRECTIONS,
1372            p.windowsize,
1373            p.windowsize,
1374            Relative2::Origin,
1375        );
1376        let pw = iw + 2 * pad;
1377        let ph = ih + 2 * pad;
1378
1379        // Flat 6-bit image (constant value): zero contrast everywhere.
1380        let pdata = vec![10u8; (pw * ph) as usize];
1381
1382        let maps = gen_image_maps(&pdata, pw, ph, &dir2rad, &dftwaves, &dftgrids, p).unwrap();
1383
1384        assert_eq!((maps.map_w, maps.map_h), (4, 4));
1385        let n = (maps.map_w * maps.map_h) as usize;
1386        assert_eq!(maps.direction_map.len(), n);
1387        // Flat -> all low contrast, all directions INVALID, no low flow, no high curvature.
1388        assert!(maps.low_contrast_map.iter().all(|&v| v == TRUE));
1389        assert!(maps.direction_map.iter().all(|&v| v == INVALID_DIR));
1390        assert!(maps.low_flow_map.iter().all(|&v| v == FALSE));
1391        assert!(maps.high_curve_map.iter().all(|&v| v == FALSE));
1392    }
1393
1394    // --- gen_image_maps rejects a non-square DFT grid -----------------------------------------
1395    #[test]
1396    fn gen_image_maps_non_square_grid_errs() {
1397        let p = &LFSPARMS_V2;
1398        let dir2rad = init_dir2rad(NUM_DIRECTIONS);
1399        let dftwaves = init_dftwaves(&DFT_COEFS, NUM_DFT_WAVES, MAP_WINDOWSIZE_V2);
1400        // Deliberately non-square grid (grid_w != grid_h).
1401        let dftgrids = init_rotgrids(
1402            32,
1403            Some(13),
1404            p.start_dir_angle,
1405            NUM_DIRECTIONS,
1406            24,
1407            20,
1408            Relative2::Origin,
1409        );
1410        let pw = 32 + 26;
1411        let ph = 32 + 26;
1412        let pdata = vec![10u8; (pw * ph) as usize];
1413        assert_eq!(
1414            gen_image_maps(&pdata, pw, ph, &dir2rad, &dftwaves, &dftgrids, p),
1415            Err(-540)
1416        );
1417    }
1418}