maple-render-core 0.3.0

Core rendering and animation logic for maple templates
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use std::sync::atomic::{AtomicUsize, Ordering};

use image::{Rgba, RgbaImage};
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use crate::{
    error::{Error, Result},
    input::{Input, Inputs},
    mapping::Mapping,
    pixer::{Pixer, sample_linear_opaque, sample_linear_premultiplied},
};

static RENDER_COUNT: AtomicUsize = AtomicUsize::new(0);

const RR: f64 = 2048.0; // Half of coordinate range (4096/2)

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RenderQuality {
    None,
    Simple,
    Sampled,
}

impl Default for RenderQuality {
    fn default() -> Self {
        RenderQuality::Sampled
    }
}

#[derive(Debug, Clone)]
pub struct CloudPoint {
    pub layer: u8,
    pub x: f64,
    pub y: f64,
}

pub struct Render {
    mapping: Option<Mapping>,
    out: RgbaImage,
    out_scaled: Option<RgbaImage>,
    quality: RenderQuality,
}

impl Render {
    pub fn new(quality: RenderQuality) -> Self {
        Render { mapping: None, out: RgbaImage::new(1, 1), out_scaled: None, quality }
    }

    pub fn with_default_quality() -> Self {
        Self::new(RenderQuality::Sampled)
    }

    pub fn attach_mapping(&mut self, mapping: Mapping) {
        self.mapping = Some(mapping);
    }

    fn check(&self) -> Result<&Mapping> {
        self.mapping.as_ref().ok_or(Error::NoMapping)
    }

    fn pre(&mut self) -> Result<()> {
        let mapping = self.check()?;
        self.out = mapping.neutral.clone();
        Ok(())
    }

    /// 9-tap antialiased sampling with standard UV map (parallelized by row chunks)
    fn add(&mut self, input: &Input) -> Result<()> {
        let mapping = self.mapping.as_ref().ok_or(Error::NoMapping)?;

        let active_scale = input.in_scale as f64 / 2.0;
        let w = mapping.light.width() as i32;
        let h = mapping.light.height() as i32;

        if (mapping.map1.width() as i32) < w {
            return Ok(());
        }

        let off = ((mapping.map2.height() as i32 - h) / 2) as i32;

        if mapping.map1.width() != mapping.neutral.width() {
            return Ok(());
        }
        if mapping.map2.width() != mapping.neutral.width() {
            return Ok(());
        }

        let out_w = self.out.width() as usize;
        let _out_h = self.out.height() as usize;
        let input_img = input.get();
        let input_opaque = input.is_opaque();

        let light_raw = mapping.light.as_raw();
        let dark_raw = mapping.dark.as_raw();
        let map1_raw = mapping.map1.as_raw();
        let map2_raw = mapping.map2.as_raw();

        let row_stride = out_w * 4;
        let map_stride = mapping.map1.width() as usize * 4;
        let out_raw = self.out.as_mut();

        #[cfg(not(target_arch = "wasm32"))]
        let iter = out_raw.par_chunks_mut(row_stride).enumerate();
        #[cfg(target_arch = "wasm32")]
        let iter = out_raw.chunks_mut(row_stride).enumerate();

        iter.for_each(|(y, row)| {
            let map_y_base = (y as i32 + off) as u32;
            if map_y_base >= mapping.map1.height() || map_y_base >= mapping.map2.height() {
                return;
            }

            for x in 0..out_w {
                let idx = x * 4;
                let light_idx = y * row_stride + idx;
                let map_idx = map_y_base as usize * map_stride + idx;

                let light_pixel = &light_raw[light_idx..light_idx + 4];
                let dark_pixel = &dark_raw[light_idx..light_idx + 4];
                let map_pixel = &map1_raw[map_idx..map_idx + 4];
                let sel_pixel = &map2_raw[map_idx..map_idx + 4];

                if sel_pixel[0] != input.layer {
                    continue;
                }

                let act = map_pixel[3] as i32;
                if act <= 25 {
                    continue;
                }

                let b_val = map_pixel[2] as i32;
                let ymod = b_val / 16;
                let xmod = b_val % 16;
                let x1 = map_pixel[0] as f64 + 256.0 * xmod as f64 - RR;
                let y1 = map_pixel[1] as f64 + 256.0 * ymod as f64 - RR;

                let mut x12 = x1;
                let mut y12 = y1;
                let mut x13 = x1;
                let mut y13 = y1;

                if (x as i32) < w - 1 && (y as i32) < h - 1 {
                    let mdx_idx = map_idx + 4;
                    let mdy_idx = map_idx + map_stride;
                    let mdx = &map1_raw[mdx_idx..mdx_idx + 4];
                    let mdy = &map1_raw[mdy_idx..mdy_idx + 4];

                    if mdx[3] > 127 && mdy[3] > 127 {
                        let idx2 = &map2_raw[mdx_idx..mdx_idx + 4];
                        let idx3 = &map2_raw[mdy_idx..mdy_idx + 4];

                        if idx2[0] == input.layer && idx3[0] == input.layer {
                            let mod2 = mdx[2] as i32;
                            let ymod2 = mod2 / 16;
                            let xmod2 = mod2 % 16;
                            x12 = mdx[0] as f64 + 256.0 * xmod2 as f64 - RR;
                            y12 = mdx[1] as f64 + 256.0 * ymod2 as f64 - RR;

                            let mod3 = mdy[2] as i32;
                            let ymod3 = mod3 / 16;
                            let xmod3 = mod3 % 16;
                            x13 = mdy[0] as f64 + 256.0 * xmod3 as f64 - RR;
                            y13 = mdy[1] as f64 + 256.0 * ymod3 as f64 - RR;
                        }

                        // Compare squared distance against the 400.0 threshold to
                        // avoid two `sqrt` calls per pixel in this warp branch.
                        // (da < 400  <=>  da^2 < 160000).
                        let dax = x1 - x12;
                        let day = y1 - y12;
                        let dbx = x1 - x13;
                        let dby = y1 - y13;
                        if dax * dax + day * day > 160_000.0 || dbx * dbx + dby * dby > 160_000.0 {
                            x12 = x1;
                            y12 = y1;
                            x13 = x1;
                            y13 = y1;
                        }
                    }
                }

                let x1s = x1 * input.xs;
                let y1s = y1 * input.ys;
                let xx_rot = input.xa * x1s + input.ya * y1s;
                let yy_rot = -input.ya * x1s + input.xa * y1s;
                let xx = input.in_x0 + active_scale * (xx_rot + RR + input.xo) / RR;
                let yy = input.in_y0 + active_scale * (yy_rot + RR + input.yo) / RR;

                let x12s = x12 * input.xs;
                let y12s = y12 * input.ys;
                let xxa_rot = input.xa * x12s + input.ya * y12s;
                let yya_rot = -input.ya * x12s + input.xa * y12s;
                let xxa = input.in_x0 + active_scale * (xxa_rot + RR + input.xo) / RR - xx;
                let yya = input.in_y0 + active_scale * (yya_rot + RR + input.yo) / RR - yy;

                let x13s = x13 * input.xs;
                let y13s = y13 * input.ys;
                let xxb_rot = input.xa * x13s + input.ya * y13s;
                let yyb_rot = -input.ya * x13s + input.xa * y13s;
                let xxb = input.in_x0 + active_scale * (xxb_rot + RR + input.xo) / RR - xx;
                let yyb = input.in_y0 + active_scale * (yyb_rot + RR + input.yo) / RR - yy;

                let (mo, m2, m3, m4, m5, m2b, m3b, m4b, m5b) = if input_opaque {
                    (
                        sample_linear_opaque(input_img, xx, yy),
                        sample_linear_opaque(input_img, xx + xxa / 2.0, yy + yya / 2.0),
                        sample_linear_opaque(input_img, xx - xxa / 2.0, yy - yya / 2.0),
                        sample_linear_opaque(input_img, xx + xxb / 2.0, yy + yyb / 2.0),
                        sample_linear_opaque(input_img, xx - xxb / 2.0, yy - yyb / 2.0),
                        sample_linear_opaque(
                            input_img,
                            xx + (xxa + xxb) / 2.0,
                            yy + (yya + yyb) / 2.0,
                        ),
                        sample_linear_opaque(
                            input_img,
                            xx + (xxa - xxb) / 2.0,
                            yy + (yya - yyb) / 2.0,
                        ),
                        sample_linear_opaque(
                            input_img,
                            xx - (xxa + xxb) / 2.0,
                            yy - (yya + yyb) / 2.0,
                        ),
                        sample_linear_opaque(
                            input_img,
                            xx - (xxa - xxb) / 2.0,
                            yy - (yya - yyb) / 2.0,
                        ),
                    )
                } else {
                    (
                        sample_linear_premultiplied(input_img, xx, yy),
                        sample_linear_premultiplied(input_img, xx + xxa / 2.0, yy + yya / 2.0),
                        sample_linear_premultiplied(input_img, xx - xxa / 2.0, yy - yya / 2.0),
                        sample_linear_premultiplied(input_img, xx + xxb / 2.0, yy + yyb / 2.0),
                        sample_linear_premultiplied(input_img, xx - xxb / 2.0, yy - yyb / 2.0),
                        sample_linear_premultiplied(
                            input_img,
                            xx + (xxa + xxb) / 2.0,
                            yy + (yya + yyb) / 2.0,
                        ),
                        sample_linear_premultiplied(
                            input_img,
                            xx + (xxa - xxb) / 2.0,
                            yy + (yya - yyb) / 2.0,
                        ),
                        sample_linear_premultiplied(
                            input_img,
                            xx - (xxa + xxb) / 2.0,
                            yy - (yya + yyb) / 2.0,
                        ),
                        sample_linear_premultiplied(
                            input_img,
                            xx - (xxa - xxb) / 2.0,
                            yy - (yya - yyb) / 2.0,
                        ),
                    )
                };

                let sc = (mo.a * 4.0
                    + (m2.a + m3.a + m4.a + m5.a) * 2.0
                    + (m2b.a + m3b.a + m4b.a + m5b.a))
                    / 16.0;

                let mut mo =
                    (mo * 4.0 + (m2 + m3 + m4 + m5) * 2.0 + (m2b + m3b + m4b + m5b)) / 16.0;

                if sc > 0.0001 {
                    mo.postblend(sc);
                } else {
                    mo.r = 0.0;
                    mo.g = 0.0;
                    mo.b = 0.0;
                    mo.a = 0.0;
                }

                let m_r = mo.r as i32;
                let m_g = mo.g as i32;
                let m_b = mo.b as i32;
                let m_a = mo.a as i32;

                let result_r = dark_pixel[0] as i32
                    + ((light_pixel[0] as i32 - dark_pixel[0] as i32) * m_r) / 255;
                let result_g = dark_pixel[1] as i32
                    + ((light_pixel[1] as i32 - dark_pixel[1] as i32) * m_g) / 255;
                let result_b = dark_pixel[2] as i32
                    + ((light_pixel[2] as i32 - dark_pixel[2] as i32) * m_b) / 255;
                let mut result_a = m_a;

                if (dark_pixel[3] as i32) < result_a {
                    result_a = dark_pixel[3] as i32;
                }

                if result_a > 0 {
                    let idx = x * 4;
                    if result_a > 250 {
                        row[idx] = result_r.clamp(0, 255) as u8;
                        row[idx + 1] = result_g.clamp(0, 255) as u8;
                        row[idx + 2] = result_b.clamp(0, 255) as u8;
                    } else {
                        row[idx] = (row[idx] as i32
                            + ((result_r - row[idx] as i32) * result_a) / 255)
                            .clamp(0, 255) as u8;
                        row[idx + 1] = (row[idx + 1] as i32
                            + ((result_g - row[idx + 1] as i32) * result_a) / 255)
                            .clamp(0, 255) as u8;
                        row[idx + 2] = (row[idx + 2] as i32
                            + ((result_b - row[idx + 2] as i32) * result_a) / 255)
                            .clamp(0, 255) as u8;
                    }
                }
            }
        });

        Ok(())
    }

    fn add_simple(&mut self, input: &Input) -> Result<()> {
        let mapping = self.mapping.as_ref().ok_or(Error::NoMapping)?;

        let active_scale = input.in_scale as f64 / 2.0;
        let off = ((mapping.map2.height() as i32 - mapping.light.height() as i32) / 2) as i32;

        if (mapping.map1.width() as i32) < (mapping.light.width() as i32) {
            return Ok(());
        }

        let out_w = self.out.width();
        let out_h = self.out.height();

        for y in 0..out_h {
            for x in 0..out_w {
                let light_pixel = mapping.light.get_pixel(x, y);
                let dark_pixel = mapping.dark.get_pixel(x, y);

                let map_y = (y as i32 + off) as u32;
                if map_y >= mapping.map1.height() || map_y >= mapping.map2.height() {
                    continue;
                }

                let map_pixel = mapping.map1.get_pixel(x, map_y);
                let sel_pixel = mapping.map2.get_pixel(x, map_y);

                let b_val = map_pixel[2] as i32;
                let ymod = b_val / 16;
                let xmod = b_val % 16;
                let act = map_pixel[3] as i32;
                let x1 = (map_pixel[0] as f64 + 256.0 * xmod as f64 - RR) * input.xs;
                let y1 = (map_pixel[1] as f64 + 256.0 * ymod as f64 - RR) * input.ys;

                let xx_rot = input.xa * x1 + input.ya * y1;
                let yy_rot = -input.ya * x1 + input.xa * y1;
                let xx = input.in_x0 + active_scale * (xx_rot + RR + input.xo) / RR;
                let yy = input.in_y0 + active_scale * (yy_rot + RR + input.yo) / RR;

                let m = input.safe_pixel(xx as i32, yy as i32);

                if sel_pixel[0] == input.layer && act > 25 {
                    let result_r = dark_pixel[0] as i32
                        + ((light_pixel[0] as i32 - dark_pixel[0] as i32) * m[0] as i32) / 255;
                    let result_g = dark_pixel[1] as i32
                        + ((light_pixel[1] as i32 - dark_pixel[1] as i32) * m[1] as i32) / 255;
                    let result_b = dark_pixel[2] as i32
                        + ((light_pixel[2] as i32 - dark_pixel[2] as i32) * m[2] as i32) / 255;
                    let mut result_a = m[3] as i32;

                    if (dark_pixel[3] as i32) < result_a {
                        result_a = dark_pixel[3] as i32;
                    }

                    if result_a > 0 {
                        let out_pixel = self.out.get_pixel_mut(x, y);
                        if result_a > 250 {
                            out_pixel[0] = result_r.clamp(0, 255) as u8;
                            out_pixel[1] = result_g.clamp(0, 255) as u8;
                            out_pixel[2] = result_b.clamp(0, 255) as u8;
                        } else {
                            out_pixel[0] = (out_pixel[0] as i32
                                + ((result_r - out_pixel[0] as i32) * result_a) / 255)
                                .clamp(0, 255) as u8;
                            out_pixel[1] = (out_pixel[1] as i32
                                + ((result_g - out_pixel[1] as i32) * result_a) / 255)
                                .clamp(0, 255) as u8;
                            out_pixel[2] = (out_pixel[2] as i32
                                + ((result_b - out_pixel[2] as i32) * result_a) / 255)
                                .clamp(0, 255) as u8;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Edge smoothing post-process
    fn post(&mut self) -> Result<()> {
        RENDER_COUNT.fetch_add(1, Ordering::SeqCst);

        let mapping = self.mapping.as_ref().ok_or(Error::NoMapping)?;
        let w = self.out.width() as i32;
        let h = self.out.height() as i32;

        if (mapping.map1.width() as i32) < (mapping.light.width() as i32) {
            return Ok(());
        }

        if mapping.map1.width() != mapping.neutral.width() {
            return Ok(());
        }
        if mapping.map2.width() != mapping.neutral.width() {
            return Ok(());
        }

        // The edge-smoothing pass only does work for pixels whose `sel` map
        // channel 2 (the "smooth" flag) is nonzero. When that channel is zero
        // everywhere (as it is for most shipped templates), the entire pass is
        // a no-op — but it still clones the full output image and scans every
        // pixel. Detect that cheaply and bail out early to avoid the clone
        // and the scan.
        if !mapping.has_nonzero_smoothing() {
            return Ok(());
        }

        let pre = self.out.clone();

        for y in 0..h {
            for x in 0..w {
                let xu = x as u32;
                let yu = y as u32;
                let sel_pixel = mapping.map2.get_pixel(xu, yu);

                if sel_pixel[2] > 0 {
                    if x > 0 && y > 0 && x < w - 1 && y < h - 1 {
                        let back1 = pre.get_pixel((x - 1) as u32, yu);
                        let idx1 = mapping.map2.get_pixel((x - 1) as u32, yu);

                        let back2 = pre.get_pixel((x + 1) as u32, yu);
                        let idx2 = mapping.map2.get_pixel((x + 1) as u32, yu);

                        let back3 = pre.get_pixel(xu, (y - 1) as u32);
                        let idx3 = mapping.map2.get_pixel(xu, (y - 1) as u32);

                        let back4 = pre.get_pixel(xu, (y + 1) as u32);
                        let idx4 = mapping.map2.get_pixel(xu, (y + 1) as u32);

                        let mut total = Pixer::new();
                        let mut ct = 0.0;

                        if idx1[2] < 127 {
                            total.add_rgba(back1);
                            ct += 1.0;
                        }
                        if idx2[2] < 127 {
                            total.add_rgba(back2);
                            ct += 1.0;
                        }
                        if idx3[2] < 127 {
                            total.add_rgba(back3);
                            ct += 1.0;
                        }
                        if idx4[2] < 127 {
                            total.add_rgba(back4);
                            ct += 1.0;
                        }

                        if ct > 0.5 {
                            total.div(ct);
                            let out_pixel = self.out.get_pixel_mut(xu, yu);
                            out_pixel[0] = total.r.clamp(0.0, 255.0) as u8;
                            out_pixel[1] = total.g.clamp(0.0, 255.0) as u8;
                            out_pixel[2] = total.b.clamp(0.0, 255.0) as u8;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    pub fn apply(&mut self, inputs: &Inputs) -> Result<()> {
        self.apply_scaled(inputs, -1, -1)
    }

    pub fn apply_scaled(&mut self, inputs: &Inputs, w: i32, h: i32) -> Result<()> {
        self.pre()?;

        match self.quality {
            RenderQuality::None => {}
            RenderQuality::Simple => {
                for input in inputs.iter() {
                    self.add_simple(input)?;
                }
            }
            RenderQuality::Sampled => {
                for input in inputs.iter() {
                    self.add(input)?;
                }
            }
        }

        self.post()?;

        if w > 0 && h > 0 && (w != self.out.width() as i32 || h != self.out.height() as i32) {
            let wi = self.out.width() as i32;
            let hi = self.out.height() as i32;

            let fi = wi as f64 / hi as f64;
            let f = w as f64 / h as f64;

            let (xo, yo, wo, ho) = if fi > f + 0.001 {
                let wo = w;
                let ho = (wo as f64 / fi) as i32;
                let yo = (h - ho) / 2;
                (0, yo, wo, ho)
            } else if fi < f - 0.001 {
                let ho = h;
                let wo = (h as f64 * fi) as i32;
                let xo = (w - wo) / 2;
                (xo, 0, wo, ho)
            } else {
                (0, 0, w, h)
            };

            let mut scaled = RgbaImage::from_pixel(w as u32, h as u32, Rgba([255, 255, 255, 0]));

            for dy in 0..ho {
                for dx in 0..wo {
                    let sx = (dx as f64 * wi as f64 / wo as f64) as u32;
                    let sy = (dy as f64 * hi as f64 / ho as f64) as u32;
                    let sx = sx.min(self.out.width() - 1);
                    let sy = sy.min(self.out.height() - 1);
                    let pixel = *self.out.get_pixel(sx, sy);
                    scaled.put_pixel((xo + dx) as u32, (yo + dy) as u32, pixel);
                }
            }

            for pixel in scaled.pixels_mut() {
                pixel[3] = 255;
            }

            self.out_scaled = Some(scaled);
            self.out = RgbaImage::new(1, 1);
        }

        Ok(())
    }

    pub fn get(&self) -> &RgbaImage {
        self.out_scaled.as_ref().unwrap_or(&self.out)
    }

    pub fn get_mut(&mut self) -> &mut RgbaImage {
        if self.out_scaled.is_some() { self.out_scaled.as_mut().unwrap() } else { &mut self.out }
    }

    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> {
        self.get().save(path)?;
        Ok(())
    }

    pub fn render_count() -> usize {
        RENDER_COUNT.load(Ordering::SeqCst)
    }

    pub fn get_cloud(&self, input: &Input) -> Result<Vec<CloudPoint>> {
        let mapping = self.mapping.as_ref().ok_or(Error::NoMapping)?;

        let active_scale = input.in_scale as f64 / 2.0;
        let off = ((mapping.map2.height() as i32 - mapping.light.height() as i32) / 2) as i32;

        if (mapping.map1.width() as i32) < (mapping.light.width() as i32) {
            return Ok(Vec::new());
        }

        let mut cloud = Vec::new();
        let w = mapping.light.width();
        let h = mapping.light.height();

        for y in 0..h {
            for x in 0..w {
                let light_pixel = mapping.light.get_pixel(x, y);
                let dark_pixel = mapping.dark.get_pixel(x, y);

                let map_y = (y as i32 + off) as u32;
                if map_y >= mapping.map1.height() || map_y >= mapping.map2.height() {
                    continue;
                }

                let map_pixel = mapping.map1.get_pixel(x, map_y);
                let sel_pixel = mapping.map2.get_pixel(x, map_y);

                let b_val = map_pixel[2] as i32;
                let ymod = b_val / 16;
                let xmod = b_val % 16;
                let act = map_pixel[3] as i32;
                let x1 = (map_pixel[0] as f64 + 256.0 * xmod as f64 - RR) * input.xs;
                let y1 = (map_pixel[1] as f64 + 256.0 * ymod as f64 - RR) * input.ys;

                let xx_rot = input.xa * x1 + input.ya * y1;
                let yy_rot = -input.ya * x1 + input.xa * y1;
                let xx = input.in_x0 + active_scale * (xx_rot + RR + input.xo) / RR;
                let yy = input.in_y0 + active_scale * (yy_rot + RR + input.yo) / RR;

                if sel_pixel[0] != 0 && act > 25 {
                    let del = 5i32;
                    let r_diff = (light_pixel[0] as i32 - dark_pixel[0] as i32).abs();
                    let g_diff = (light_pixel[1] as i32 - dark_pixel[1] as i32).abs();
                    let b_diff = (light_pixel[2] as i32 - dark_pixel[2] as i32).abs();

                    if (r_diff > del || g_diff > del || b_diff > del)
                        && dark_pixel[3] > 100
                        && light_pixel[3] > 100
                    {
                        cloud.push(CloudPoint { layer: sel_pixel[0], x: xx, y: yy });
                    }
                }
            }
        }

        Ok(cloud)
    }

    pub fn auto_zoom_input(&self, input: &mut Input) -> Result<bool> {
        let mapping = self.mapping.as_ref().ok_or(Error::NoMapping)?;

        let active_scale = input.in_scale as f64 / 2.0;
        let off = ((mapping.map2.height() as i32 - mapping.light.height() as i32) / 2) as i32;

        if (mapping.map1.width() as i32) < (mapping.light.width() as i32) {
            return Ok(false);
        }

        let mut x_min = input.width() as f64;
        let mut x_max = 0.0f64;
        let mut y_min = input.height() as f64;
        let mut y_max = 0.0f64;

        let w = mapping.light.width();
        let h = mapping.light.height();

        for y in 0..h {
            for x in 0..w {
                let map_y = (y as i32 + off) as u32;
                if map_y >= mapping.map1.height() || map_y >= mapping.map2.height() {
                    continue;
                }

                let map_pixel = mapping.map1.get_pixel(x, map_y);
                let sel_pixel = mapping.map2.get_pixel(x, map_y);

                let b_val = map_pixel[2] as i32;
                let ymod = b_val / 16;
                let xmod = b_val % 16;
                let act = map_pixel[3] as i32;
                let x1 = (map_pixel[0] as f64 + 256.0 * xmod as f64 - RR) * input.xs;
                let y1 = (map_pixel[1] as f64 + 256.0 * ymod as f64 - RR) * input.ys;

                let xx_rot = input.xa * x1 + input.ya * y1;
                let yy_rot = -input.ya * x1 + input.xa * y1;
                let xx = input.in_x0 + active_scale * (xx_rot + RR + input.xo) / RR;
                let yy = input.in_y0 + active_scale * (yy_rot + RR + input.yo) / RR;

                // Only check layer 1 for auto-zoom
                // Only check layer 1 for auto-zoom
                if sel_pixel[0] == 1 && act > 25 {
                    if xx < x_min {
                        x_min = xx;
                    }
                    if xx > x_max {
                        x_max = xx;
                    }
                    if yy < y_min {
                        y_min = yy;
                    }
                    if yy > y_max {
                        y_max = yy;
                    }
                }
            }
        }

        let hh = input.height() as f64;
        if y_max - y_min < hh * 0.75 {
            input.xs *= 2.0;
            input.ys *= 2.0;
            return Ok(true);
        }

        Ok(false)
    }

    pub fn auto_zoom(&self, inputs: &mut Inputs) -> Result<bool> {
        let mut changed = false;
        for input in inputs.iter_mut() {
            if self.auto_zoom_input(input)? {
                changed = true;
            }
        }
        Ok(changed)
    }
}