amosaic 1.0.0

This library provides tools for generating and working with aperiodic tilings and mosaics, based on the hat monotile discovered by David Smith and inspired by the work of Craig S. Kaplan.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use crate::hat::geometry::{mul, trans_pt, ttrans, IDENT};
use crate::hat::tiles::{
  collect_hats, construct_metatiles, construct_patch, construct_prototiles, DrawContext, HatTile,
  MetaTile, Tile,
};
use image::{ImageBuffer, ImageError, Rgb, RgbImage};
use nalgebra::Vector2;
use std::path::Path;
use std::rc::Rc;
use svg::node::element::Polygon;
use svg::node::element::SVG;
use svg::Document;

/// Configuration for the mosaic image generation.
#[derive(Debug, Clone)]
pub struct AMosaic {
  pub width: u32,
  pub height: u32,
  pub input_data: Vec<u8>,
}

impl AMosaic {
  /// Creates a new AMosaic configuration with the given width, height, and output path.
  pub fn new(width: u32, height: u32, input_data: Vec<u8>) -> Self {
    AMosaic {
      width,
      height,
      input_data,
    }
  }

  /// Computes the minimum level needed to cover the canvas based on scale.
  fn compute_required_level(&self, scale: f64) -> i32 {
    // Assume initial patch diameter (d_0) and growth factor (s) for hat tiling.
    // These values may need to be adjusted based on the specific tiling implementation.
    let initial_diameter = 5.0; // Initial patch diameter in geometric coordinates
    let growth_factor = 2.0; // Approximate scaling factor per substitution level

    // Canvas diagonal in pixels
    let canvas_diagonal =
      (self.width as f64 * self.width as f64 + self.height as f64 * self.height as f64).sqrt();

    // Required diameter in geometric coordinates: canvas_diagonal / scale
    let required_diameter = canvas_diagonal / scale;

    // Solve for n: initial_diameter * growth_factor^n >= required_diameter
    // n >= ceil(log_{growth_factor}(required_diameter / initial_diameter))
    let level = (required_diameter / initial_diameter)
      .log(growth_factor)
      .ceil()
      .max(0.0) as i32;

    level
  }
  /// Emit an SVG of the mosaic with perfectly straight edges.
  pub fn to_svg(&self, scale: f64) -> String {
    // 1) Build the patch
    let level = self.compute_required_level(scale);
    let root = self
      .create_tile_patch(level)
      .expect("failed to build patch");

    // 2) Compute the transform
    let to_screen = [scale, 0.0, 0.0, 0.0, -scale, 0.0];
    let t_center = ttrans(self.width as f64 / 2.0, self.height as f64 / 2.0);
    let transform = mul(&t_center, &to_screen);

    // 3) Start the SVG canvas
    let mut svg_canvas = Document::new()
      .set("width", self.width)
      .set("height", self.height)
      .set("viewBox", (0, 0, self.width, self.height))
      .add(SVG::new().set("xmlns", "http://www.w3.org/2000/svg"));

    // 4) Input image for color sampling
    let input = self.decode_input_image();

    // 5) Walk every hat and emit a <polygon>
    for (hat, t_abs) in collect_hats(&root, transform) {
      // Map outline to floating‐point pixel coords
      let poly_f: Vec<_> = hat.shape.iter().map(|p| trans_pt(&t_abs, *p)).collect();

      // Sample color
      let poly_in: Vec<(i32, i32)> = poly_f
        .iter()
        .map(|p| {
          let ix = (p.x + 0.5).floor() as i32;
          let iy = (p.y + 0.5).floor() as i32;
          (
            ix.clamp(0, self.width as i32 - 1),
            iy.clamp(0, self.height as i32 - 1),
          )
        })
        .collect();
      let (r, g, b) = average_color_scanline(&input, &poly_in);

      // Build the SVG points string
      let points = poly_f
        .iter()
        .map(|p| format!("{:.2},{:.2}", p.x, p.y))
        .collect::<Vec<_>>()
        .join(" ");

      // Create and add the <polygon>
      let polygon = Polygon::new()
        .set("points", points)
        .set("fill", format!("rgb({},{},{})", r, g, b));
      svg_canvas = svg_canvas.add(polygon);
    }

    // 6) Serialize to a string
    svg_canvas.to_string()
  }

  pub fn draw(&self, scale: f64, output: &mut RgbImage) -> Result<(), ImageError> {
    let level = self.compute_required_level(scale);
    // 1) Build the substitution patch
    let root = self.create_tile_patch(level)?;

    // 2) How many border pixels to allocate?
    //    (scale<1 → grow_px=1; scale large → bleed that many px)
    let grow_px = scale.ceil() as u32;

    // 3) Padded canvas dimensions
    let pad_w = self.width + 2 * grow_px;
    let pad_h = self.height + 2 * grow_px;

    // 4) Set up the screen transform centered on the Padded canvas
    let to_screen = [scale, 0.0, 0.0, 0.0, -scale, 0.0];
    let t_center_pad = ttrans(pad_w as f64 / 2.0, pad_h as f64 / 2.0);
    let transform = mul(&t_center_pad, &to_screen);

    // 5) Create a white padded image to draw into
    let mut padded = RgbImage::from_pixel(pad_w, pad_h, Rgb([255, 255, 255]));

    // 6) We'll still sample colors from the original input image
    let input_img = self.decode_input_image();

    // 7) Draw each “hat” into the padded canvas
    for (hat, t_abs) in collect_hats(&root, transform) {
      // 7a) compute floating‐point outline in padded‐space
      let poly_f: Vec<Vector2<f64>> = hat.shape.iter().map(|p| trans_pt(&t_abs, *p)).collect();

      // 7b) quick reject: if the poly never overlaps the original canvas at all
      let (min_x_f, max_x_f) = poly_f
        .iter()
        .map(|p| p.x)
        .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), x| {
          (mn.min(x), mx.max(x))
        });
      let (min_y_f, max_y_f) = poly_f
        .iter()
        .map(|p| p.y)
        .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), y| {
          (mn.min(y), mx.max(y))
        });
      if max_x_f < -0.5
        || min_x_f > (self.width as f64 - 0.5)
        || max_y_f < -0.5
        || min_y_f > (self.height as f64 - 0.5)
      {
        continue;
      }

      // 7c) Build an integer polygon for COLOR SAMPLING (clamped to original img)
      let poly_in: Vec<(i32, i32)> = poly_f
        .iter()
        .map(|p| {
          let ix = (p.x + 0.5).floor() as i32;
          let iy = (p.y + 0.5).floor() as i32;
          (
            ix.clamp(0, self.width as i32 - 1),
            iy.clamp(0, self.height as i32 - 1),
          )
        })
        .collect();
      if poly_in.len() < 3 {
        continue;
      }
      let color = average_color_scanline(&input_img, &poly_in);

      // 7d) Build an integer polygon for DRAWING (shifted into padded coords)
      let poly_pad: Vec<(i32, i32)> = poly_f
        .iter()
        .map(|p| {
          let ix = (p.x + 0.5).floor() as i32 + grow_px as i32;
          let iy = (p.y + 0.5).floor() as i32 + grow_px as i32;
          (ix, iy)
        })
        .collect();

      // 7e) Fill it (with the built-in ±1px grow) into `padded`
      fill_polygon_gapless(&mut padded, &poly_pad, color);
    }

    // 8) Crop the center `width×height` region back into the real `output`
    for y in 0..self.height {
      for x in 0..self.width {
        let p = padded.get_pixel(x + grow_px, y + grow_px);
        output.put_pixel(x, y, *p);
      }
    }

    Ok(())
  }
  /// helper to decode your raw `input_data` into an RgbImage
  fn decode_input_image(&self) -> RgbImage {
    ImageBuffer::from_raw(self.width, self.height, self.input_data.clone())
      .unwrap_or_else(|| RgbImage::from_pixel(self.width, self.height, Rgb([255, 255, 255])))
  }

  /// Constructs the tile patch for the specified level.
  pub fn create_tile_patch(&self, level: i32) -> Result<Rc<dyn Tile>, ImageError> {
    let (mt0, mt1, mt2, mt3) = construct_prototiles();
    let mut patch = construct_patch(&mt0, &mt1, &mt2, &mt3);
    for _ in 0..level {
      let (nmt0, nmt1, nmt2, nmt3) = construct_metatiles(&patch);
      patch = construct_patch(&nmt0, &nmt1, &nmt2, &nmt3);
    }
    Ok(Rc::new(patch) as Rc<dyn Tile>)
  }
}

pub struct ImageDrawContext<'a> {
  pub img: &'a mut RgbImage,
}

impl<'a> DrawContext for ImageDrawContext<'a> {
  fn polygon(
    &mut self,
    points: &[(i32, i32)],
    fill: Option<(u8, u8, u8)>,
    outline: Option<(u8, u8, u8)>,
  ) {
    if let Some(col) = fill {
      // use scanline fill for gap‐free polygons
      fill_polygon_gapless(self.img, points, col);
    }
  }
}
fn draw_edge(
  img: &mut RgbImage,
  (mut x0, mut y0): (i32, i32),
  (x1, y1): (i32, i32),
  color: (u8, u8, u8),
) {
  let dx = (x1 - x0).abs();
  let dy = (y1 - y0).abs();
  let sx = if x0 < x1 { 1 } else { -1 };
  let sy = if y0 < y1 { 1 } else { -1 };
  let mut err = dx - dy;

  loop {
    // clamp to image bounds
    if let (Some(xx), Some(yy)) = (
      (0..img.width() as i32).contains(&x0).then(|| x0 as u32),
      (0..img.height() as i32).contains(&y0).then(|| y0 as u32),
    ) {
      img.put_pixel(xx, yy, Rgb([color.0, color.1, color.2]));
    }
    if x0 == x1 && y0 == y1 {
      break;
    }
    let e2 = err * 2;
    if e2 > -dy {
      err -= dy;
      x0 += sx;
    }
    if e2 < dx {
      err += dx;
      y0 += sy;
    }
  }
}

/// Scanline‐fill + explicit boundary draw.
fn fill_polygon_gapless(img: &mut RgbImage, poly: &[(i32, i32)], color: (u8, u8, u8)) {
  // 1) Scanline fill
  struct Edge {
    y_min: i32,
    y_max: i32,
    x: f64,
    inv_slope: f64,
  }
  let n = poly.len();
  if n < 3 {
    return;
  }

  let mut edges = Vec::with_capacity(n);
  for i in 0..n {
    let (x0, y0) = poly[i];
    let (x1, y1) = poly[(i + 1) % n];
    if y0 == y1 {
      continue;
    }
    let (y_min, y_max, x_at_ymin, dy, dx) = if y0 < y1 {
      (y0, y1, x0 as f64, (y1 - y0) as f64, (x1 - x0) as f64)
    } else {
      (y1, y0, x1 as f64, (y0 - y1) as f64, (x0 - x1) as f64)
    };
    edges.push(Edge {
      y_min,
      y_max,
      x: x_at_ymin,
      inv_slope: dx / dy,
    });
  }

  let h = img.height() as i32;
  let w = img.width() as i32;
  let y_start = poly.iter().map(|&(_, y)| y).min().unwrap().clamp(0, h - 1);
  let y_end = poly.iter().map(|&(_, y)| y).max().unwrap().clamp(0, h - 1);

  for y in y_start..=y_end {
    let mut xs: Vec<f64> = edges
      .iter()
      .filter_map(|e| {
        if (e.y_min..e.y_max).contains(&y) {
          Some(e.x + (y - e.y_min) as f64 * e.inv_slope)
        } else {
          None
        }
      })
      .collect();

    xs.sort_by(|a, b| a.partial_cmp(b).unwrap());

    match xs.len() {
      0 => continue,       // still nothing to fill here
      1 => xs.push(xs[0]), // turn that one point into a zero‐width span
      _ => {}              // 2 or more, normal case
    }

    for chunk in xs.chunks(2) {
      if let [x0, x1] = chunk {
        // 1px horizontal grow on each side, then clamp
        let x_start = (x0.ceil() as i32).max(0);
        let x_end = (x1.floor() as i32).min(w - 1);
        if x_end >= x_start {
          let yy = y as u32;
          for xx in x_start as u32..=x_end as u32 {
            img.put_pixel(xx, yy, Rgb([color.0, color.1, color.2]));
          }
        }
      }
    }
  }

  // 2) Draw the edges so no single‐pixel gap remains
  for i in 0..n {
    let p0 = poly[i];
    let p1 = poly[(i + 1) % n];
    draw_edge(img, p0, p1, color);
  }
}
/// Bresenham line‐drawer for the polygon boundary.
// fn draw_edge(img: &mut RgbImage, a: (i32, i32), b: (i32, i32), color: (u8, u8, u8)) {
//   let (mut x0, mut y0) = a;
//   let (x1, y1) = b;
//   let dx = (x1 - x0).abs();
//   let dy = (y1 - y0).abs();
//   let sx = if x0 < x1 { 1 } else { -1 };
//   let sy = if y0 < y1 { 1 } else { -1 };
//   let mut err = dx - dy;
//   while {
//     if x0 >= 0 && (x0 as u32) < img.width() && y0 >= 0 && (y0 as u32) < img.height() {
//       img.put_pixel(x0 as u32, y0 as u32, Rgb([color.0, color.1, color.2]));
//     }
//     if x0 == x1 && y0 == y1 {
//       false
//     } else {
//       let e2 = err * 2;
//       if e2 > -dy {
//         err -= dy;
//         x0 += sx;
//       }
//       if e2 < dx {
//         err += dx;
//         y0 += sy;
//       }
//       true
//     }
//   } {}
// }
/// A pure‐Rust scanline average that only samples interior pixels.
pub fn average_color_scanline(img: &RgbImage, poly: &[(i32, i32)]) -> (u8, u8, u8) {
  let n = poly.len();
  if n < 3 {
    return (0, 0, 0);
  }

  let min_y = poly
    .iter()
    .map(|&(_, y)| y)
    .min()
    .unwrap()
    .max(0)
    .min((img.height() as i32) - 1);
  let max_y = poly
    .iter()
    .map(|&(_, y)| y)
    .max()
    .unwrap()
    .max(0)
    .min((img.height() as i32) - 1);

  let mut r_sum = 0u64;
  let mut g_sum = 0u64;
  let mut b_sum = 0u64;
  let mut count = 0u64;

  for y in min_y..=max_y {
    // collect intersections with the horizontal line y+0.5
    let mut xs = Vec::with_capacity(n);
    for i in 0..n {
      let (x0, y0) = poly[i];
      let (x1, y1) = poly[(i + 1) % n];
      if (y0 <= y && y1 > y) || (y1 <= y && y0 > y) {
        let t = ((y as f64) + 0.5 - (y0 as f64)) / ((y1 as f64) - (y0 as f64));
        let x = (x0 as f64) + t * ((x1 as f64) - (x0 as f64));
        xs.push(x);
      }
    }
    if xs.len() < 2 {
      continue;
    }
    xs.sort_by(|a, b| a.partial_cmp(b).unwrap());

    // fill between each pair
    for pair in xs.chunks_exact(2) {
      let x_start = pair[0].ceil() as i32;
      let x_end = pair[1].floor() as i32;
      for x in x_start..=x_end {
        if x >= 0 && (x as u32) < img.width() {
          let pix = img.get_pixel(x as u32, y as u32);
          r_sum += pix[0] as u64;
          g_sum += pix[1] as u64;
          b_sum += pix[2] as u64;
          count += 1;
        }
      }
    }
  }

  if count == 0 {
    (0, 0, 0)
  } else {
    (
      (r_sum / count) as u8,
      (g_sum / count) as u8,
      (b_sum / count) as u8,
    )
  }
}
pub fn average_color(img: &RgbImage, poly: &[(i32, i32)]) -> (u8, u8, u8) {
  if poly.is_empty() {
    return (0, 0, 0);
  }
  let width = img.width();
  let height = img.height();
  let mut r_sum: u64 = 0;
  let mut g_sum: u64 = 0;
  let mut b_sum: u64 = 0;
  let mut count: u64 = 0;

  let min_x = poly.iter().map(|p| p.0).min().unwrap_or(0).max(0) as u32;
  let max_x = poly
    .iter()
    .map(|p| p.0)
    .max()
    .unwrap_or(0)
    .min(width as i32 - 1) as u32;
  let min_y = poly.iter().map(|p| p.1).min().unwrap_or(0).max(0) as u32;
  let max_y = poly
    .iter()
    .map(|p| p.1)
    .max()
    .unwrap_or(0)
    .min(height as i32 - 1) as u32;

  for x in min_x..max_x {
    for y in min_y..max_y {
      if point_in_polygon(x as i32, y as i32, poly) {
        let pixel = img.get_pixel(x, y);
        r_sum += pixel[0] as u64;
        g_sum += pixel[1] as u64;
        b_sum += pixel[2] as u64;
        count += 1;
      }
    }
  }

  if count == 0 {
    eprintln!("average_color: No pixels inside polygon, using vertex colors");
    for &(x, y) in poly {
      if x >= 0 && x < width as i32 && y >= 0 && y < height as i32 {
        let pixel = img.get_pixel(x as u32, y as u32);
        r_sum += pixel[0] as u64;
        g_sum += pixel[1] as u64;
        b_sum += pixel[2] as u64;
        count += 1;
      }
    }
  }

  if count == 0 {
    eprintln!("No valid pixels found for polygon, returning gray");
    return (128, 128, 128); // Gray to distinguish from black
  }

  (
    (r_sum / count) as u8,
    (g_sum / count) as u8,
    (b_sum / count) as u8,
  )
}

fn point_in_polygon(x: i32, y: i32, poly: &[(i32, i32)]) -> bool {
  let mut inside = false;
  let n = poly.len();
  for i in 0..n {
    let (x1, y1) = poly[i];
    let (x2, y2) = poly[(i + 1) % n];
    let intersects = ((y1 > y) != (y2 > y))
      && ((x as f64) < (x2 - x1) as f64 * (y - y1) as f64 / (y2 - y1) as f64 + x1 as f64);
    if intersects {
      inside = !inside;
    }
  }
  inside
}

#[cfg(test)]
mod tests {
  use super::*;
  use image::Rgb;
  #[test]
  fn test_amosaic_new() {
    let input_data = vec![137, 80, 78, 71]; // Partial PNG header for test
    let mosaic = AMosaic::new(800, 600, input_data.clone());
    assert_eq!(mosaic.width, 800);
    assert_eq!(mosaic.height, 600);
    assert_eq!(mosaic.input_data, input_data);
  }

  #[test]
  fn test_average_color_empty_polygon() {
    let img = RgbImage::from_pixel(100, 100, Rgb([255, 255, 255]));
    let poly: Vec<(i32, i32)> = vec![];
    let color = average_color(&img, &poly);
    assert_eq!(color, (0, 0, 0), "Empty polygon should return black");
  }

  #[test]
  fn test_average_color_single_pixel() {
    let img = RgbImage::from_pixel(1, 1, Rgb([100, 150, 200]));
    let poly = vec![(0, 0)];
    let color = average_color(&img, &poly);
    assert_eq!(
      color,
      (100, 150, 200),
      "Single pixel polygon should return its color"
    );
  }
}