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
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
---
phase: 18
title: Sprite Transforms
---

# Phase 18: Sprite Transforms

**Status:** Not Started

**Depends on:** Phase 17 (Colored Grid Display - for `pxl show` visualization)

---

Add transform operations for pixelsrc sprites at two levels:
1. **CLI command** (`pxl transform`) - Source-to-source transformation, outputs new `.pxl`
2. **Format attribute** - Declarative transforms applied at render time (source unchanged)

**Related:** [Colored Grid Display](./colored-grid-display.md) - Use `pxl show` to visualize transforms in terminal

---

## CLI Command: `pxl transform`

### Usage

```bash
pxl transform <input> [options] -o <output>
```

### Flags

| Flag | Description | Example |
|------|-------------|---------|
| `--mirror <axis>` | Mirror horizontally or vertically | `--mirror horizontal`, `--mirror vertical`, `--mirror both` |
| `--rotate <degrees>` | Rotate by 90, 180, or 270 degrees | `--rotate 90` |
| `--flip <axis>` | Alias for mirror (common terminology) | `--flip h`, `--flip v` |
| `--tile <WxH>` | Tile sprite into grid | `--tile 3x2` |
| `--pad <N>` | Add N pixels of transparent padding | `--pad 2` |
| `--outline [color]` | Add 1px outline around opaque pixels | `--outline`, `--outline "#000"` |
| `--crop <X,Y,W,H>` | Extract sub-region | `--crop 0,0,8,8` |
| `--shift <X,Y>` | Circular shift (wrap around) | `--shift 4,0` |
| `-o, --output` | Output file (required) | `-o flipped.pxl` |
| `--sprite <name>` | Transform specific sprite (if multiple) | `--sprite player` |

### Transform Order

Transforms are applied in the order specified:

```bash
# Mirror first, then rotate
pxl transform input.pxl --mirror horizontal --rotate 90 -o output.pxl

# Rotate first, then mirror (different result!)
pxl transform input.pxl --rotate 90 --mirror horizontal -o output.pxl
```

### Output

- Always outputs valid `.pxl` source (not PNG)
- Preserves palette references
- Transforms the grid tokens directly
- Can be piped: `pxl transform --stdin ... | pxl render --stdin`

---

## Format Attribute: `transform`

Declarative transforms applied at render time. Source grid remains unchanged.

### On Sprite (via `source` reference)

Create a transformed sprite that references another:

```json
{"type": "sprite", "name": "arrow_right", "palette": "icons", "grid": ["..."]}
{"type": "sprite", "name": "arrow_left", "source": "arrow_right", "transform": ["mirror-h"]}
{"type": "sprite", "name": "arrow_down", "source": "arrow_right", "transform": ["rotate-90"]}
```

**Rules:**
- `source` references another sprite by name
- `transform` is an array of operations (applied in order)
- Cannot have both `grid` and `source` (mutually exclusive)
- `palette` is optional (inherits from source if omitted)

### On Variant

Variants already reference a sprite; add transforms:

```json
{"type": "sprite", "name": "enemy", "palette": "...", "grid": ["..."]}
{"type": "variant", "name": "enemy_flipped", "sprite": "enemy", "transform": ["mirror-h"]}
{"type": "variant", "name": "enemy_alt", "sprite": "enemy", "palette": "alt_colors", "transform": ["mirror-h"]}
```

### On Composition Layer

Transform individual layers within a composition:

```json
{
  "type": "composition",
  "name": "symmetric_scene",
  "size": [64, 32],
  "layers": [
    {"sprite": "tree", "position": [0, 0]},
    {"sprite": "tree", "position": [48, 0], "transform": ["mirror-h"]},
    {"sprite": "cloud", "position": [16, 0], "transform": ["mirror-v", "rotate:180"]}
  ]
}
```

### On Animation

Transform animation frame sequences:

```json
{"type": "animation", "name": "walk_right", "frames": ["walk_1", "walk_2", "walk_3"], "fps": 8}
{"type": "animation", "name": "walk_right_loop", "source": "walk_right", "transform": ["pingpong"]}
{"type": "animation", "name": "walk_left", "source": "walk_right", "transform": ["mirror-h"]}
```

**Animation transform behavior:**
- **Sprite transforms** (`mirror-h`, `rotate`, `outline`, etc.): Applied to each frame's sprite
- **Sequence transforms** (`pingpong`, `reverse`, `frame-offset`, `hold`): Applied to frame sequence

### Mixed Sprite + Sequence Transforms

Animations can combine both transform types. They're applied in two phases:

**Phase 1: Sprite transforms** (applied to each frame)
**Phase 2: Sequence transforms** (applied to frame order)

```json
{
  "type": "animation",
  "name": "walk_left_loop",
  "source": "walk_right",
  "transform": ["mirror-h", "outline", "pingpong", "hold:0,2"]
}
```

**Execution order:**
1. `mirror-h` → flip each frame horizontally
2. `outline` → add outline to each frame
3. `pingpong` → duplicate frames in reverse (1,2,3 → 1,2,3,2,1)
4. `hold:0,2` → hold first frame for 2 extra ticks

The transform array is processed in order, but sprite transforms are batched and applied first, then sequence transforms are batched and applied second. This ensures predictable results regardless of how you order them in the array.

**Explicit phase control** (optional, for edge cases):
```json
{
  "type": "animation",
  "name": "complex",
  "source": "base",
  "sprite_transform": ["mirror-h", "outline"],
  "sequence_transform": ["pingpong", "hold:0,2"]
}
```

Using separate `sprite_transform` and `sequence_transform` arrays gives explicit control when needed.

---

## Transform Operations

### Parameterized Syntax

Transforms can be specified as strings or objects. Both are valid in the format:

**String syntax** (simple or with colon params):
```json
"transform": ["mirror-h", "rotate:90", "tile:3x2", "pad:4"]
```

**Object syntax** (for complex params):
```json
"transform": [
  "mirror-h",
  {"op": "tile", "w": 3, "h": 2},
  {"op": "outline", "token": "{border}", "width": 2}
]
```

**CLI syntax**:
```bash
pxl transform input.pxl --mirror horizontal --rotate 90 --tile 3x2 --pad 4
```

### Geometric (Grid-Level)

| Operation | Aliases | Description | Params |
|-----------|---------|-------------|--------|
| `mirror-h` | `symmetry-h`, `flip-h` | Mirror horizontally (left↔right) ||
| `mirror-v` | `symmetry-v`, `flip-v` | Mirror vertically (top↔bottom) ||
| `rotate` | `rot` | Rotate clockwise | `degrees`: 90, 180, 270 |

**Examples:**
- `"mirror-h"` or `"symmetry-h"` — same operation
- `"rotate:90"` or `{"op": "rotate", "degrees": 90}`

### Expansion

| Operation | Description | Params |
|-----------|-------------|--------|
| `tile` | Tile sprite into grid | `w`, `h` (or `WxH` string) |
| `pad` | Add transparent padding | `size` (pixels) |
| `crop` | Extract sub-region | `x`, `y`, `w`, `h` |

**Examples:**
- `"tile:3x2"` — tile 3 wide, 2 tall
- `{"op": "pad", "size": 4}` — 4px padding all sides
- `{"op": "crop", "x": 0, "y": 0, "w": 8, "h": 8}` — extract 8x8 region

### Effects

| Operation | Description | Params |
|-----------|-------------|--------|
| `outline` | Add outline around opaque pixels | `token` (optional), `width` (default 1) |
| `shift` | Circular shift (wrap around) | `x`, `y` (pixels) |
| `shadow` | Add drop shadow | `x`, `y`, `token` |

**Examples:**
- `"outline"` — 1px black outline
- `{"op": "outline", "token": "{border}", "width": 2}` — 2px outline using palette token
- `"shift:4,0"` — shift 4px right with wrap

### Animation Transforms

| Operation | Description | Params |
|-----------|-------------|--------|
| `pingpong` | Duplicate frames in reverse (1,2,3 → 1,2,3,2,1) | `exclude_ends` (bool, default false) |
| `reverse` | Reverse frame order ||
| `frame-offset` | Rotate frame order | `offset` (int) |
| `hold` | Duplicate specific frames | `frame`, `count` |

**Examples:**
- `"pingpong"` — creates smooth loop
- `{"op": "pingpong", "exclude_ends": true}` — 1,2,3 → 1,2,3,2 (no duplicate endpoints)
- `"reverse"` — play backwards
- `{"op": "frame-offset", "offset": 2}` — start from frame 2
- `{"op": "hold", "frame": 0, "count": 3}` — hold first frame for 3 ticks

---

## Implementation Plan

### Phase 17.1: Core Transform Module

Create `src/transforms.rs`:

```rust
/// A single transform operation with optional parameters
#[derive(Debug, Clone, PartialEq)]
pub enum Transform {
    // Geometric
    MirrorH,
    MirrorV,
    Rotate { degrees: u16 },  // 90, 180, 270

    // Expansion
    Tile { w: u32, h: u32 },
    Pad { size: u32 },
    Crop { x: u32, y: u32, w: u32, h: u32 },

    // Effects
    Outline { token: Option<String>, width: u32 },
    Shift { x: i32, y: i32 },
    Shadow { x: i32, y: i32, token: Option<String> },

    // Animation (only valid for Animation type)
    Pingpong { exclude_ends: bool },
    Reverse,
    FrameOffset { offset: i32 },
    Hold { frame: usize, count: usize },
}

/// Parse transform from string syntax: "mirror-h", "rotate:90", "tile:3x2"
pub fn parse_transform_str(s: &str) -> Result<Transform, TransformError>;

/// Parse transform from JSON value (string or object)
pub fn parse_transform_value(value: &serde_json::Value) -> Result<Transform, TransformError>;

/// Transform a grid of token rows (for sprites)
pub fn transform_grid(grid: &[String], transforms: &[Transform]) -> Result<Vec<String>, TransformError>;

/// Transform animation frames
pub fn transform_frames(frames: &[String], transforms: &[Transform]) -> Result<Vec<String>, TransformError>;
```

**Alias resolution** (in `parse_transform_str`):
- `symmetry-h``MirrorH`
- `symmetry-v``MirrorV`
- `flip-h``MirrorH`
- `flip-v``MirrorV`
- `rot``Rotate`

**Key functions:**
- `mirror_horizontal(grid)` - Reverse token order in each row
- `mirror_vertical(grid)` - Reverse row order
- `rotate_grid(grid, degrees)` - Transpose + mirror combinations
- `tile_grid(grid, w, h)` - Repeat grid
- `pad_grid(grid, size, token)` - Add border
- `outline_grid(grid, token, width)` - Add outline around opaque
- `pingpong_frames(frames, exclude_ends)` - Duplicate frames in reverse
- `reverse_frames(frames)` - Reverse frame order

### Phase 17.2: CLI Command

Add to `cli.rs`:

```rust
/// Transform sprites (mirror, rotate, tile, etc.)
Transform {
    /// Input file
    input: PathBuf,

    /// Mirror axis (horizontal, vertical, both)
    #[arg(long)]
    mirror: Option<String>,

    /// Rotate degrees (90, 180, 270)
    #[arg(long)]
    rotate: Option<u16>,

    /// Tile pattern (e.g., "2x2", "3x1")
    #[arg(long)]
    tile: Option<String>,

    /// Padding pixels
    #[arg(long)]
    pad: Option<u32>,

    /// Add outline
    #[arg(long)]
    outline: bool,

    /// Crop region (X,Y,W,H)
    #[arg(long)]
    crop: Option<String>,

    /// Shift pixels (X,Y)
    #[arg(long)]
    shift: Option<String>,

    /// Target sprite name
    #[arg(long)]
    sprite: Option<String>,

    /// Output file
    #[arg(short, long)]
    output: PathBuf,

    /// Read from stdin
    #[arg(long)]
    stdin: bool,
}
```

### Phase 17.3: Format Support

Update `models.rs`:

```rust
/// Transform specification - can be string or object in JSON
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TransformSpec {
    String(String),                        // "mirror-h", "rotate:90"
    Object {
        op: String,
        #[serde(flatten)]
        params: HashMap<String, serde_json::Value>,
    },
}

pub struct Sprite {
    pub name: String,
    pub size: Option<[u32; 2]>,
    pub palette: Option<PaletteRef>,
    pub grid: Option<Vec<String>>,         // None if using source
    pub source: Option<String>,            // Reference to another sprite
    pub transform: Option<Vec<TransformSpec>>,
}

pub struct Variant {
    pub name: String,
    #[serde(alias = "base")]             // Backwards compat
    pub source: String,                   // Renamed from 'base', alias kept
    pub palette: Option<PaletteRef>,
    pub transform: Option<Vec<TransformSpec>>,  // NEW
}

pub struct CompositionLayer {
    pub sprite: String,
    pub position: [i32; 2],
    pub transform: Option<Vec<TransformSpec>>,  // NEW
}

pub struct Animation {
    pub name: String,
    pub frames: Option<Vec<String>>,       // None if using source
    pub source: Option<String>,            // Reference to another animation
    pub fps: Option<u32>,
    pub transform: Option<Vec<TransformSpec>>,  // NEW
}

/// User-defined transform
pub struct TransformDef {
    pub name: String,
    pub params: Option<Vec<String>>,              // Parameter names
    pub ops: Option<Vec<TransformSpec>>,          // Simple sequence
    pub compose: Option<Vec<TransformSpec>>,      // Parallel composition
    pub cycle: Option<Vec<Vec<String>>>,          // Per-frame cycling
    pub frames: Option<u32>,                      // For keyframe generation
    pub keyframes: Option<KeyframeSpec>,          // Keyframe data
    pub easing: Option<String>,                   // Default easing
}

/// Keyframe specification - array or object form
#[serde(untagged)]
pub enum KeyframeSpec {
    Array(Vec<Keyframe>),                         // [{frame: 0, shift-y: 0}, ...]
    Properties(HashMap<String, PropertyKeyframes>), // {shift-y: {expr: "..."}}
}

pub struct Keyframe {
    pub frame: u32,
    #[serde(flatten)]
    pub values: HashMap<String, f64>,             // property -> value
}

pub struct PropertyKeyframes {
    pub expr: Option<String>,                     // Math expression
    pub keyframes: Option<Vec<(u32, f64)>>,       // (frame, value) pairs
    pub easing: Option<String>,                   // Per-property easing
}
```

Update `registry.rs` to resolve transforms during sprite/animation resolution.

### Phase 17.4: Render Integration

Update `renderer.rs`:
- Apply transforms after resolving sprite but before rasterizing
- Transform the token grid, not the pixels (preserves quality)

---

## Examples

### CLI: Create mirrored arrow set

```bash
# Start with right-facing arrow
cat arrow_right.pxl
# {"type": "sprite", "name": "arrow", "palette": {...}, "grid": [...]}

# Generate all directions
pxl transform arrow_right.pxl --mirror horizontal -o arrow_left.pxl
pxl transform arrow_right.pxl --rotate 90 -o arrow_down.pxl
pxl transform arrow_right.pxl --rotate 270 -o arrow_up.pxl
```

### Format: Symmetric character

```json
{"type": "palette", "name": "char", "colors": {"{_}": "#00000000", "{x}": "#FFD700"}}
{"type": "sprite", "name": "letter_A_left", "palette": "char", "grid": [
  "{_}{_}{x}",
  "{_}{x}{x}",
  "{x}{_}{x}",
  "{x}{x}{x}",
  "{x}{_}{x}"
]}
{"type": "sprite", "name": "letter_A", "source": "letter_A_left", "transform": ["symmetry-h"]}
```

*Note: `symmetry-h` would append mirrored version to create full symmetric sprite*

### Format: Tiled background

```json
{"type": "sprite", "name": "grass_tile", "palette": "nature", "grid": ["..."]}
{"type": "sprite", "name": "grass_bg", "source": "grass_tile", "transform": ["tile-4x4"]}
```

### Format: Composition with transforms

```json
{
  "type": "composition",
  "name": "forest",
  "size": [128, 64],
  "layers": [
    {"sprite": "tree", "position": [0, 0]},
    {"sprite": "tree", "position": [32, 0], "transform": ["mirror-h"]},
    {"sprite": "tree", "position": [64, 0]},
    {"sprite": "tree", "position": [96, 0], "transform": ["mirror-h"]}
  ]
}
```

---

## Validation & Warnings

### Result Validation

Warn (don't error) when transforms produce unexpected results:

| Condition | Warning |
|-----------|---------|
| Crop outside bounds | `"crop region extends beyond sprite bounds"` |
| Empty result | `"transform resulted in 0x0 sprite"` |
| Missing source | `"source sprite 'foo' not found"` |

### Expansion Warnings

When transforms would create large outputs, warn but allow override:

```
⚠ Warning: Transform chain will expand sprite from 8x8 to 6400x6400 pixels
  - tile:10x10 (8x8 → 80x80)
  - tile:10x10 (80x80 → 800x800)
  - tile:8x8 (800x800 → 6400x6400)

  Use --allow-large to proceed, or reduce expansion.
```

**Thresholds:**
- Warn if result > 1024x1024 pixels
- Warn if result > 10x source size
- Warn if frame count > 100 (for animations)

**CLI override:**
```bash
pxl transform input.pxl --tile 10x10 --tile 10x10 --allow-large -o huge.pxl
```

**Format override** (per-sprite):
```json
{
  "type": "sprite",
  "name": "massive_bg",
  "source": "tile",
  "transform": ["tile:50x50"],
  "allow_large": true
}
```

---

## Resolved Design Decisions

1. **Symmetry operations**: `symmetry-h` and `symmetry-v` are aliases for `mirror-h`/`mirror-v`

2. **Parameterized transforms**: Support both syntaxes:
   - String with colon: `"tile:3x2"`, `"rotate:90"`, `"pad:4"`
   - Object form: `{"op": "tile", "w": 3, "h": 2}`

3. **Animation transforms**: Yes — `pingpong`, `reverse`, `frame-offset`, `hold`

4. **Mixed transforms on animations**: Yes — sprite transforms apply to each frame, sequence transforms apply to frame order. Can use single `transform` array (auto-sorted) or explicit `sprite_transform`/`sequence_transform` arrays.

5. **Expansion warnings**: Warn on large results but allow user override via `--allow-large` (CLI) or `allow_large: true` (format)

6. **Unified `source` attribute**: Use `source` as the canonical name for referencing base sprites/animations. Alias `base` (Variant) for backwards compatibility.

---

## User-Defined Transforms

Users can define custom, reusable, parameterized transforms.

### Named Transform Sequences

Simple reuse of transform chains:

```json
{
  "type": "transform",
  "name": "flip-glow",
  "ops": ["mirror-h", "outline"]
}
```

Usage:
```json
{"type": "sprite", "name": "enemy_left", "source": "enemy_right", "transform": ["flip-glow"]}
```

### Parameterized Transforms

Transforms with configurable values:

```json
{
  "type": "transform",
  "name": "padded-outline",
  "params": ["padding", "outline_width"],
  "ops": [
    {"op": "pad", "size": "${padding}"},
    {"op": "outline", "width": "${outline_width}"}
  ]
}
```

Usage:
```json
{"transform": [{"op": "padded-outline", "padding": 2, "outline_width": 1}]}
```

### Transform Composition

Combine multiple effects in parallel (computed together per-frame):

```json
{
  "type": "transform",
  "name": "chaos-shake",
  "compose": [
    {"op": "shake", "axis": "x", "amount": 2, "rate": 1.0},
    {"op": "shake", "axis": "y", "amount": 1, "rate": 1.5}
  ]
}
```

Both effects calculated and combined each frame, rather than applied sequentially.

### Keyframe Animation Generation

Create animations from static sprites by defining key moments:

```json
{
  "type": "transform",
  "name": "hop",
  "frames": 8,
  "keyframes": [
    {"frame": 0, "shift-y": 0},
    {"frame": 4, "shift-y": -4},
    {"frame": 8, "shift-y": 0}
  ],
  "easing": "ease-out"
}
```

**How it works:**
- Define values at specific frames (keyframes)
- System interpolates frames in between
- Easing controls the interpolation curve

**Apply to static sprite → generates animation:**
```json
{"type": "animation", "name": "coin_hop", "source": "coin", "transform": ["hop"]}
```

### Easing Functions

Control how values interpolate between keyframes:

| Easing | Description | Use Case |
|--------|-------------|----------|
| `linear` | Constant speed | Mechanical movement |
| `ease-in` | Slow start, fast end | Falling, acceleration |
| `ease-out` | Fast start, slow end | Throwing upward, deceleration |
| `ease-in-out` | Slow start and end | Smooth natural motion |
| `bounce` | Overshoots and settles | Landing, UI pop-in |
| `elastic` | Spring-like oscillation | Wobbly, cartoonish |

```
Linear:       ●───●───●───●───●  (constant)
Ease-out:     ●─────●───●──●─●  (decelerating)
Ease-in:      ●─●──●───●─────●  (accelerating)
Ease-in-out:  ●──●────●────●──●  (smooth S-curve)
Bounce:       ●───●─●─●●●        (overshoot + settle)
```

### Mathematical Expressions

For advanced animation, use expressions with math functions:

```json
{
  "type": "transform",
  "name": "accelerating-fall",
  "params": ["gravity", "max_speed"],
  "frames": 12,
  "keyframes": {
    "shift-y": {
      "expr": "min(frame * frame * ${gravity}, ${max_speed})"
    }
  }
}
```

**Available variables:**
- `frame` - Current frame index (0-based)
- `t` - Normalized time (0.0 to 1.0)
- `total_frames` - Total frame count
- Any user-defined `params`

**Available functions:**
- `sin(x)`, `cos(x)`, `tan(x)` - Trigonometry
- `pow(base, exp)` - Exponentiation
- `sqrt(x)` - Square root
- `min(a, b)`, `max(a, b)` - Clamping
- `abs(x)` - Absolute value
- `floor(x)`, `ceil(x)`, `round(x)` - Rounding

### Complex Example: Spiral

Multi-param transform with exponential decay:

```json
{
  "type": "transform",
  "name": "spiral-in",
  "params": ["start_radius", "decay", "spin_rate"],
  "frames": 16,
  "keyframes": {
    "shift-x": {"expr": "${start_radius} * pow(${decay}, frame) * cos(frame * ${spin_rate})"},
    "shift-y": {"expr": "${start_radius} * pow(${decay}, frame) * sin(frame * ${spin_rate})"}
  }
}
```

Usage:
```json
{
  "type": "animation",
  "name": "coin_collect",
  "source": "coin",
  "transform": [
    {"op": "spiral-in", "start_radius": 8, "decay": 0.85, "spin_rate": 0.5}
  ]
}
```

Creates a 16-frame animation of the coin spiraling inward.

### Composed Keyframe Animations

Combine multiple keyframe effects:

```json
{
  "type": "transform",
  "name": "dramatic-entrance",
  "frames": 12,
  "compose": [
    {
      "keyframes": [
        {"frame": 0, "shift-y": -16},
        {"frame": 8, "shift-y": 0}
      ],
      "easing": "bounce"
    },
    {
      "keyframes": [
        {"frame": 0, "scale": 0.5},
        {"frame": 12, "scale": 1.0}
      ],
      "easing": "ease-out"
    }
  ]
}
```

Object drops in from above (with bounce) while scaling up.

### Per-Frame Transform Cycling

Apply different transforms to each frame in a cycle:

```json
{
  "type": "transform",
  "name": "shiver",
  "cycle": [
    ["shift:1,0"],
    ["shift:-1,0"],
    ["shift:0,1"],
    ["shift:0,-1"]
  ]
}
```

Frame 0 → shift right, frame 1 → shift left, frame 2 → shift down, frame 3 → shift up, frame 4 → shift right (repeats).

---

## Future Extensions

- **Symmetry generation**: `extend-h`, `extend-v` (append mirrored copy to create full sprite from half)
- **Color transforms**: `invert`, `grayscale`, `hue-shift`
- **Blend modes**: For composition layers
- **Conditional transforms**: Apply based on variant state

---

## Task Dependency Diagram

```
                           SPRITE TRANSFORMS TASK FLOW
═══════════════════════════════════════════════════════════════════════════════

PREREQUISITE
┌─────────────────────────────────────────────────────────────────────────────┐
│                           Phase 0 Complete                                  │
└─────────────────────────────────────────────────────────────────────────────┘
WAVE 1 (Foundation)
┌─────────────────────────────────────────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                            TRF-1                                    │    │
│  │               Transform Module Foundation                           │    │
│  │               (src/transforms.rs)                                   │    │
│  │               - Transform enum                                      │    │
│  │               - parse_transform_str/value                           │    │
│  │               - lib.rs export                                       │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘
WAVE 2 (Transform Types - Parallel)
┌─────────────────────────────────────────────────────────────────────────────┐
│  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐ │
│  │    TRF-2      │  │    TRF-3      │  │    TRF-4      │  │    TRF-5      │ │
│  │  Geometric    │  │  Expansion    │  │   Effect      │  │  Animation    │ │
│  │  Transforms   │  │  Transforms   │  │  Transforms   │  │  Transforms   │ │
│  │  - mirror     │  │  - tile       │  │  - outline    │  │  - pingpong   │ │
│  │  - rotate     │  │  - pad        │  │  - shift      │  │  - reverse    │ │
│  │               │  │  - crop       │  │  - shadow     │  │  - hold       │ │
│  └───────────────┘  └───────────────┘  └───────────────┘  └───────────────┘ │
│                                                                     │       │
│  ┌──────────────────────────────────────────────────────────────────┼─────┐ │
│  │                            TRF-7                                 │     │ │
│  │               Format Support Models                              │     │ │
│  │               - TransformSpec                                    │     │ │
│  │               - Update Sprite/Variant/Animation                  │     │ │
│  └──────────────────────────────────────────────────────────────────┼─────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
            │                                                         │
            ▼                                                         ▼
WAVE 3 (Integration)
┌─────────────────────────────────────────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                            TRF-6                                    │    │
│  │               Transform CLI Command                                 │    │
│  │               (pxl transform with all flags)                        │    │
│  │               Needs: TRF-2, TRF-3, TRF-4, TRF-5                      │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                            TRF-8                                    │    │
│  │               Format Support Registry                               │    │
│  │               (resolve transforms in registry)                      │    │
│  │               Needs: TRF-7                                          │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘
            │                                     │
            │                                     ▼
            │         ┌─────────────────────────────────────────────────────┐
            │         │                    TRF-9                            │
            │         │           Render Integration                        │
            │         │           Needs: TRF-7, TRF-8                        │
            │         └─────────────────────────────────────────────────────┘
            │                                     │
            │         ┌─────────────────────────────────────────────────────┐
            │         │                    TRF-10                           │
            │         │           User-Defined Transforms                   │
            │         │           - TransformDef, keyframes                 │
            │         │           - Easing, expressions                     │
            │         │           Needs: TRF-8                              │
            │         └─────────────────────────────────────────────────────┘
            │                                     │
            ▼                                     ▼
WAVE 4 (Testing)
┌─────────────────────────────────────────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                            TRF-11                                   │    │
│  │                    Transform Test Suite                             │    │
│  │                    (unit + integration tests)                       │    │
│  │                    Needs: TRF-6, TRF-9, TRF-10                       │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘
WAVE 5 (Documentation)
┌─────────────────────────────────────────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                            TRF-12                                   │    │
│  │                    Transform Documentation                          │    │
│  │                    - prime output                                   │    │
│  │                    - format spec                                    │    │
│  │                    - demo.sh examples                               │    │
│  │                    Needs: TRF-11                                    │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘

═══════════════════════════════════════════════════════════════════════════════

PARALLELIZATION SUMMARY:
┌─────────────────────────────────────────────────────────────────────────────┐
│  Wave 1: TRF-1                               (1 task)                       │
│  Wave 2: TRF-2 + TRF-3 + TRF-4 + TRF-5 + TRF-7  (5 tasks in parallel)       │
│  Wave 3: TRF-6 (after TRF-2-5) + TRF-8 (after TRF-7)  (2 parallel tracks)   │
│          TRF-9 (after TRF-7,8) + TRF-10 (after TRF-8)                       │
│  Wave 4: TRF-11                              (1 task, needs TRF-6,9,10)     │
│  Wave 5: TRF-12                              (1 task)                       │
└─────────────────────────────────────────────────────────────────────────────┘

CRITICAL PATH: TRF-1 → TRF-2 → TRF-6 → TRF-11 → TRF-12
          OR:  TRF-1 → TRF-7 → TRF-8 → TRF-10 → TRF-11 → TRF-12

BEADS CREATION ORDER:
  1. TRF-1 (no deps)
  2. TRF-2, TRF-3, TRF-4, TRF-5, TRF-7 (dep: TRF-1)
  3. TRF-6 (dep: TRF-2,3,4,5), TRF-8 (dep: TRF-7)
  4. TRF-9 (dep: TRF-7,8), TRF-10 (dep: TRF-8)
  5. TRF-11 (dep: TRF-6,9,10)
  6. TRF-12 (dep: TRF-11)
```

---

## Tasks

### Task TRF-1: Transform Module Foundation

**Wave:** 1

Create the core transform infrastructure.

**Deliverables:**
- New file `src/transforms.rs`:
  ```rust
  /// A single transform operation with optional parameters
  #[derive(Debug, Clone, PartialEq)]
  pub enum Transform {
      // Geometric
      MirrorH,
      MirrorV,
      Rotate { degrees: u16 },

      // Expansion
      Tile { w: u32, h: u32 },
      Pad { size: u32 },
      Crop { x: u32, y: u32, w: u32, h: u32 },

      // Effects
      Outline { token: Option<String>, width: u32 },
      Shift { x: i32, y: i32 },
      Shadow { x: i32, y: i32, token: Option<String> },

      // Animation
      Pingpong { exclude_ends: bool },
      Reverse,
      FrameOffset { offset: i32 },
      Hold { frame: usize, count: usize },
  }

  /// Parse transform from string syntax
  pub fn parse_transform_str(s: &str) -> Result<Transform, TransformError>;

  /// Parse transform from JSON value
  pub fn parse_transform_value(value: &serde_json::Value) -> Result<Transform, TransformError>;
  ```
- Update `src/lib.rs` to add `pub mod transforms;`

**Verification:**
```bash
cargo build
cargo test transforms
```

**Dependencies:** Phase 0 complete

---

### Task TRF-2: Geometric Transforms

**Wave:** 2 (parallel with TRF-3, TRF-4, TRF-5, TRF-7)

Implement mirror and rotate operations.

**Deliverables:**
- In `src/transforms.rs`:
  ```rust
  /// Mirror grid horizontally (reverse token order in each row)
  pub fn mirror_horizontal(grid: &[String]) -> Vec<String>

  /// Mirror grid vertically (reverse row order)
  pub fn mirror_vertical(grid: &[String]) -> Vec<String>

  /// Rotate grid by 90, 180, or 270 degrees clockwise
  pub fn rotate_grid(grid: &[String], degrees: u16) -> Result<Vec<String>, TransformError>
  ```

**Verification:**
```bash
cargo test mirror
cargo test rotate
```

**Dependencies:** Task TRF-1

---

### Task TRF-3: Expansion Transforms

**Wave:** 2 (parallel with TRF-2, TRF-4, TRF-5, TRF-7)

Implement tile, pad, and crop operations.

**Deliverables:**
- In `src/transforms.rs`:
  ```rust
  /// Tile grid into WxH repetitions
  pub fn tile_grid(grid: &[String], w: u32, h: u32) -> Vec<String>

  /// Add transparent padding around grid
  pub fn pad_grid(grid: &[String], size: u32, token: &str) -> Vec<String>

  /// Extract sub-region from grid
  pub fn crop_grid(grid: &[String], x: u32, y: u32, w: u32, h: u32) -> Result<Vec<String>, TransformError>
  ```

**Verification:**
```bash
cargo test tile
cargo test pad
cargo test crop
```

**Dependencies:** Task TRF-1

---

### Task TRF-4: Effect Transforms

**Wave:** 2 (parallel with TRF-2, TRF-3, TRF-5, TRF-7)

Implement outline, shift, and shadow operations.

**Deliverables:**
- In `src/transforms.rs`:
  ```rust
  /// Add outline around opaque pixels
  pub fn outline_grid(grid: &[String], token: Option<&str>, width: u32) -> Vec<String>

  /// Circular shift (wrap around)
  pub fn shift_grid(grid: &[String], x: i32, y: i32) -> Vec<String>

  /// Add drop shadow
  pub fn shadow_grid(grid: &[String], x: i32, y: i32, token: Option<&str>) -> Vec<String>
  ```

**Verification:**
```bash
cargo test outline
cargo test shift
cargo test shadow
```

**Dependencies:** Task TRF-1

---

### Task TRF-5: Animation Transforms

**Wave:** 2 (parallel with TRF-2, TRF-3, TRF-4, TRF-7)

Implement frame sequence operations.

**Deliverables:**
- In `src/transforms.rs`:
  ```rust
  /// Duplicate frames in reverse (1,2,3 → 1,2,3,2,1)
  pub fn pingpong_frames(frames: &[String], exclude_ends: bool) -> Vec<String>

  /// Reverse frame order
  pub fn reverse_frames(frames: &[String]) -> Vec<String>

  /// Rotate frame order by offset
  pub fn frame_offset(frames: &[String], offset: i32) -> Vec<String>

  /// Hold specific frame for extra ticks
  pub fn hold_frame(frames: &[String], frame: usize, count: usize) -> Vec<String>
  ```

**Verification:**
```bash
cargo test pingpong
cargo test reverse_frames
cargo test frame_offset
cargo test hold
```

**Dependencies:** Task TRF-1

---

### Task TRF-6: Transform CLI Command

**Wave:** 3 (after TRF-2, TRF-3, TRF-4, TRF-5)

Add `pxl transform` command with all flags.

**Deliverables:**
- Update `src/cli.rs`:
  ```rust
  /// Transform sprites (mirror, rotate, tile, etc.)
  Transform {
      input: PathBuf,
      #[arg(long)] mirror: Option<String>,
      #[arg(long)] rotate: Option<u16>,
      #[arg(long)] tile: Option<String>,
      #[arg(long)] pad: Option<u32>,
      #[arg(long)] outline: bool,
      #[arg(long)] crop: Option<String>,
      #[arg(long)] shift: Option<String>,
      #[arg(long)] sprite: Option<String>,
      #[arg(short, long)] output: PathBuf,
      #[arg(long)] stdin: bool,
      #[arg(long)] allow_large: bool,
  }
  ```

**Verification:**
```bash
./target/release/pxl transform examples/arrow.pxl --mirror horizontal -o arrow_left.pxl
./target/release/pxl transform examples/tile.pxl --tile 3x3 -o tiled.pxl
./target/release/pxl transform examples/sprite.pxl --rotate 90 --outline -o output.pxl
```

**Dependencies:** Tasks TRF-2, TRF-3, TRF-4, TRF-5

---

### Task TRF-7: Format Support Models

**Wave:** 2 (parallel with TRF-2, TRF-3, TRF-4, TRF-5)

Add transform support to format types.

**Deliverables:**
- Update `src/models.rs`:
  ```rust
  #[derive(Debug, Clone, Serialize, Deserialize)]
  #[serde(untagged)]
  pub enum TransformSpec {
      String(String),
      Object { op: String, #[serde(flatten)] params: HashMap<String, Value> },
  }

  // Add to Sprite, Variant, CompositionLayer, Animation:
  pub transform: Option<Vec<TransformSpec>>,

  // Add source field to Sprite:
  pub source: Option<String>,
  ```

**Verification:**
```bash
cargo build
cargo test models
```

**Dependencies:** Task TRF-1

---

### Task TRF-8: Format Support Registry

**Wave:** 3 (after TRF-7)

Resolve transforms during sprite/animation resolution.

**Deliverables:**
- Update `src/registry.rs`:
  - Resolve `source` references for sprites
  - Apply transforms when resolving sprites/animations
  - Handle transform chains

**Verification:**
```bash
cargo test registry
./target/release/pxl render examples/transformed.pxl
```

**Dependencies:** Task TRF-7

---

### Task TRF-9: Render Integration

**Wave:** 3 (after TRF-7, TRF-8)

Apply transforms during rendering.

**Deliverables:**
- Update `src/renderer.rs`:
  - Apply transforms after resolving sprite but before rasterizing
  - Transform the token grid, not the pixels

**Verification:**
```bash
./target/release/pxl render examples/with_transforms.pxl -o output.png
```

**Dependencies:** Tasks TRF-7, TRF-8

---

### Task TRF-10: User-Defined Transforms

**Wave:** 3 (after TRF-8)

Support custom reusable transforms with keyframes.

**Deliverables:**
- Add `TransformDef` type to `src/models.rs`
- Implement keyframe interpolation
- Implement easing functions (linear, ease-in, ease-out, etc.)
- Implement expression evaluation for advanced animations

**Verification:**
```bash
cargo test keyframe
cargo test easing
./target/release/pxl render examples/custom_transform.pxl -o output.gif
```

**Dependencies:** Task TRF-8

---

### Task TRF-11: Transform Test Suite

**Wave:** 4 (after TRF-6, TRF-9, TRF-10)

Comprehensive tests for all transform functionality.

**Deliverables:**
- `tests/transform_tests.rs`:
  - Unit tests for each transform operation
  - Edge cases (empty grids, single-pixel, etc.)
  - Transform composition tests
- `tests/cli_integration.rs` additions:
  - CLI transform command tests
  - Round-trip tests
- Test fixtures in `tests/fixtures/valid/`

**Verification:**
```bash
cargo test transforms
cargo test --test cli_integration transform
```

**Dependencies:** Tasks TRF-6, TRF-9, TRF-10

---

### Task TRF-12: Transform Documentation

**Wave:** 5 (after TRF-11)

Update all documentation for transform feature.

**Deliverables:**
- Update `src/prime.rs` with transform commands and examples
- Update `docs/spec/format.md` with transform syntax
- Update `demo.sh` with transform examples

**Verification:**
```bash
./target/release/pxl prime | grep transform
grep "transform" docs/spec/format.md
./demo.sh  # Should run without errors
```

**Dependencies:** Task TRF-11

---

## Verification Summary

```bash
# 1. All existing tests pass
cargo test

# 2. Transform module tests pass
cargo test transforms

# 3. CLI command works
./target/release/pxl transform examples/arrow.pxl --mirror horizontal -o left.pxl
./target/release/pxl transform examples/tile.pxl --tile 3x3 -o tiled.pxl
./target/release/pxl transform examples/sprite.pxl --rotate 90 --pad 2 --outline -o output.pxl

# 4. Format transforms work
./target/release/pxl render examples/with_transforms.pxl -o output.png

# 5. Chain transforms work
./target/release/pxl transform input.pxl --mirror h --rotate 90 --tile 2x2 -o output.pxl

# 6. Documentation updated
./target/release/pxl prime | grep transform
```

---

## Success Criteria

1. All transform operations work as documented
2. CLI `pxl transform` supports all flags and chains transforms correctly
3. Format `transform` attribute works on sprites, variants, compositions, and animations
4. User-defined transforms support keyframes and easing
5. Large expansion warnings work with `--allow-large` override
6. All tests pass
7. Documentation reflects new capabilities