pixelsrc 0.2.0

Pixelsrc - GenAI-native pixel art format and compiler
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
//! Semantic sprite comparison
//!
//! Provides tools for comparing sprites and detecting differences in:
//! - Dimensions (width, height)
//! - Palette colors (added, removed, changed tokens)
//! - Grid content (row-by-row changes)

use crate::models::{PaletteRef, Sprite, TtpObject};
use crate::parser::parse_stream;
use crate::tokenizer::tokenize;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

/// Result of comparing two sprites
#[derive(Debug, Clone)]
pub struct SpriteDiff {
    /// Change in dimensions, if any
    pub dimension_change: Option<DimensionChange>,
    /// Changes to palette colors
    pub palette_changes: Vec<PaletteChange>,
    /// Changes to grid content
    pub grid_changes: Vec<GridChange>,
    /// Human-readable summary of the diff
    pub summary: String,
}

impl SpriteDiff {
    /// Returns true if there are no differences
    pub fn is_empty(&self) -> bool {
        self.dimension_change.is_none()
            && self.palette_changes.is_empty()
            && self.grid_changes.is_empty()
    }
}

/// Change in sprite dimensions
#[derive(Debug, Clone, PartialEq)]
pub struct DimensionChange {
    /// Old dimensions (width, height)
    pub old: (u32, u32),
    /// New dimensions (width, height)
    pub new: (u32, u32),
}

/// A change to a palette token
#[derive(Debug, Clone, PartialEq)]
pub enum PaletteChange {
    /// Token was added
    Added { token: String, color: String },
    /// Token was removed
    Removed { token: String },
    /// Token color was changed
    Changed { token: String, old_color: String, new_color: String },
}

/// A change to a grid row
#[derive(Debug, Clone)]
pub struct GridChange {
    /// Row number (0-indexed)
    pub row: usize,
    /// Human-readable description of the change
    pub description: String,
}

/// Context for sprite comparison, containing resolved palettes
struct DiffContext {
    /// Palettes from file A (name -> colors)
    palettes_a: HashMap<String, HashMap<String, String>>,
    /// Palettes from file B (name -> colors)
    palettes_b: HashMap<String, HashMap<String, String>>,
}

impl DiffContext {
    fn new() -> Self {
        Self { palettes_a: HashMap::new(), palettes_b: HashMap::new() }
    }

    /// Resolve a palette reference to its color map
    fn resolve_palette(
        &self,
        palette_ref: &PaletteRef,
        palettes: &HashMap<String, HashMap<String, String>>,
    ) -> HashMap<String, String> {
        match palette_ref {
            PaletteRef::Named(name) => palettes.get(name).cloned().unwrap_or_default(),
            PaletteRef::Inline(colors) => colors.clone(),
        }
    }
}

/// Compare two sprites and return their differences
pub fn diff_sprites(
    a: &Sprite,
    b: &Sprite,
    palette_a: &HashMap<String, String>,
    palette_b: &HashMap<String, String>,
) -> SpriteDiff {
    let mut palette_changes = Vec::new();
    let mut grid_changes = Vec::new();

    // Compare dimensions
    let dim_a = get_sprite_dimensions(a);
    let dim_b = get_sprite_dimensions(b);
    let dimension_change =
        if dim_a != dim_b { Some(DimensionChange { old: dim_a, new: dim_b }) } else { None };

    // Compare palettes
    let tokens_a: HashSet<_> = palette_a.keys().collect();
    let tokens_b: HashSet<_> = palette_b.keys().collect();

    // Find removed tokens
    for token in tokens_a.difference(&tokens_b) {
        palette_changes.push(PaletteChange::Removed { token: (*token).clone() });
    }

    // Find added tokens
    for token in tokens_b.difference(&tokens_a) {
        if let Some(color) = palette_b.get(*token) {
            palette_changes
                .push(PaletteChange::Added { token: (*token).clone(), color: color.clone() });
        }
    }

    // Find changed tokens
    for token in tokens_a.intersection(&tokens_b) {
        let color_a = palette_a.get(*token);
        let color_b = palette_b.get(*token);
        if color_a != color_b {
            if let (Some(old), Some(new)) = (color_a, color_b) {
                palette_changes.push(PaletteChange::Changed {
                    token: (*token).clone(),
                    old_color: old.clone(),
                    new_color: new.clone(),
                });
            }
        }
    }

    // Sort palette changes for consistent output
    palette_changes.sort_by(|a, b| {
        let token_a = match a {
            PaletteChange::Added { token, .. } => token,
            PaletteChange::Removed { token } => token,
            PaletteChange::Changed { token, .. } => token,
        };
        let token_b = match b {
            PaletteChange::Added { token, .. } => token,
            PaletteChange::Removed { token } => token,
            PaletteChange::Changed { token, .. } => token,
        };
        token_a.cmp(token_b)
    });

    // Compare grids
    let max_rows = a.grid.len().max(b.grid.len());
    for row_idx in 0..max_rows {
        let row_a = a.grid.get(row_idx);
        let row_b = b.grid.get(row_idx);

        match (row_a, row_b) {
            (Some(ra), Some(rb)) => {
                if ra != rb {
                    let description = describe_row_change(row_idx, ra, rb);
                    grid_changes.push(GridChange { row: row_idx, description });
                }
            }
            (Some(_), None) => {
                grid_changes
                    .push(GridChange { row: row_idx, description: "Row removed".to_string() });
            }
            (None, Some(_)) => {
                grid_changes
                    .push(GridChange { row: row_idx, description: "Row added".to_string() });
            }
            (None, None) => {}
        }
    }

    // Generate summary
    let summary = generate_summary(&dimension_change, &palette_changes, &grid_changes);

    SpriteDiff { dimension_change, palette_changes, grid_changes, summary }
}

/// Get sprite dimensions, computing from grid if not specified
fn get_sprite_dimensions(sprite: &Sprite) -> (u32, u32) {
    if let Some([w, h]) = sprite.size {
        return (w, h);
    }

    // Compute from grid
    let height = sprite.grid.len() as u32;
    let width = sprite
        .grid
        .first()
        .map(|row| {
            let (tokens, _) = tokenize(row);
            tokens.len() as u32
        })
        .unwrap_or(0);

    (width, height)
}

/// Describe the change between two rows
fn describe_row_change(_row_idx: usize, old: &str, new: &str) -> String {
    let (tokens_old, _) = tokenize(old);
    let (tokens_new, _) = tokenize(new);

    // Find what tokens were added/removed/changed
    let set_old: HashSet<_> = tokens_old.iter().collect();
    let set_new: HashSet<_> = tokens_new.iter().collect();

    let added: Vec<_> = set_new.difference(&set_old).collect();
    let removed: Vec<_> = set_old.difference(&set_new).collect();

    if tokens_old.len() != tokens_new.len() {
        return format!("Token count changed: {} → {}", tokens_old.len(), tokens_new.len());
    }

    if !added.is_empty() && !removed.is_empty() {
        let added_str: Vec<_> = added.iter().map(|t| t.as_str()).collect();
        let removed_str: Vec<_> = removed.iter().map(|t| t.as_str()).collect();
        return format!("Tokens changed: -{} +{}", removed_str.join(", "), added_str.join(", "));
    }

    // Count position differences
    let mut diff_positions = Vec::new();
    for (pos, (t_old, t_new)) in tokens_old.iter().zip(tokens_new.iter()).enumerate() {
        if t_old != t_new {
            diff_positions.push(pos);
        }
    }

    if diff_positions.len() <= 3 {
        format!(
            "Tokens changed at position(s): {}",
            diff_positions.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ")
        )
    } else {
        format!("{} tokens changed", diff_positions.len())
    }
}

/// Generate a human-readable summary of the diff
fn generate_summary(
    dimension_change: &Option<DimensionChange>,
    palette_changes: &[PaletteChange],
    grid_changes: &[GridChange],
) -> String {
    let mut parts = Vec::new();

    if let Some(dim) = dimension_change {
        parts
            .push(format!("Dimensions: {}x{} → {}x{}", dim.old.0, dim.old.1, dim.new.0, dim.new.1));
    }

    let added_count =
        palette_changes.iter().filter(|c| matches!(c, PaletteChange::Added { .. })).count();
    let removed_count =
        palette_changes.iter().filter(|c| matches!(c, PaletteChange::Removed { .. })).count();
    let changed_count =
        palette_changes.iter().filter(|c| matches!(c, PaletteChange::Changed { .. })).count();

    if added_count > 0 || removed_count > 0 || changed_count > 0 {
        let mut palette_parts = Vec::new();
        if added_count > 0 {
            palette_parts.push(format!("+{} token(s)", added_count));
        }
        if removed_count > 0 {
            palette_parts.push(format!("-{} token(s)", removed_count));
        }
        if changed_count > 0 {
            palette_parts.push(format!("~{} color(s)", changed_count));
        }
        parts.push(format!("Palette: {}", palette_parts.join(", ")));
    }

    if !grid_changes.is_empty() {
        parts.push(format!("Grid: {} row(s) changed", grid_changes.len()));
    }

    if parts.is_empty() {
        "No differences".to_string()
    } else {
        parts.join(". ")
    }
}

/// Compare two files and return differences for each matching sprite
pub fn diff_files(path_a: &Path, path_b: &Path) -> Result<Vec<(String, SpriteDiff)>, String> {
    // Parse both files
    let file_a =
        File::open(path_a).map_err(|e| format!("Cannot open '{}': {}", path_a.display(), e))?;
    let file_b =
        File::open(path_b).map_err(|e| format!("Cannot open '{}': {}", path_b.display(), e))?;

    let result_a = parse_stream(BufReader::new(file_a));
    let result_b = parse_stream(BufReader::new(file_b));

    // Build context with palettes
    let mut ctx = DiffContext::new();

    // Collect sprites and palettes from file A
    let mut sprites_a: HashMap<String, Sprite> = HashMap::new();
    for obj in &result_a.objects {
        match obj {
            TtpObject::Palette(p) => {
                ctx.palettes_a.insert(p.name.clone(), p.colors.clone());
            }
            TtpObject::Sprite(s) => {
                sprites_a.insert(s.name.clone(), s.clone());
            }
            _ => {}
        }
    }

    // Collect sprites and palettes from file B
    let mut sprites_b: HashMap<String, Sprite> = HashMap::new();
    for obj in &result_b.objects {
        match obj {
            TtpObject::Palette(p) => {
                ctx.palettes_b.insert(p.name.clone(), p.colors.clone());
            }
            TtpObject::Sprite(s) => {
                sprites_b.insert(s.name.clone(), s.clone());
            }
            _ => {}
        }
    }

    // Find sprites to compare (present in both files)
    let mut diffs = Vec::new();

    // All sprite names from both files
    let mut all_names: Vec<_> = sprites_a
        .keys()
        .chain(sprites_b.keys())
        .cloned()
        .collect::<HashSet<_>>()
        .into_iter()
        .collect();
    all_names.sort();

    for name in all_names {
        match (sprites_a.get(&name), sprites_b.get(&name)) {
            (Some(sprite_a), Some(sprite_b)) => {
                // Both files have this sprite - compare them
                let palette_a = ctx.resolve_palette(&sprite_a.palette, &ctx.palettes_a);
                let palette_b = ctx.resolve_palette(&sprite_b.palette, &ctx.palettes_b);
                let diff = diff_sprites(sprite_a, sprite_b, &palette_a, &palette_b);
                diffs.push((name, diff));
            }
            (Some(_), None) => {
                // Sprite only in file A (removed)
                diffs.push((
                    name.clone(),
                    SpriteDiff {
                        dimension_change: None,
                        palette_changes: Vec::new(),
                        grid_changes: Vec::new(),
                        summary: format!("Sprite '{}' removed in second file", name),
                    },
                ));
            }
            (None, Some(_)) => {
                // Sprite only in file B (added)
                diffs.push((
                    name.clone(),
                    SpriteDiff {
                        dimension_change: None,
                        palette_changes: Vec::new(),
                        grid_changes: Vec::new(),
                        summary: format!("Sprite '{}' added in second file", name),
                    },
                ));
            }
            (None, None) => unreachable!(),
        }
    }

    Ok(diffs)
}

/// Format a diff for display
pub fn format_diff(name: &str, diff: &SpriteDiff, file_a: &str, file_b: &str) -> String {
    let mut output = Vec::new();

    output.push(format!("Comparing sprite \"{}\" ({}) vs ({}):", name, file_a, file_b));
    output.push(String::new());

    // Dimensions
    if let Some(dim) = &diff.dimension_change {
        output
            .push(format!("Dimensions: {}x{} → {}x{}", dim.old.0, dim.old.1, dim.new.0, dim.new.1));
    } else if diff.is_empty() {
        output.push("No differences found.".to_string());
        return output.join("\n");
    } else {
        output.push("Dimensions: Same".to_string());
    }

    // Palette changes
    if !diff.palette_changes.is_empty() {
        output.push(String::new());
        output.push("Token changes:".to_string());
        for change in &diff.palette_changes {
            match change {
                PaletteChange::Added { token, color } => {
                    output.push(format!("  + {} = {}", token, color));
                }
                PaletteChange::Removed { token } => {
                    output.push(format!("  - {}", token));
                }
                PaletteChange::Changed { token, old_color, new_color } => {
                    output.push(format!("  ~ {} color: {} → {}", token, old_color, new_color));
                }
            }
        }
    }

    // Grid changes
    if !diff.grid_changes.is_empty() {
        output.push(String::new());
        output.push("Grid changes:".to_string());
        for change in &diff.grid_changes {
            output.push(format!("  Row {}: {}", change.row + 1, change.description));
        }
    }

    // Summary
    output.push(String::new());
    output.push(format!("Summary: {}", diff.summary));

    output.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_sprite(name: &str, palette: HashMap<String, String>, grid: Vec<&str>) -> Sprite {
        Sprite {
            name: name.to_string(),
            size: None,
            palette: PaletteRef::Inline(palette),
            grid: grid.into_iter().map(String::from).collect(),
            metadata: None,
            ..Default::default()
        }
    }

    #[test]
    fn test_identical_sprites() {
        let palette = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{a}".to_string(), "#FF0000".to_string()),
        ]);

        let sprite = make_sprite("test", palette.clone(), vec!["{_}{a}{_}", "{a}{a}{a}"]);

        let diff = diff_sprites(&sprite, &sprite, &palette, &palette);

        assert!(diff.is_empty());
        assert!(diff.dimension_change.is_none());
        assert!(diff.palette_changes.is_empty());
        assert!(diff.grid_changes.is_empty());
    }

    #[test]
    fn test_color_change() {
        let palette_a = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{skin}".to_string(), "#FFCC99".to_string()),
        ]);
        let palette_b = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{skin}".to_string(), "#FFD4AA".to_string()),
        ]);

        let sprite_a = make_sprite("test", palette_a.clone(), vec!["{skin}{skin}"]);
        let sprite_b = make_sprite("test", palette_b.clone(), vec!["{skin}{skin}"]);

        let diff = diff_sprites(&sprite_a, &sprite_b, &palette_a, &palette_b);

        assert!(!diff.is_empty());
        assert_eq!(diff.palette_changes.len(), 1);
        assert!(matches!(
            &diff.palette_changes[0],
            PaletteChange::Changed {
                token,
                old_color,
                new_color
            } if token == "{skin}" && old_color == "#FFCC99" && new_color == "#FFD4AA"
        ));
    }

    #[test]
    fn test_added_token() {
        let palette_a = HashMap::from([("{_}".to_string(), "#00000000".to_string())]);
        let palette_b = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{highlight}".to_string(), "#FFFFFF".to_string()),
        ]);

        let sprite_a = make_sprite("test", palette_a.clone(), vec!["{_}{_}"]);
        let sprite_b = make_sprite("test", palette_b.clone(), vec!["{_}{_}"]);

        let diff = diff_sprites(&sprite_a, &sprite_b, &palette_a, &palette_b);

        assert!(!diff.is_empty());
        assert_eq!(diff.palette_changes.len(), 1);
        assert!(matches!(
            &diff.palette_changes[0],
            PaletteChange::Added { token, color }
            if token == "{highlight}" && color == "#FFFFFF"
        ));
    }

    #[test]
    fn test_removed_token() {
        let palette_a = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{old}".to_string(), "#FF0000".to_string()),
        ]);
        let palette_b = HashMap::from([("{_}".to_string(), "#00000000".to_string())]);

        let sprite_a = make_sprite("test", palette_a.clone(), vec!["{_}{_}"]);
        let sprite_b = make_sprite("test", palette_b.clone(), vec!["{_}{_}"]);

        let diff = diff_sprites(&sprite_a, &sprite_b, &palette_a, &palette_b);

        assert!(!diff.is_empty());
        assert_eq!(diff.palette_changes.len(), 1);
        assert!(matches!(
            &diff.palette_changes[0],
            PaletteChange::Removed { token } if token == "{old}"
        ));
    }

    #[test]
    fn test_dimension_change() {
        let palette = HashMap::from([("{a}".to_string(), "#FF0000".to_string())]);

        let sprite_a = Sprite {
            name: "test".to_string(),
            size: Some([8, 8]),
            palette: PaletteRef::Inline(palette.clone()),
            grid: vec!["{a}".to_string(); 8],
            metadata: None,
            ..Default::default()
        };
        let sprite_b = Sprite {
            name: "test".to_string(),
            size: Some([16, 16]),
            palette: PaletteRef::Inline(palette.clone()),
            grid: vec!["{a}".to_string(); 16],
            metadata: None,
            ..Default::default()
        };

        let diff = diff_sprites(&sprite_a, &sprite_b, &palette, &palette);

        assert!(diff.dimension_change.is_some());
        let dim = diff.dimension_change.unwrap();
        assert_eq!(dim.old, (8, 8));
        assert_eq!(dim.new, (16, 16));
    }

    #[test]
    fn test_grid_change() {
        let palette = HashMap::from([
            ("{_}".to_string(), "#00000000".to_string()),
            ("{a}".to_string(), "#FF0000".to_string()),
            ("{b}".to_string(), "#00FF00".to_string()),
        ]);

        let sprite_a = make_sprite("test", palette.clone(), vec!["{a}{a}", "{_}{_}"]);
        let sprite_b = make_sprite("test", palette.clone(), vec!["{a}{b}", "{_}{_}"]);

        let diff = diff_sprites(&sprite_a, &sprite_b, &palette, &palette);

        assert!(!diff.is_empty());
        assert_eq!(diff.grid_changes.len(), 1);
        assert_eq!(diff.grid_changes[0].row, 0);
    }

    #[test]
    fn test_get_sprite_dimensions_from_size() {
        let sprite = Sprite {
            name: "test".to_string(),
            size: Some([16, 8]),
            palette: PaletteRef::Inline(HashMap::new()),
            grid: vec![],
            metadata: None,
            ..Default::default()
        };
        assert_eq!(get_sprite_dimensions(&sprite), (16, 8));
    }

    #[test]
    fn test_get_sprite_dimensions_from_grid() {
        let sprite = Sprite {
            name: "test".to_string(),
            size: None,
            palette: PaletteRef::Inline(HashMap::new()),
            grid: vec![
                "{a}{b}{c}{d}".to_string(),
                "{a}{b}{c}{d}".to_string(),
                "{a}{b}{c}{d}".to_string(),
            ],
            metadata: None,
            ..Default::default()
        };
        assert_eq!(get_sprite_dimensions(&sprite), (4, 3));
    }
}