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
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
|
//! manim-style animation, written as code. A scene is one file, of one of
//! two kinds, drawn by the same player.
//!
//! **Compiled** (`Scene`): `construct` runs once, at comptime, recording
//! objects and plays, which become keyframes per object (a `from` pose, a
//! `to` pose, a time span and an easing). The whole timeline is data before
//! the first frame, and drawing an instant is a lookup and a `tween.lerp`.
//! Updaters (`always`) add motion on top.
//!
//! pub const scene = anim.Scene(construct);
//!
//! fn construct(s: *anim.Builder) void {
//! const title = s.typst("= Hello", .{ .y = -200 });
//! s.play(.{title.write()}, .{});
//! s.always(title, bob, .{20});
//! s.play(.{anim.camera(.{ .zoom = 1.5 })}, .{ .ease = anim.ease.outBack });
//! }
//!
//! fn bob(now: anim.Now, height: f32) anim.Pose {
//! var p = now.pose;
//! p.y += height * @sin(now.t * 3);
//! return p;
//! }
//!
//! **Live** (`Live`): `frame` runs every frame, at runtime, with the time
//! and the input. The same calls add objects and play animations, but each
//! `play` takes effect at once, against `s.t`, so the code after it can read
//! and change what shows: updaters are plain code, and a scene can follow
//! the mouse or any runtime data. Its Typst sources sit in a namespace, for
//! the build to find.
//!
//! pub const typst = struct {
//! pub const title = "= Hello";
//! };
//! pub const scene = anim.Live(frame, typst);
//!
//! fn frame(s: *anim.Frame) void {
//! const title = s.typst(typst.title, .{ .y = -200 });
//! s.play(.{title.write()}, .{});
//! s.pause();
//! s.pose(title).x = s.pointer[0];
//! }
//!
//! Both are functions of time (and a live one, of the input too), so
//! scrubbing, seeking and hot reload are free.
//!
//! **Talks** are live scenes with gates: `pause` waits for the presenter's
//! click, `gate` for any condition, and time runs on while they wait, so
//! loops (`loop`) and plays already running carry on. A talk is a function
//! of its time and of the gates opened so far, both plain data in a `Deck`,
//! which the stock player keeps and any sketch can keep in its own State.
//!
//! Animations, as methods of an object handle: `write`, `create`,
//! `fadeIn`, `fadeOut`, `transformInto` (morph), `move`, `scaleTo`,
//! `rotate`, `indicate`; and `camera`, `Value.to`. `play` runs a tuple of
//! them together, with options `.seconds`, `.ease` (any `fn (f32) f32`,
//! `ease.smooth` by default) and `.lag` (manim's lag ratio, 0 by
//! default). `wait` moves time on; `pause`
//! makes what follows wait for a click, like a slide step. Typst is
//! compiled at build time (`sb.addScene`), from the scene's
//! `typst_sources`.
//!
//! **Custom objects** (`s.custom(&data, .{ .x = 100 })`) are drawn by the
//! scene's own code, with `sketch.Frame` commands, in their place among
//! the others: same camera, same pose, same animations (see `Placed`).
const std = @import("std");
const sk = @import("sketch");
const vector = @import("vector");
const tween = sk.tween;
const Drawing = vector.Drawing;
pub const ease = tween.ease;
pub const Painter = @import("Painter.zig");
// manim's palette.
pub const blue: u32 = 0x58c4dd;
pub const teal: u32 = 0x5cd0b3;
pub const green: u32 = 0x83c167;
pub const yellow: u32 = 0xf7d96f;
pub const gold: u32 = 0xf0ac5f;
pub const red: u32 = 0xfc6255;
pub const maroon: u32 = 0xc55f73;
pub const purple: u32 = 0x9a72ac;
pub const white: u32 = 0xece6e2;
pub const background: u32 = 0x1c1c1f;
/// Where an object is and how much of it shows. Every field interpolates.
pub const Pose = struct {
x: f32 = 0,
y: f32 = 0,
scale: f32 = 1,
rotation: f32 = 0,
opacity: f32 = 1,
visible: bool = false,
/// Write/create progress: 0 nothing, 1 complete.
drawn: f32 = 1,
reveal: Reveal = .write,
/// Morph progress into `into`.
morph: f32 = 0,
into: u16 = none,
/// Indicate's glow.
highlight: f32 = 0,
pub const none = std.math.maxInt(u16);
pub const Reveal = enum { write, create };
};
pub const Camera = struct {
x: f32 = 0,
y: f32 = 0,
zoom: f32 = 1,
rotation: f32 = 0,
};
pub const Ease = *const fn (f32) f32;
pub fn Key(comptime P: type) type {
return struct {
start: f32,
end: f32,
ease: Ease,
from: P,
to: P,
pub fn at(k: @This(), t: f32) P {
return tween.lerp(k.from, k.to, k.ease(tween.progress(t, k.start, k.end)));
}
};
}
// ---------------------------------------------------------------------------
// Objects
pub const Source = union(enum) {
svg: []const u8,
/// Typst source, compiled to SVG at build time.
typst: []const u8,
rect: struct { w: f32, h: f32, radius: f32 = 0 },
circle: struct { r: f32 },
line: struct { dx: f32, dy: f32, arrow: bool = false },
polygon: []const [2]f32,
/// Drawn by the scene's own code (`custom`).
custom: Custom,
/// The shapes of `of` whose bounds' centre lies in `area` (in `of`'s
/// units), around the area's centre (`part`).
part: struct { of: *const Object, area: vector.geom.Rect },
};
/// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`,
/// `f.text`): runtime data as a table, a memory grid, a code panel. It is
/// an object like the others: posed, animated and ordered among them.
/// `draw` runs while the frame is painted, when the object shows
/// (`visible`, `opacity` above 0); `ctx` must live until then (a live
/// scene's `s.arena` does).
pub const Custom = struct {
draw: *const fn (ctx: *const anyopaque, f: *sk.Frame, at: Placed) void,
ctx: *const anyopaque,
};
/// What a custom object's `draw` gets: where it stands at this instant.
pub const Placed = struct {
/// Scene time, in seconds.
t: f32,
/// The object's pose now. `x`, `y`, `scale` and `rotation` are in `xf`
/// already; `opacity` is for `draw` to honour (`pen` and `text` do),
/// and so are `drawn` (0 to 1 as a `write` or `create` plays: reveal
/// what you like by it) and `highlight` (`indicate`).
pose: Pose,
/// The object's units (its origin where the pose puts it, y down) to
/// canvas pixels: the camera, then the pose.
xf: sk.math.Affine,
/// Canvas pixels per unit of the object: for text sizes.
scale: f32,
/// Scene units to canvas pixels: the camera alone.
stage: sk.math.Affine,
/// Every `Value` of the scene, now.
values: []const f32,
pub fn value(p: Placed, v: Value) f32 {
return p.values[@backingInt(v)];
}
/// `base` in the object's units and at its opacity, for `sk.draw`:
/// `sk.draw.rect(f, r, at.pen(.{ .fill = .white }))`.
pub fn pen(p: Placed, base: sk.draw.Pen) sk.draw.Pen {
var out = base.transformed(p.xf);
if (out.fill) |c| out.fill = p.faded(c);
if (out.stroke) |c| out.stroke = p.faded(c);
return out;
}
/// `f.text` in the object's units and at its opacity: `x, y` is the
/// line's top left, scale 1 a 13-unit font. Text does not turn: a
/// rotated object's text moves with it and stays level.
pub fn text(p: Placed, f: *sk.Frame, x: f32, y: f32, scale: f32, bytes: []const u8, ink: sk.Color) void {
const at = p.xf.apply(.{ x, y });
f.text(at[0], at[1], scale * p.scale, bytes, p.faded(ink));
}
/// `text` in another face (`sk.Face`: bold or italic mono, the sans).
pub fn textIn(p: Placed, f: *sk.Frame, face: sk.Face, x: f32, y: f32, scale: f32, bytes: []const u8, ink: sk.Color) void {
const at = p.xf.apply(.{ x, y });
f.textIn(face, at[0], at[1], scale * p.scale, bytes, p.faded(ink));
}
/// The width and line height `textIn` covers, in the object's units.
pub fn textSizeIn(p: Placed, f: *sk.Frame, face: sk.Face, scale: f32, bytes: []const u8) [2]f32 {
const size = f.host.textSizeIn(face, scale * p.scale, bytes);
return .{ size[0] / p.scale, size[1] / p.scale };
}
/// The width and line height `text` covers, in the object's units.
pub fn textSize(p: Placed, f: *sk.Frame, scale: f32, bytes: []const u8) [2]f32 {
const size = f.host.textSize(scale * p.scale, bytes);
return .{ size[0] / p.scale, size[1] / p.scale };
}
/// `ink` at the pose's opacity.
pub fn faded(p: Placed, ink: sk.Color) sk.Color {
return ink.alphaFloat(@as(f32, @floatFromInt(ink.a)) / 255 * p.pose.opacity);
}
};
pub const Object = struct {
source: Source,
pose: Pose,
/// Styling for primitives; SVGs keep their own.
fill: ?u32 = null,
stroke: ?u32 = null,
width: f32 = 4,
/// Areas whose shapes parts were taken from it: it draws the rest.
cut: []const vector.geom.Rect = &.{},
/// Identifies what the object looks like (not where it is), to cache
/// its drawing by.
pub fn id(o: Object) u64 {
var h: std.hash.Wyhash = .init(0);
h.update(@tagName(o.source));
switch (o.source) {
.svg, .typst => |text| h.update(text),
.polygon => |points| h.update(std.mem.sliceAsBytes(points)),
.rect => |r| h.update(std.mem.asBytes(&[_]f32{ r.w, r.h, r.radius })),
.circle => |c| h.update(std.mem.asBytes(&c.r)),
.line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })),
.custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })),
.part => |p| {
h.update(std.mem.asBytes(&p.of.id()));
h.update(std.mem.asBytes(&p.area));
},
}
h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 }));
h.update(std.mem.asBytes(&o.width));
h.update(std.mem.sliceAsBytes(o.cut));
return h.final();
}
/// What a part or a cut object is drawn from (`sift`): the object
/// without its cut, or the one a part was taken from.
pub fn whole(o: Object) Object {
if (o.cut.len == 0) return o.source.part.of.*;
var w = o;
w.cut = &.{};
return w;
}
};
/// Pose fields to animate towards; the others stay as they are.
pub const Target = struct {
x: ?f32 = null,
y: ?f32 = null,
scale: ?f32 = null,
rotation: ?f32 = null,
opacity: ?f32 = null,
fn of(fields: anytype) Target {
var t: Target = .{};
inline for (@typeInfo(@TypeOf(fields)).@"struct".field_names) |name| @field(t, name) = @field(fields, name);
return t;
}
fn apply(t: Target, p: *Pose) void {
inline for (@typeInfo(Target).@"struct".field_names) |name| if (@field(t, name)) |v| {
@field(p, name) = v;
};
}
};
pub const CameraTarget = struct {
x: ?f32 = null,
y: ?f32 = null,
zoom: ?f32 = null,
rotation: ?f32 = null,
};
/// A handle to an object added to a scene.
pub const Obj = enum(u16) {
_,
pub fn write(o: Obj) Animation {
return .{ .write = o };
}
pub fn create(o: Obj) Animation {
return .{ .create = o };
}
pub fn fadeIn(o: Obj) Animation {
return .{ .fade_in = o };
}
pub fn fadeOut(o: Obj) Animation {
return .{ .fade_out = o };
}
/// Morphs into `other`, which takes over when done.
pub fn transformInto(o: Obj, other: Obj) Animation {
return .{ .transform = .{ .from = o, .to = other } };
}
/// Towards any of `x`, `y`, `scale`, `rotation`, `opacity`.
pub fn move(o: Obj, to: anytype) Animation {
return .{ .move = .{ .obj = o, .to = .of(to) } };
}
pub fn scaleTo(o: Obj, scale: f32) Animation {
return .{ .move = .{ .obj = o, .to = .{ .scale = scale } } };
}
/// By `radians`, from wherever it is.
pub fn rotate(o: Obj, radians: f32) Animation {
return .{ .rotate = .{ .obj = o, .by = radians } };
}
pub fn indicate(o: Obj) Animation {
return .{ .indicate = o };
}
};
/// A number animated along the timeline, for updaters (or live code) to read.
pub const Value = enum(u16) {
_,
pub fn to(v: Value, target: f32) Animation {
return .{ .value = .{ .value = v, .to = target } };
}
};
/// Moves the camera towards any of `x`, `y`, `zoom`, `rotation`.
pub fn camera(to: anytype) Animation {
var t: CameraTarget = .{};
inline for (@typeInfo(@TypeOf(to)).@"struct".field_names) |name| @field(t, name) = @field(to, name);
return .{ .camera = t };
}
pub const Animation = union(enum) {
write: Obj,
create: Obj,
fade_in: Obj,
fade_out: Obj,
transform: struct { from: Obj, to: Obj },
move: struct { obj: Obj, to: Target },
rotate: struct { obj: Obj, by: f32 },
indicate: Obj,
camera: CameraTarget,
value: struct { value: Value, to: f32 },
};
/// What an updater sees each frame.
pub const Now = struct {
/// Scene time, in seconds.
t: f32,
/// The object's pose from the timeline (and earlier updaters).
pose: Pose,
values: []const f32,
pub fn value(n: Now, v: Value) f32 {
return n.values[@backingInt(v)];
}
};
pub const Updater = struct {
obj: Obj,
/// From this time on.
since: f32,
update: *const fn (Now) Pose,
};
// ---------------------------------------------------------------------------
// Playing animations, the same for both kinds of scene
const Play = struct {
start: f32,
seconds: f32,
ease: Ease,
lag: f32,
animations: []const Animation,
/// `play`'s options: `.seconds` (1, or 2 with a write in it), `.ease`
/// (`ease.smooth`) and `.lag` (0: all start together).
fn of(start: f32, animations: []const Animation, options: anytype) Play {
const O = @TypeOf(options);
var seconds: f32 = 1;
for (animations) |a| if (a == .write) {
seconds = 2;
};
if (@hasField(O, "seconds")) seconds = options.seconds;
return .{
.start = start,
.seconds = seconds,
.ease = if (@hasField(O, "ease")) options.ease else ease.smooth,
.lag = if (@hasField(O, "lag")) options.lag else 0,
.animations = animations,
};
}
/// Animation `i`'s key. With a lag, manim's lag ratio: each animation
/// starts `lag` of its length after the one before, and all are as long
/// as lets the last end with the play.
fn key(p: Play, comptime P: type, i: usize, from: P, to: P, with: ?Ease) Key(P) {
const each = p.seconds / (1 + p.lag * @as(f32, @floatFromInt(@max(p.animations.len, 1) - 1)));
const start = p.start + @as(f32, @floatFromInt(i)) * p.lag * each;
return .{ .start = start, .end = start + each, .ease = with orelse p.ease, .from = from, .to = to };
}
};
/// Animations as an array, from a tuple or an array.
fn list(animations: anytype) [count(@TypeOf(animations))]Animation {
var out: [count(@TypeOf(animations))]Animation = undefined;
inline for (animations, 0..) |a, i| out[i] = a;
return out;
}
fn count(comptime T: type) usize {
return switch (@typeInfo(T)) {
.array => |a| a.len,
else => @typeInfo(T).@"struct".field_names.len,
};
}
/// What a play does to one object: the pose it starts from and ends on,
/// timed as its first animation in the play (`at`).
const Change = struct { obj: u16, at: usize, from: Pose, to: Pose, ease: ?Ease = null };
/// The changes `animations`, played together, make to objects standing in
/// their `settled` poses. `buf` needs two per animation.
fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) []Change {
var n: usize = 0;
for (animations, 0..) |a, at| switch (a) {
.write, .create => |o| {
const c = touch(buf, &n, at, settled, o);
c.from.visible = true;
c.from.drawn = 0;
if (c.from.opacity <= 0) c.from.opacity = 1;
c.from.reveal = if (a == .write) .write else .create;
c.to = c.from;
c.to.drawn = 1;
},
.fade_in => |o| {
const c = touch(buf, &n, at, settled, o);
c.from.visible = true;
c.from.drawn = 1;
c.from.opacity = 0;
c.to = c.from;
c.to.opacity = 1;
},
.fade_out => |o| {
const c = touch(buf, &n, at, settled, o);
c.to.opacity = 0;
c.to.visible = false;
},
.transform => |t| {
const c = touch(buf, &n, at, settled, t.from);
c.from.into = @backingInt(t.to);
c.from.morph = 0;
c.to = c.from;
c.to.morph = 1;
c.to.visible = false;
const d = touch(buf, &n, at, settled, t.to);
d.from.visible = false;
d.to = d.from;
d.to.visible = true;
d.to.drawn = 1;
d.to.opacity = 1;
},
.move => |m| m.to.apply(&touch(buf, &n, at, settled, m.obj).to),
.rotate => |r| touch(buf, &n, at, settled, r.obj).to.rotation += r.by,
.indicate => |o| {
const c = touch(buf, &n, at, settled, o);
c.to.scale *= 1.2;
c.to.highlight = 1;
c.ease = ease.thereAndBack;
},
.camera, .value => {},
};
return buf[0..n];
}
fn touch(buf: []Change, n: *usize, at: usize, settled: []const Pose, o: Obj) *Change {
const i = @backingInt(o);
for (buf[0..n.*]) |*c| if (c.obj == i) return c;
buf[n.*] = .{ .obj = i, .at = at, .from = settled[i], .to = settled[i] };
n.* += 1;
return &buf[n.* - 1];
}
/// Where `animations` leave a camera standing at `view`, if they move it,
/// and the first of them that does (`Change.at`).
fn aim(view: Camera, animations: []const Animation) ?struct { to: Camera, at: usize } {
var out: ?Camera = null;
var first: usize = 0;
for (animations, 0..) |a, i| if (a == .camera) {
if (out == null) first = i;
var c = out orelse view;
inline for (@typeInfo(CameraTarget).@"struct".field_names) |name| if (@field(a.camera, name)) |v| {
@field(c, name) = v;
};
out = c;
};
return .{ .to = out orelse return null, .at = first };
}
/// Adding objects, the same for both kinds of scene (anything with `add`).
const adding = struct {
/// An SVG document, placed by `at`'s fields: `x`, `y`, `scale`,
/// `rotation`, `opacity`, `visible`.
fn svg(s: anytype, bytes: []const u8, at: anytype) Obj {
return s.add(.{ .source = .{ .svg = bytes }, .pose = tween.toward(Pose{}, at, 1) });
}
/// Typst markup (after the scene's `typst_preamble`), placed like `svg`.
fn typst(s: anytype, source: []const u8, at: anytype) Obj {
return s.add(.{ .source = .{ .typst = source }, .pose = tween.toward(Pose{}, at, 1) });
}
/// Primitives take their size, `fill`, `stroke`, `width`, and the pose
/// fields, in one literal.
fn rect(s: anytype, spec: anytype) Obj {
return s.add(primitive(.{ .rect = .{ .w = spec.w, .h = spec.h, .radius = number(spec, "radius", 0) } }, spec));
}
fn circle(s: anytype, spec: anytype) Obj {
return s.add(primitive(.{ .circle = .{ .r = spec.r } }, spec));
}
fn line(s: anytype, spec: anytype) Obj {
return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy } }, spec));
}
fn arrow(s: anytype, spec: anytype) Obj {
return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy, .arrow = true } }, spec));
}
/// `.points` is a slice of `[2]f32`, kept by reference.
fn polygon(s: anytype, spec: anytype) Obj {
return s.add(primitive(.{ .polygon = spec.points }, spec));
}
/// An object drawn by `data.draw(f, placed)` (`f: *sk.Frame`, `placed:
/// Placed`), placed like `svg`. `data` is a pointer, kept: in a live
/// scene to something in `s.arena`, which the code after the plays may
/// still change; in a compiled one to a constant.
fn custom(s: anytype, data: anytype, at: anytype) Obj {
const T = @typeInfo(@TypeOf(data)).pointer.child;
const erased = struct {
fn draw(ctx: *const anyopaque, f: *sk.Frame, placed: Placed) void {
@as(*const T, @ptrCast(@alignCast(ctx))).draw(f, placed);
}
};
return s.add(.{ .source = .{ .custom = .{ .draw = erased.draw, .ctx = data } }, .pose = tween.toward(Pose{}, at, 1) });
}
};
/// `part`'s area: `.x`, `.y` its centre (0 when left out), `.w`, `.h`.
fn areaOf(spec: anytype) vector.geom.Rect {
const w: f32 = spec.w;
const h: f32 = spec.h;
return .{ .x = number(spec, "x", 0) - w / 2, .y = number(spec, "y", 0) - h / 2, .w = w, .h = h };
}
/// Where a part whose origin is `c` in its object's units stands, when the
/// object stands at `p`.
fn partPose(p: Pose, c: vector.geom.Vec) Pose {
var q = p;
const at = vector.geom.Affine.rotate(p.rotation).apply(c * vector.geom.splat(p.scale));
q.x += at[0];
q.y += at[1];
q.into = Pose.none;
q.morph = 0;
return q;
}
fn primitive(source: Source, spec: anytype) Object {
var pose: Pose = .{};
inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| {
if (@hasField(@TypeOf(spec), name)) @field(pose, name) = @field(spec, name);
}
return .{
.source = source,
.pose = pose,
.fill = if (@hasField(@TypeOf(spec), "fill")) spec.fill else null,
.stroke = if (@hasField(@TypeOf(spec), "stroke")) spec.stroke else null,
.width = number(spec, "width", 4),
};
}
fn number(spec: anytype, comptime name: []const u8, default: f32) f32 {
return if (@hasField(@TypeOf(spec), name)) @field(spec, name) else default;
}
// ---------------------------------------------------------------------------
// Compiled scenes
/// What `construct` receives. Every method runs at comptime.
pub const Builder = struct {
objects: []const Object = &.{},
values: []const f32 = &.{},
plays: []const Play = &.{},
updaters: []const Updater = &.{},
/// Parts, each following its object through the plays laid before it
/// was taken.
follows: []const Follow = &.{},
/// Where the next play starts.
cursor: f32 = 0,
const Follow = struct { obj: u16, of: u16, plays: usize, at: vector.geom.Vec };
pub fn add(b: *Builder, o: Object) Obj {
b.objects = b.objects ++ .{o};
return @fromBackingInt(@intCast(b.objects.len - 1));
}
/// The shapes of `of` whose bounds' centre lies in `area` (`.x`, `.y`
/// its centre, `.w`, `.h`, in `of`'s units: those of `s.rect` laid
/// over `of` at the origin, at scale 1), as an object of their own,
/// around the area's centre; `of` draws the rest. It stands where they
/// stood and shows as `of` does after the plays so far; plays after it
/// move one or the other. A shape goes to the first part that takes it.
pub fn part(b: *Builder, of: Obj, area: anytype) Obj {
const i = @backingInt(of);
const r = areaOf(area);
const whole = b.objects[i];
var cut = whole;
cut.cut = whole.cut ++ .{r};
b.objects = b.objects[0..i] ++ .{cut} ++ b.objects[i + 1 ..];
const o = b.add(.{ .source = .{ .part = .{ .of = &whole, .area = r } }, .pose = partPose(whole.pose, r.center()) });
b.follows = b.follows ++ .{Follow{ .obj = @backingInt(o), .of = i, .plays = b.plays.len, .at = r.center() }};
return o;
}
pub const svg = adding.svg;
pub const typst = adding.typst;
pub const rect = adding.rect;
pub const circle = adding.circle;
pub const line = adding.line;
pub const arrow = adding.arrow;
pub const polygon = adding.polygon;
pub const custom = adding.custom;
pub fn value(b: *Builder, initial: f32) Value {
b.values = b.values ++ .{initial};
return @fromBackingInt(@intCast(b.values.len - 1));
}
/// Runs `animations` (a tuple or an array) together, then moves time
/// past them.
pub fn play(b: *Builder, animations: anytype, options: anytype) void {
const all = list(animations);
const p = Play.of(b.cursor, &all, options);
b.plays = b.plays ++ .{p};
b.cursor += p.seconds;
}
pub fn wait(b: *Builder, seconds: f32) void {
b.cursor += seconds;
}
/// From now on, every frame, `o`'s pose is `update(now, args...)`:
/// `args` (a tuple) is bound here, like a closure's captures, so an
/// updater can follow other objects or read values.
pub fn always(b: *Builder, o: Obj, comptime update: anytype, comptime args: anytype) void {
const bound = struct {
fn call(now: Now) Pose {
return @call(.auto, update, .{now} ++ args);
}
};
b.updaters = b.updaters ++ .{Updater{ .obj = o, .since = b.cursor, .update = bound.call }};
}
};
/// Runs `construct` at comptime and compiles what it recorded.
pub fn Scene(comptime construct: fn (*Builder) void) type {
@setEvalBranchQuota(10_000_000);
const recorded = comptime blk: {
var b: Builder = .{};
construct(&b);
break :blk b;
};
const n = recorded.objects.len;
// Play the timeline once, at comptime, recording keyframes.
const compiled = comptime blk: {
var poses: [n]Pose = undefined;
for (&poses, recorded.objects) |*p, o| p.* = o.pose;
var values: [recorded.values.len]f32 = recorded.values[0..recorded.values.len].*;
var view: Camera = .{};
var keys: [n][]const Key(Pose) = @splat(&.{});
var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{});
var camera_keys: []const Key(Camera) = &.{};
var marks: []const f32 = &.{};
for (recorded.plays, 0..) |play, played| {
var buf: [2 * play.animations.len]Change = undefined;
var touched: [n]bool = @splat(false);
for (changes(&buf, &poses, play.animations)) |c| {
const k = play.key(Pose, c.at, c.from, c.to, c.ease);
keys[c.obj] = keys[c.obj] ++ .{k};
poses[c.obj] = k.at(k.end);
touched[c.obj] = true;
}
for (recorded.follows) |f| if (played < f.plays and touched[f.of]) {
var k = keys[f.of][keys[f.of].len - 1];
k.from = partPose(k.from, f.at);
k.to = partPose(k.to, f.at);
keys[f.obj] = keys[f.obj] ++ .{k};
poses[f.obj] = k.at(k.end);
touched[f.obj] = true;
};
for (play.animations, 0..) |a, at| if (a == .value) {
const i = @backingInt(a.value.value);
value_keys[i] = value_keys[i] ++ .{play.key(f32, at, values[i], a.value.to, null)};
values[i] = a.value.to;
};
if (aim(view, play.animations)) |to| {
camera_keys = camera_keys ++ .{play.key(Camera, to.at, view, to.to, null)};
view = to.to;
}
marks = marks ++ .{play.start};
}
break :blk .{ .keys = keys, .value_keys = value_keys, .camera_keys = camera_keys, .marks = marks };
};
const frozen_objects = recorded.objects[0..n].*;
const frozen_values = recorded.values[0..recorded.values.len].*;
const frozen_updaters = recorded.updaters[0..recorded.updaters.len].*;
const frozen_keys = compiled.keys;
const frozen_value_keys = compiled.value_keys;
const frozen_camera_keys = compiled.camera_keys[0..compiled.camera_keys.len].*;
const frozen_marks = compiled.marks[0..compiled.marks.len].*;
const typst_list = comptime blk: {
var out: []const []const u8 = &.{};
for (recorded.objects) |o| if (o.source == .typst) {
out = out ++ .{o.source.typst};
};
break :blk out[0..out.len].*;
};
return struct {
pub const objects: []const Object = &frozen_objects;
pub const initial_values: []const f32 = &frozen_values;
pub const updaters: []const Updater = &frozen_updaters;
pub const keys: [n][]const Key(Pose) = frozen_keys;
pub const value_keys = frozen_value_keys;
pub const camera_keys: []const Key(Camera) = &frozen_camera_keys;
/// Start times of every play, for chapter-style seeking.
pub const marks: []const f32 = &frozen_marks;
pub const duration: f32 = recorded.cursor;
/// Every Typst source, for the build step that compiles them.
pub const typst_sources: []const []const u8 = &typst_list;
/// The scene at `now`, for the player.
pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot {
const poses = try arena.alloc(Pose, n);
const morphs = try arena.alloc(Morph, n);
for (poses, morphs, 0..) |*p, *m, i| {
p.* = pose(i, now.t);
if (p.into != Pose.none) if (key(i, now.t)) |k| {
m.* = .{ .from = k.from, .to = pose(p.into, k.end) };
};
}
return .{ .t = now.t, .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = &.{} };
}
/// The key shaping object `i` at `t`: the last one to have started.
pub fn key(i: usize, t: f32) ?Key(Pose) {
return latest(Pose, keys[i], t);
}
/// Every value at `t`.
pub fn values(t: f32) [frozen_values.len]f32 {
var out = frozen_values;
for (&out, value_keys) |*v, own| if (latest(f32, own, t)) |k| {
v.* = k.at(t);
};
return out;
}
/// Where object `i` is at `t`: the timeline, then its updaters.
pub fn pose(i: usize, t: f32) Pose {
var p = if (key(i, t)) |k| k.at(t) else objects[i].pose;
if (updaters.len > 0) {
const now_values = values(t);
for (updaters) |u| if (@backingInt(u.obj) == i and t >= u.since) {
p = u.update(.{ .t = t, .pose = p, .values = &now_values });
};
}
return p;
}
/// The camera at `t`.
pub fn view(t: f32) Camera {
return if (latest(Camera, camera_keys, t)) |k| k.at(t) else .{};
}
};
}
fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) {
var found: ?Key(P) = null;
for (keys) |k| {
if (k.start > t) break;
found = k;
}
return found;
}
pub const BuildError = error{ TypstNotCompiled, CustomHasNoDrawing } || vector.svg.Error;
/// The drawing of an object, centered on its origin, in pixels at scale 1.
/// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs.
pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) BuildError!Drawing {
if (o.source == .part or o.cut.len > 0) return sift(arena, try build(arena, o.whole(), compiled), o);
const document: ?[]const u8 = switch (o.source) {
.svg => |bytes| bytes,
.typst => |source| compiled.find(source) orelse return error.TypstNotCompiled,
.custom => return error.CustomHasNoDrawing,
else => null,
};
if (document) |bytes| {
{
const d = try vector.svg.parse(arena, bytes);
// Keep the SVG's pixel size (Typst's points are 4/3 px), centered.
const s = if (d.view.w > 0) d.width / d.view.w else 1;
const c = d.view.center();
const centring = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1]));
const shapes = try arena.dupe(Drawing.Shape, d.shapes);
for (shapes) |*shape| {
shape.transform = centring.mul(shape.transform);
if (shape.clip) |*q| for (q) |*v| {
v.* = centring.apply(v.*);
};
}
var out = d;
out.shapes = shapes;
out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s };
return out;
}
}
var b: Drawing.Builder = .init(arena);
var style: Drawing.Style = .{
.fill = if (o.fill) |c| .{ .color = color(c) } else .none,
.stroke = if (o.stroke) |c| .{ .color = color(c) } else .none,
.stroke_width = o.width,
.cap = .round,
.join = .round,
};
switch (o.source) {
.rect => |r| try b.rect(.{ .x = -r.w / 2, .y = -r.h / 2, .w = r.w, .h = r.h }, r.radius),
.circle => |c| try b.ellipse(.{ 0, 0 }, c.r, c.r),
.polygon => |pts| {
var points: [64]vector.geom.Vec = undefined;
for (pts[0..@min(pts.len, 64)], 0..) |p, i| points[i] = p;
try b.polyline(points[0..@min(pts.len, 64)], true);
},
.line => |l| {
const a: vector.geom.Vec = .{ -l.dx / 2, -l.dy / 2 };
const z: vector.geom.Vec = .{ l.dx / 2, l.dy / 2 };
try b.lineTo(a, z);
try b.closeSubpath(false);
if (l.arrow) {
try b.endShape(.identity, style);
// The head, filled in the stroke color.
const dir = vector.geom.normalize(z - a);
const n = vector.geom.perp(dir);
const head = @max(o.width * 3, 12);
const back = z - dir * vector.geom.splat(head);
try b.polyline(&.{ z + dir * vector.geom.splat(o.width), back + n * vector.geom.splat(head / 2), back - n * vector.geom.splat(head / 2) }, true);
style.fill = style.stroke;
style.stroke = .none;
}
},
.svg, .typst, .custom, .part => unreachable,
}
try b.endShape(.identity, style);
const r = @max(extent(o.source), 1);
return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r);
}
/// The drawing of a part, or of an object parts were taken from, out of
/// `whole`, the drawing of `o.whole()`: the shapes whose bounds' centre
/// lies in the part's area, around the area's centre; or those in none of
/// the object's `cut`, where they were. Shapes and geometry are shared.
pub fn sift(arena: std.mem.Allocator, whole: Drawing, o: Object) error{OutOfMemory}!Drawing {
const areas: []const vector.geom.Rect = if (o.cut.len > 0) o.cut else &.{o.source.part.area};
const keep_inside = o.cut.len == 0;
const c: vector.geom.Vec = if (keep_inside) areas[0].center() else .{ 0, 0 };
const to = vector.geom.Affine.translate(-c[0], -c[1]);
var shapes: std.ArrayList(Drawing.Shape) = .empty;
for (whole.shapes) |shape| {
const b = whole.shapeBounds(shape);
const mid = shape.transform.apply((b.min + b.max) * vector.geom.splat(0.5));
const inside = for (areas) |a| {
if (mid[0] >= a.x and mid[0] < a.x + a.w and mid[1] >= a.y and mid[1] < a.y + a.h) break true;
} else false;
if (inside != keep_inside) continue;
var kept = shape;
kept.transform = to.mul(shape.transform);
if (kept.clip) |*q| for (q) |*v| {
v.* = to.apply(v.*);
};
try shapes.append(arena, kept);
}
var out = whole;
out.shapes = shapes.items;
if (keep_inside) out.view = .{ .x = -areas[0].w / 2, .y = -areas[0].h / 2, .w = areas[0].w, .h = areas[0].h };
return out;
}
fn extent(s: Source) f32 {
return switch (s) {
.rect => |r| @max(r.w, r.h) / 2,
.circle => |c| c.r,
.line => |l| @max(@abs(l.dx), @abs(l.dy)) / 2,
.polygon => |pts| blk: {
var m: f32 = 0;
for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1])));
break :blk m;
},
.svg, .typst, .custom, .part => 0,
};
}
/// `0xRRGGBB`, or `0xRRGGBBAA` when above 24 bits.
pub fn color(c: u32) Drawing.Color {
const rgba: u32 = if (c > 0xffffff) c else (c << 8) | 0xff;
return .{
@as(f32, @floatFromInt(rgba >> 24)) / 255,
@as(f32, @floatFromInt((rgba >> 16) & 0xff)) / 255,
@as(f32, @floatFromInt((rgba >> 8) & 0xff)) / 255,
@as(f32, @floatFromInt(rgba & 0xff)) / 255,
};
}
// ---------------------------------------------------------------------------
// Live scenes
/// A live scene: `frame` runs every frame, at runtime, and the scene is
/// whatever it builds. `typst` is a namespace whose declarations are the
/// Typst sources `frame` uses, or a tuple of them (`sources`), for the
/// build to compile.
pub fn Live(comptime frame_fn: fn (*Frame) void, comptime typst: anytype) type {
return struct {
pub const frame = frame_fn;
pub const typst_sources: []const []const u8 = sources(typst);
/// The scene at `now`, `frame` run once, its gates all closed.
pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot {
var s: Frame = .{ .t = now.t, .in = now.in, .pointer = now.pointer, .arena = arena };
frame_fn(&s);
return s.shot();
}
};
}
/// Every declaration of `namespaces` (a namespace, or a tuple of them),
/// each a Typst source, for the build to compile: a sketch that draws
/// Typst itself declares `pub const scene = struct { pub const
/// typst_sources = anim.sources(.{typst}); };` for `sb.addTypst`.
pub fn sources(comptime namespaces: anytype) []const []const u8 {
const frozen = comptime blk: {
const all = if (@TypeOf(namespaces) == type) .{namespaces} else namespaces;
var out: []const []const u8 = &.{};
for (all) |namespace| for (@typeInfo(namespace).@"struct".decl_names) |name| {
out = out ++ .{@as([]const u8, @field(namespace, name))};
};
break :blk out[0..out.len].*;
};
return &frozen;
}
/// What a live scene's `frame` gets: the time, the input, and the same calls
/// as `Builder`, which take effect at `t` right away.
pub const Frame = struct {
/// Scene time, in seconds. In a talk it runs on through gates.
t: f32,
in: *const sk.Input,
/// The mouse, in scene units from the canvas center (before the scene's
/// own camera).
pointer: [2]f32,
/// Lives for this frame.
arena: std.mem.Allocator,
/// The gates opened so far, in order (the deck's log).
gates: []const Gate = &.{},
/// The presenter asked for the next step (`Ask.next`) and nothing has
/// taken it yet: the `pause` it reaches opens. Code laid out before
/// that pause takes the click for itself by setting it false (a widget
/// the click landed on).
next: bool = false,
/// This update's events, pointer positions in scene units
/// (`Deck.pointer`): in the deck's `update` run only, empty when drawn.
events: []const sk.Event = &.{},
/// Where `gate` writes a gate that opens: the deck's `update` run only.
log: ?*Log = null,
/// Open every gate laid before `slides` slides, `hold` after it is
/// reached (or now, if that is later): `Ask.end`, `next_slide`, export.
lay: ?Lay = null,
/// A gate opened in this run: one click opens one gate.
opened: bool = false,
/// Where the first gate still closed is laid.
closed: ?f32 = null,
/// Where the next play starts.
cursor: f32 = 0,
objects: std.ArrayList(Object) = .empty,
/// Each object's pose after every play so far, and as it shows at `t`.
settled: std.ArrayList(Pose) = .empty,
shown: std.ArrayList(Pose) = .empty,
morphs: std.ArrayList(Morph) = .empty,
values: std.ArrayList(struct { settled: f32, shown: f32 }) = .empty,
settled_view: Camera = .{},
view: Camera = .{},
marks: std.ArrayList(f32) = .empty,
/// Where each gate is laid: the cursor when the code reached it.
stops: std.ArrayList(f32) = .empty,
/// Where each `slide` begins, and how many gates come before it.
slides: std.ArrayList(struct { at: f32, gates: u32 }) = .empty,
const Lay = struct { hold: f32, slides: usize };
pub fn add(s: *Frame, o: Object) Obj {
s.push(&s.objects, o);
s.push(&s.settled, o.pose);
s.push(&s.shown, o.pose);
s.push(&s.morphs, undefined);
return @fromBackingInt(@intCast(s.objects.items.len - 1));
}
pub const svg = adding.svg;
pub const typst = adding.typst;
pub const rect = adding.rect;
pub const circle = adding.circle;
pub const line = adding.line;
pub const arrow = adding.arrow;
pub const polygon = adding.polygon;
pub const custom = adding.custom;
/// The shapes of `of` inside `area`, as an object of their own, showing
/// as `of` does now; `of` draws the rest (see `Builder.part`).
pub fn part(s: *Frame, of: Obj, area: anytype) Obj {
const i = @backingInt(of);
const r = areaOf(area);
const whole = s.new(s.objects.items[i]);
s.objects.items[i].cut = std.mem.concat(s.arena, vector.geom.Rect, &.{ whole.cut, &.{r} }) catch @panic("anim: out of memory");
const o = s.add(.{ .source = .{ .part = .{ .of = whole, .area = r } }, .pose = partPose(whole.pose, r.center()) });
s.settled.items[@backingInt(o)] = partPose(s.settled.items[i], r.center());
s.shown.items[@backingInt(o)] = partPose(s.shown.items[i], r.center());
return o;
}
pub fn value(s: *Frame, initial: f32) Value {
s.push(&s.values, .{ .settled = initial, .shown = initial });
return @fromBackingInt(@intCast(s.values.items.len - 1));
}
/// Value `v` at `t`.
pub fn get(s: *const Frame, v: Value) f32 {
return s.values.items[@backingInt(v)].shown;
}
/// How `o` shows at `t`, to change in place. Code runs in order: a later
/// play that has started by `t` sets it again.
pub fn pose(s: *Frame, o: Obj) *Pose {
return &s.shown.items[@backingInt(o)];
}
/// The camera at `t`, to change in place, like `pose`.
pub fn camera(s: *Frame) *Camera {
return &s.view;
}
/// Runs `animations` (a tuple or an array) together from the cursor, as
/// they stand at `t`, then moves the cursor past them.
pub fn play(s: *Frame, animations: anytype, options: anytype) void {
const all = list(animations);
var buf: [2 * all.len]Change = undefined;
s.playAll(&all, &buf, Play.of(s.cursor, &all, options));
}
/// `play`, of animations known at runtime; `buf` holds two changes each.
fn playAll(s: *Frame, all: []const Animation, buf: []Change, p: Play) void {
const touched = changes(buf, s.settled.items, all);
for (touched) |c| {
const k = p.key(Pose, c.at, c.from, c.to, c.ease);
s.settled.items[c.obj] = k.at(k.end);
if (s.t >= k.start) s.shown.items[c.obj] = k.at(s.t);
}
// A morph ends where its target settles.
for (touched) |c| if (c.from.into != Pose.none and s.t >= p.key(Pose, c.at, c.from, c.to, c.ease).start) {
s.morphs.items[c.obj] = .{ .from = c.from, .to = s.settled.items[c.from.into] };
};
for (all, 0..) |a, at| if (a == .value) {
const v = &s.values.items[@backingInt(a.value.value)];
const k = p.key(f32, at, v.settled, a.value.to, null);
v.settled = a.value.to;
if (s.t >= k.start) v.shown = k.at(s.t);
};
if (aim(s.settled_view, all)) |to| {
const k = p.key(Camera, to.at, s.settled_view, to.to, null);
s.settled_view = to.to;
if (s.t >= k.start) s.view = k.at(s.t);
}
s.push(&s.marks, p.start);
s.cursor += p.seconds;
}
pub fn wait(s: *Frame, seconds: f32) void {
s.cursor += seconds;
}
/// A gate: the plays after it wait until it opens, while time runs on,
/// so plays already running, loops and code reading `t` carry on. It
/// opens in the deck's `update`, on the first frame at or after it is
/// reached on which `open` is not null, and from then on returns that
/// value, a choice to branch on; closed, it returns null. The cursor
/// moves to where it opened, or, closed, just past `t`, so what follows
/// waits in the future. Gates are known by the order they are reached.
pub fn gate(s: *Frame, open: ?u16) ?u16 {
const k = s.stops.items.len;
s.push(&s.stops, s.cursor);
if (k < s.gates.len) {
s.cursor += s.gates[k].wait;
return s.gates[k].value;
}
if (s.closed == null) if (s.log) |log| {
const laying = if (s.lay) |lay| s.slides.items.len < lay.slides else false;
const opens = if (laying) open orelse 0 else if (!s.opened and s.t >= s.cursor) open else null;
if (opens) |v| {
const wait_for = if (laying) @max(s.lay.?.hold, s.t - s.cursor) else s.t - s.cursor;
if (log.appendBounded(.{ .wait = wait_for, .value = v })) {
s.opened = true;
s.cursor += wait_for;
return v;
} else |_| {}
}
};
if (s.closed == null) s.closed = s.cursor;
s.cursor = @max(s.cursor, s.t + 1.0 / 60.0);
return null;
}
/// A gate the presenter opens (`Ask.next`: a click, space, page down),
/// like a slide's next step.
pub fn pause(s: *Frame) void {
_ = s.gate(if (s.next) 0 else null);
}
/// A slide begins: `Ask.next_slide` and `back_slide` go from slide to
/// slide, each shown at rest, held at its first gate.
pub fn slide(s: *Frame) void {
s.push(&s.slides, .{ .at = s.cursor, .gates = @intCast(s.stops.items.len) });
}
/// `f(s, args...)` beside the main line: its plays start at the cursor,
/// and the cursor is left where it was, so what follows runs alongside.
pub fn beside(s: *Frame, comptime f: anytype, args: anytype) void {
const at = s.cursor;
@call(.auto, f, .{s} ++ args);
s.cursor = at;
}
/// `f(s, args...)`, a run of plays that ends where it began, again and
/// again from the cursor until the gate laid right after it opens (for
/// ever while it is closed); the cycle running then completes. The
/// cursor is left where it was. `f` only plays: objects are made
/// outside it. It costs two runs of `f` a frame at most.
pub fn loop(s: *Frame, comptime f: anytype, args: anytype) void {
const start = s.cursor;
@call(.auto, f, .{s} ++ args); // the first cycle, which measures it
const period = s.cursor - start;
const k = s.stops.items.len;
const until = if (k < s.gates.len) start + s.gates[k].wait else std.math.inf(f32);
if (period > 0 and s.t >= start + period) {
var cycle = @floor((@min(s.t, until) - start) / period);
// One that would begin as the gate opens never runs.
if (cycle > 0 and start + cycle * period >= until) cycle -= 1;
s.cursor = start + cycle * period;
@call(.auto, f, .{s} ++ args); // the cycle in progress, which wins
}
s.cursor = start;
}
/// Fades out everything that shows once the plays so far are done, on
/// the main line (`play`'s options): the end of a slide.
pub fn clear(s: *Frame, options: anytype) void {
var all: std.ArrayList(Animation) = .empty;
for (s.settled.items, 0..) |p, i| if (p.visible and p.opacity > 0) s.push(&all, .{ .fade_out = @fromBackingInt(@intCast(i)) });
const buf = s.arena.alloc(Change, 2 * all.items.len) catch @panic("anim: out of memory");
s.playAll(all.items, buf, Play.of(s.cursor, all.items, options));
}
/// `data` in the arena, to change until the frame ends: what a custom
/// object draws.
pub fn new(s: *Frame, data: anytype) *@TypeOf(data) {
const kept = s.arena.create(@TypeOf(data)) catch @panic("anim: out of memory");
kept.* = data;
return kept;
}
/// What the run built, for the player.
fn shot(s: *Frame) !Shot {
const values = try s.arena.alloc(f32, s.values.items.len);
for (values, s.values.items) |*v, own| v.* = own.shown;
return .{ .t = s.t, .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items };
}
/// Slide `j`'s resting picture: where its first gate is laid, or, with
/// no gate of its own, where the next slide begins or the talk ends.
fn rest(s: *const Frame, j: usize) f32 {
const first = s.slides.items[j].gates;
const after = if (j + 1 < s.slides.items.len) s.slides.items[j + 1] else null;
if (first < s.stops.items.len and (after == null or first < after.?.gates)) return s.stops.items[first];
return if (after) |a| a.at else s.cursor;
}
/// Keeps scene code free of error handling: the frame arena running out
/// is fatal anyway.
fn push(s: *Frame, items: anytype, item: @TypeOf(items.items[0])) void {
items.append(s.arena, item) catch @panic("anim: out of memory");
}
};
// ---------------------------------------------------------------------------
// Talks: a live scene with gates, and its playhead
/// A gate opened: how long after it was reached, and the value it opened with.
pub const Gate = struct { wait: f32 = 0, value: u16 = 0 };
const Log = sk.List(Gate, 256);
/// What the presenter asks of a deck this frame. The sketch decides which
/// keys and clicks they are: the deck owns no input.
pub const Ask = struct {
/// The next step: opens the pause the deck waits at, or, during a
/// step, finishes it (the playhead jumps to where the next gate is
/// laid; at the last step, to the end). A paused deck plays on.
next: bool = false,
/// Back a step: the picture held before the last gate opened.
back: bool = false,
/// The next or the previous slide (`Frame.slide`), at rest: held at
/// its first gate, every gate before it opened (at once, a choice with
/// 0) or undone.
next_slide: bool = false,
back_slide: bool = false,
/// A seek: the gates opened after it have not happened yet.
to: ?f32 = null,
/// The end: every gate opened where it is reached.
end: bool = false,
};
/// A talk's playhead: plain data for a sketch's State, so hot reload,
/// snapshots, replay and the console see it like any field. The talk is
/// `frame(s: *Frame, ctx...)`, a live scene's frame with more arguments,
/// run from the top every frame: in `update`, given `ctx` as it is, so it
/// may change the app (`mutable`), and in `shot`, given it read-only.
pub const Deck = struct {
/// Talk time, in seconds: it runs on through gates.
t: f32 = 0,
playing: bool = true,
speed: f32 = 1,
/// Exported, each gate holds this long, then opens itself.
hold: f32 = 1,
/// The gates opened, in order: with `t`, all the talk depends on.
log: Log = .{},
/// When the last gate in `log` opened, as of the last update: an edit
/// that moves it moves `t` with it, so a reload keeps the same step, as
/// far into it.
anchor: f32 = 0,
/// The talk as the last update laid it, for a HUD and for scripts: its
/// end (a closed gate lays what follows it just past `t`), the gates
/// laid, opened or not, whether it waits at one, the slides begun by
/// `t`, and all the slides.
duration: f32 = 0,
gates: u32 = 0,
waiting: bool = false,
slide: u32 = 0,
slides: u32 = 0,
/// In `update`: time from the ticks, `ask` applied, and the talk run
/// once (more when asked to move), opening the gate it waits at.
/// Exported (`in.exporting`), it opens every gate `hold` after it is
/// reached, in the first frame's run, and runs at the export's pace.
pub fn update(d: *Deck, in: *const sk.Input, ask: Ask, comptime frame: anytype, ctx: anytype) void {
var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
for (in.events) |e| if (e.kind == .tick) {
if (in.exporting) {
d.t += e.x;
} else if (d.playing) d.t += e.x * d.speed;
};
if (ask.next) d.playing = true;
const events = arena.dupe(sk.Event, in.events) catch return;
for (events) |*e| switch (e.kind) {
.mouse_move, .mouse_down, .mouse_up, .wheel, .wheel_horizontal => {
const p = pointer(in, e.x, e.y);
e.x = p[0];
e.y = p[1];
},
else => {},
};
const all: Frame.Lay = .{ .hold = 0, .slides = std.math.maxInt(usize) };
// Elsewhere: against the talk as it is laid now.
const moves = ask.back or ask.to != null or ask.end or ask.next_slide or ask.back_slide;
if (moves) {
const m = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null);
d.log.len = @min(d.log.count(), m.stops.items.len);
const n = d.log.count();
var on: u32 = 0;
for (m.slides.items) |sl| on += @intFromBool(sl.at <= d.t);
if (ask.back) {
d.t = if (n > 0) m.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0;
d.log.len = n -| 1;
} else if (ask.to) |to| {
d.t = to;
while (d.log.count() > 0 and m.stops.items[d.log.count() - 1] + d.log.buffer[d.log.count() - 1].wait > to) d.log.len -= 1;
} else if (ask.back_slide) {
if (on < 2) {
d.t = 0;
d.log.len = 0;
} else {
d.log.len = m.slides.items[on - 2].gates;
d.t = m.rest(on - 2);
}
} else {
// Gates open up to the next slide's first, or all of them:
// a choice may be what lays the slides after it.
const l = d.run(arena, in, frame, readOnly(ctx), &.{}, true, false, if (ask.next_slide) .{ .hold = 0, .slides = on + 1 } else all);
d.t = if (ask.next_slide and on < l.slides.items.len) l.rest(on) else l.cursor;
}
}
const before = d.log.count();
var s = d.run(arena, in, frame, ctx, events, true, ask.next and !moves, if (in.exporting) .{ .hold = d.hold, .slides = all.slides } else null);
if (s.stops.items.len < before) {
// An edit took gates out: the ones it left are the talk's.
d.log.len = @intCast(s.stops.items.len);
} else if (!moves and before > 0) {
// An edit moved the last opened gate: so does `t`. That run's
// input is not taken again.
const now = s.stops.items[before - 1] + d.log.buffer[before - 1].wait;
if (now != d.anchor) {
d.log.len = before;
d.t += now - d.anchor;
s = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null);
}
}
// A step under way, finished: the playhead to where it waits next.
if (ask.next and s.next and !s.opened and !moves) d.t = @max(d.t, s.closed orelse s.cursor);
const n = d.log.count();
d.anchor = if (n > 0) s.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0;
d.duration = s.cursor;
d.gates = @intCast(s.stops.items.len);
d.waiting = if (s.closed) |c| d.t >= c else false;
d.slides = @intCast(s.slides.items.len);
d.slide = 0;
for (s.slides.items) |sl| d.slide += @intFromBool(sl.at <= d.t);
}
/// In `draw`: the talk now, for `Painter.paint`; `ctx` read-only and
/// the log too, so drawing changes nothing.
pub fn shot(d: *const Deck, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32, comptime frame: anytype, ctx: anytype) !Shot {
var s: Frame = .{ .t = d.t, .in = in, .pointer = mouse, .arena = arena, .gates = d.log.constSlice() };
@call(.auto, frame, .{&s} ++ readOnly(ctx));
return s.shot();
}
/// Window pixels to scene units from the center: the scene's frame
/// (`width` by `height`) fitted into the window, as `Painter` draws it.
pub fn pointer(in: *const sk.Input, x: f32, y: f32) [2]f32 {
const w = @max(@floor(in.window_width), 1);
const h = @max(@floor(in.window_height), 1);
const k = @min(w / width, h / height);
return .{ (x - w / 2) / k, (y - h / 2) / k };
}
/// One run of the talk at `t`, as the log stands.
fn run(d: *Deck, arena: std.mem.Allocator, in: *const sk.Input, comptime frame: anytype, ctx: anytype, events: []const sk.Event, logs: bool, next: bool, lay: ?Frame.Lay) Frame {
var s: Frame = .{
.t = d.t,
.in = in,
.pointer = pointer(in, in.mouse_x, in.mouse_y),
.arena = arena,
.gates = d.log.constSlice(),
.log = if (logs) &d.log else null,
.next = next,
.events = events,
.lay = lay,
};
@call(.auto, frame, .{&s} ++ ctx);
return s;
}
};
/// `app`, to change: a talk is given the app as `*App` in the deck's
/// `update` run and as `*const App` when drawn, where this is null, so
/// drawing cannot write to it. `if (anim.mutable(app)) |a| a.n += 1`.
pub fn mutable(app: anytype) ?*@typeInfo(@TypeOf(app)).pointer.child {
return if (@typeInfo(@TypeOf(app)).pointer.attrs.@"const") null else app;
}
/// `ctx` with every pointer in it to const: what the runs that only look
/// are given.
fn readOnly(ctx: anytype) ReadOnly(@TypeOf(ctx)) {
var out: ReadOnly(@TypeOf(ctx)) = undefined;
inline for (0..ctx.len) |i| out[i] = ctx[i];
return out;
}
fn ReadOnly(comptime Ctx: type) type {
const types = @typeInfo(Ctx).@"struct".field_types;
var out: [types.len]type = undefined;
for (&out, types) |*o, T| o.* = switch (@typeInfo(T)) {
.pointer => |p| if (p.size == .one) *const p.child else T,
else => T,
};
return @Tuple(&out);
}
/// The scene's frame, in scene units: what shows at camera zoom 1.
pub const width = 1280;
pub const height = 720;
// ---------------------------------------------------------------------------
// Both kinds, to the player
/// What a scene is asked for, each frame.
pub const Instant = struct {
/// Scene time, in seconds.
t: f32,
in: *const sk.Input = &no_input,
pointer: [2]f32 = .{ 0, 0 },
const no_input: sk.Input = .{};
};
/// A scene at one instant: what the player draws.
pub const Shot = struct {
t: f32,
objects: []const Object,
poses: []const Pose,
/// For each object morphing (`pose.into`): the pose its morph started
/// from, and where its target ends up.
morphs: []const Morph,
/// Every `Value`, by handle.
values: []const f32,
camera: Camera,
duration: f32,
/// Start times of every play, for chapter-style seeking.
marks: []const f32,
/// Where each gate is laid (`gate`, `pause`).
stops: []const f32,
};
pub const Morph = struct { from: Pose, to: Pose };
// ---------------------------------------------------------------------------
fn testScene(s: *Builder) void {
const a = s.circle(.{ .r = 10, .fill = blue });
const b = s.rect(.{ .w = 20, .h = 20, .x = 100 });
const k = s.value(0);
s.play(.{a.create()}, .{});
s.wait(0.5);
s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 });
s.always(b, follow, .{k});
s.play(.{a.transformInto(b)}, .{});
}
fn follow(now: Now, k: Value) Pose {
var p = now.pose;
p.y = now.value(k);
return p;
}
test "construct records a timeline that compiles to settling keyframes" {
const S = Scene(testScene);
try std.testing.expectEqual(@as(f32, 4.5), S.duration);
try std.testing.expectEqual(@as(f32, 1), S.pose(0, 1).drawn);
try std.testing.expectApproxEqAbs(@as(f32, 25), S.pose(0, 2.5).x, 1e-3);
try std.testing.expectEqual(@as(f32, 2), S.view(10).zoom);
try std.testing.expectApproxEqAbs(@as(f32, 5), S.values(2.5)[0], 1e-3);
// The updater only runs from where it was added.
try std.testing.expectEqual(@as(f32, 0), S.pose(1, 1).y);
try std.testing.expectEqual(@as(f32, 10), S.pose(1, 4).y);
const mid = S.pose(0, 4.0);
try std.testing.expect(mid.visible and mid.morph > 0 and mid.into == 1);
try std.testing.expect(!S.pose(0, 4.5).visible);
try std.testing.expect(S.pose(1, 4.5).visible);
try std.testing.expectEqual(@as(usize, 3), S.marks.len);
}
/// `testScene`, live: the updater is a line of code after the plays.
fn liveScene(s: *Frame) void {
const a = s.circle(.{ .r = 10, .fill = blue });
const b = s.rect(.{ .w = 20, .h = 20, .x = 100 });
const k = s.value(0);
s.play(.{a.create()}, .{});
s.wait(0.5);
s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 });
const since = s.cursor;
s.play(.{a.transformInto(b)}, .{});
if (s.t >= since) s.pose(b).y = s.get(k);
}
test "a live scene shows what the compiled one does, at every instant" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const compiled = Scene(testScene);
const live = Live(liveScene, struct {});
for ([_]f32{ 0, 0.5, 1, 1.7, 2.5, 3.5, 4, 4.5, 9 }) |t| {
const a = try compiled.shot(arena.allocator(), .{ .t = t });
const b = try live.shot(arena.allocator(), .{ .t = t });
try std.testing.expectEqualSlices(Pose, a.poses, b.poses);
try std.testing.expectEqualSlices(f32, a.values, b.values);
try std.testing.expectEqual(a.camera, b.camera);
try std.testing.expectEqual(a.duration, b.duration);
try std.testing.expectEqualSlices(f32, a.marks, b.marks);
}
}
test "Typst sources come from a namespace or a tuple of them" {
const a = struct {
pub const title = "= A";
};
const b = struct {
pub const law = "$ x $";
pub const end = "= B";
};
try std.testing.expectEqual(@as(usize, 1), Live(liveScene, a).typst_sources.len);
try std.testing.expectEqualStrings("$ x $", Live(liveScene, .{ a, b }).typst_sources[1]);
try std.testing.expectEqual(@as(usize, 3), sources(.{ a, b }).len);
try std.testing.expect(Live(liveScene, a).frame == liveScene);
}
// ---------------------------------------------------------------------------
// Talks: the semantics of the model in .scratch/sketch/anim/gates_model.zig
// (pardes-code), on the real types, then the presenter's rulings.
/// `d.update` with `before` and then a tick of `seconds`, in a window the
/// size of the scene's frame (its center the scene's origin).
fn step(d: *Deck, before: []const sk.Event, seconds: f32, ask: Ask, comptime frame: anytype, ctx: anytype) void {
var events: [8]sk.Event = undefined;
@memcpy(events[0..before.len], before);
events[before.len] = .{ .kind = .tick, .x = seconds };
d.update(&.{ .events = events[0 .. before.len + 1], .window_width = width, .window_height = height }, ask, frame, ctx);
}
/// Value 0 of the talk drawn now.
fn shown(d: *const Deck, arena: std.mem.Allocator, comptime frame: anytype, ctx: anytype) !f32 {
return (try d.shot(arena, &Instant.no_input, .{ 0, 0 }, frame, ctx)).values[0];
}
/// Round 1's slide 2: a phase that runs from `spin`, through the hold at
/// the second gate, until half a second after it opens; -1 otherwise.
fn orbit(s: *Frame) void {
const phase = s.value(-1);
s.wait(2); // the title, written
s.pause();
s.wait(2.5); // out, and the equation in
const spin = s.cursor;
s.pause();
const leave = s.cursor;
s.wait(0.5);
if (s.t >= spin and s.t < leave + 0.5) s.values.items[@backingInt(phase)].shown = s.t - spin;
}
test "a loop runs on through the hold, and its phase is continuous across the click" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var d: Deck = .{};
step(&d, &.{}, 10, .{}, orbit, .{});
try std.testing.expect(d.waiting and d.log.count() == 0 and d.gates == 2);
step(&d, &.{}, 0, .{ .next = true }, orbit, .{});
try std.testing.expectEqual(@as(f32, 8), d.log.buffer[0].wait);
// Slide 2 is in at 12.5; at 15 the deck waits, the phase running.
step(&d, &.{}, 5, .{}, orbit, .{});
try std.testing.expect(d.waiting);
const before = try shown(&d, arena.allocator(), orbit, .{});
step(&d, &.{}, 0, .{ .next = true }, orbit, .{});
try std.testing.expect(!d.waiting and d.log.count() == 2);
try std.testing.expectEqual(before, try shown(&d, arena.allocator(), orbit, .{}));
try std.testing.expectApproxEqAbs(@as(f32, 2.5), before, 1e-4);
// Half a second after the click it has gone.
step(&d, &.{}, 0.6, .{}, orbit, .{});
try std.testing.expectEqual(@as(f32, -1), try shown(&d, arena.allocator(), orbit, .{}));
}
/// Round 1's equation, stepped: written to 1, then each step morphs it one
/// further, to 4.
fn equations(s: *Frame) void {
const form = s.value(0);
s.play(.{form.to(1)}, .{ .seconds = 2, .ease = ease.linear });
for (2..5) |i| {
s.pause();
s.play(.{form.to(@floatFromInt(i))}, .{ .seconds = 1.2, .ease = ease.linear });
}
}
test "back cuts to the picture held before the last click" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var d: Deck = .{};
// Clicks at 5, 9 and 20.
step(&d, &.{}, 5, .{ .next = true }, equations, .{});
step(&d, &.{}, 4, .{ .next = true }, equations, .{});
step(&d, &.{}, 11, .{ .next = true }, equations, .{});
try std.testing.expectEqual(@as(u32, 3), d.log.count());
step(&d, &.{}, 0.6, .{}, equations, .{});
try std.testing.expectApproxEqAbs(@as(f32, 3.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3);
// Back, mid-morph: the third form at rest, held where the click was.
step(&d, &.{}, 0, .{ .back = true }, equations, .{});
try std.testing.expect(d.t == 20 and d.log.count() == 2 and d.waiting);
try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{}));
// Time runs on while held; nothing moves.
step(&d, &.{}, 40, .{}, equations, .{});
try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{}));
// Back again: the second form, at 9; then the first, at 5; then the start.
step(&d, &.{}, 0, .{ .back = true }, equations, .{});
try std.testing.expect(d.t == 9 and d.log.count() == 1);
try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), equations, .{}));
step(&d, &.{}, 0, .{ .back = true }, equations, .{});
try std.testing.expect(d.t == 5 and d.log.count() == 0 and d.waiting);
step(&d, &.{}, 0, .{ .back = true }, equations, .{});
try std.testing.expect(d.t == 0 and !d.waiting);
// Forward after back plays the step again.
step(&d, &.{}, 3, .{ .next = true }, equations, .{});
step(&d, &.{}, 0.6, .{}, equations, .{});
try std.testing.expectApproxEqAbs(@as(f32, 1.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3);
}
test "exported, each gate opens a fixed hold after it is reached: the same frames every run" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var runs: [2]Deck = .{ .{ .hold = 1 }, .{ .hold = 1 } };
var seen: [2][4]f32 = undefined;
for (&runs, &seen) |*d, *values| for (0..10 * 30) |frame| {
const tick = [_]sk.Event{.{ .kind = .tick, .x = 1.0 / 30.0 }};
d.update(&.{ .events = &tick, .exporting = true, .window_width = width, .window_height = height }, .{}, equations, .{});
if (frame % 75 == 0) values[frame / 75] = try shown(d, arena.allocator(), equations, .{});
};
for (runs) |d| {
try std.testing.expectEqual(@as(u32, 3), d.log.count());
for (d.log.constSlice()) |g| try std.testing.expectEqual(@as(f32, 1), g.wait);
try std.testing.expectApproxEqAbs(@as(f32, 2 + 3 * 2.2), d.duration, 1e-4);
}
try std.testing.expectEqualSlices(Gate, runs[0].log.constSlice(), runs[1].log.constSlice());
try std.testing.expectEqual(seen[0], seen[1]);
}
/// A talk that branches on the app's choice: proof (0) is two steps with a
/// pause between, skip (1) one; both end on the same slide. Each part shows
/// a circle: proof one, proof two, skipped, the end.
fn branching(s: *Frame, app: anytype) void {
var parts: [4]Obj = undefined;
for (&parts) |*p| p.* = s.circle(.{ .r = 1 });
s.wait(2);
const pick = s.gate(app.pick) orelse return; // closed: nothing after it shows
switch (pick) {
0 => {
s.play(.{parts[0].fadeIn()}, .{});
s.pause();
s.play(.{parts[1].fadeIn()}, .{});
},
else => s.play(.{parts[2].fadeIn()}, .{}),
}
s.play(.{parts[3].fadeIn()}, .{});
}
const Choice = struct { pick: ?u16 = null };
fn showing(d: *const Deck, arena: std.mem.Allocator, app: *const Choice) ![4]bool {
const shot = try d.shot(arena, &Instant.no_input, .{ 0, 0 }, branching, .{app});
var out: [4]bool = undefined;
for (&out, shot.poses) |*o, p| o.* = p.visible;
return out;
}
test "a choice is logged in update, branched on, and replays from the log alone" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var app: Choice = .{};
var d: Deck = .{};
step(&d, &.{}, 3, .{}, branching, .{&app});
try std.testing.expect(d.waiting and d.log.count() == 0);
// A click is no choice.
step(&d, &.{}, 0, .{ .next = true }, branching, .{&app});
try std.testing.expect(d.waiting and d.log.count() == 0 and d.t == 3);
// The app says "skip": the gate opens with 1.
app.pick = 1;
step(&d, &.{}, 0, .{}, branching, .{&app});
try std.testing.expectEqual(Gate{ .wait = 1, .value = 1 }, d.log.buffer[0]);
// From the log alone, whatever the app says now: skipped, then the end.
app.pick = null;
d.t = 3.5;
try std.testing.expectEqual([4]bool{ false, false, true, false }, try showing(&d, arena.allocator(), &app));
d.t = 4.5;
try std.testing.expectEqual([4]bool{ false, false, true, true }, try showing(&d, arena.allocator(), &app));
// Another log takes the proof, whose pause is the second gate.
var proof: Deck = .{ .t = 4.5 };
try proof.log.appendBounded(.{ .wait = 1, .value = 0 });
try std.testing.expectEqual([4]bool{ true, false, false, false }, try showing(&proof, arena.allocator(), &app));
try proof.log.appendBounded(.{ .wait = 2 });
proof.t = 6.5;
try std.testing.expectEqual([4]bool{ true, true, false, false }, try showing(&proof, arena.allocator(), &app));
}
fn twoPauses(s: *Frame) void {
s.wait(2);
s.pause();
s.pause();
}
test "one click opens one gate, even when two are back to back" {
var d: Deck = .{};
step(&d, &.{}, 5, .{ .next = true }, twoPauses, .{});
try std.testing.expect(d.log.count() == 1 and d.waiting);
step(&d, &.{}, 0, .{ .next = true }, twoPauses, .{});
try std.testing.expect(d.log.count() == 2 and !d.waiting);
}
/// A swing of value `v` from 0 to 1 and back, in 1.5 s.
fn swing(s: *Frame, v: Value) void {
s.play(.{v.to(1)}, .{ .seconds = 0.75, .ease = ease.linear });
s.play(.{v.to(0)}, .{ .seconds = 0.75, .ease = ease.linear });
}
fn swinging(s: *Frame) void {
const v = s.value(0);
s.wait(2);
s.loop(swing, .{v});
s.pause();
}
test "a loop repeats until the next gate opens, then finishes its cycle" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
// Laid at 2: at 5.3 the third cycle is 0.3 s in.
var f: Frame = .{ .t = 5.3, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator() };
swinging(&f);
try std.testing.expectApproxEqAbs(@as(f32, 0.4), f.get(@fromBackingInt(0)), 1e-4);
// The gate opened at 6, in the third cycle (from 5): at 6.4 it is
// still swinging back, at 6.6 done, with no fourth.
const gates = [_]Gate{.{ .wait = 4 }};
var g: Frame = .{ .t = 6.4, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates };
swinging(&g);
try std.testing.expectApproxEqAbs(@as(f32, 1 - 0.65 / 0.75), g.get(@fromBackingInt(0)), 1e-4);
var h: Frame = .{ .t = 6.6, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates };
swinging(&h);
try std.testing.expectEqual(@as(f32, 0), h.get(@fromBackingInt(0)));
}
/// A three-step talk whose first step lasts `tempo.first`: value 0 is ten
/// times the step shown plus how far into it.
fn retimed(s: *Frame, tempo: anytype) void {
const at = s.value(0);
s.wait(tempo.first);
s.pause();
const one = s.cursor;
s.wait(1);
s.pause();
const two = s.cursor;
s.wait(1);
const v = &s.values.items[@backingInt(at)].shown;
if (s.t >= two) v.* = 20 + s.t - two else if (s.t >= one) v.* = 10 + s.t - one else v.* = s.t;
}
test "retiming a step above: waits plus re-anchoring keep the presenter where they were" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var tempo: struct { first: f32 } = .{ .first = 2 };
var d: Deck = .{};
// Opened after 3 s of waiting, then 4: half a second into step 2.
step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo});
step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo});
step(&d, &.{}, 0.5, .{}, retimed, .{&tempo});
try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4);
// The first step is retimed to 5 s, and the library reloads: the same
// step, as far in, the log as it was.
tempo.first = 5;
step(&d, &.{}, 0, .{}, retimed, .{&tempo});
try std.testing.expectApproxEqAbs(@as(f32, 13.5), d.t, 1e-4);
try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4);
try std.testing.expect(d.log.count() == 2 and d.log.buffer[0].wait == 3 and d.log.buffer[1].wait == 4);
}
/// Written in 2 s, a pause, then one more second.
fn written(s: *Frame) void {
const v = s.value(0);
s.play(.{v.to(1)}, .{ .seconds = 2 });
s.pause();
s.play(.{v.to(2)}, .{ .seconds = 1 });
}
test "a click during a step finishes it, and the next click opens the gate (Keynote)" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var d: Deck = .{};
step(&d, &.{}, 1, .{}, written, .{});
try std.testing.expect(!d.waiting);
step(&d, &.{}, 0, .{ .next = true }, written, .{});
try std.testing.expect(d.t == 2 and d.waiting and d.log.count() == 0);
try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), written, .{}));
// A paused deck plays on when asked for the next step.
d.playing = false;
step(&d, &.{}, 0, .{ .next = true }, written, .{});
try std.testing.expect(d.playing and d.log.count() == 1 and d.log.buffer[0].wait == 0);
// The last step, finished: the end.
step(&d, &.{}, 0.2, .{ .next = true }, written, .{});
try std.testing.expectEqual(@as(f32, 3), d.t);
try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), written, .{}));
}
/// Three slides: the first holds one pause, the second two, the third none.
fn slides(s: *Frame) void {
const v = s.value(0);
s.slide();
s.play(.{v.to(1)}, .{ .ease = ease.linear });
s.pause();
s.play(.{v.to(2)}, .{ .ease = ease.linear });
s.slide();
s.play(.{v.to(3)}, .{ .ease = ease.linear });
s.pause();
s.play(.{v.to(4)}, .{ .ease = ease.linear });
s.pause();
s.play(.{v.to(5)}, .{ .ease = ease.linear });
s.slide();
s.play(.{v.to(6)}, .{ .ease = ease.linear });
}
test "slides: next and previous go to each one's resting picture" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var d: Deck = .{};
step(&d, &.{}, 0.5, .{}, slides, .{});
try std.testing.expect(d.slide == 1 and d.slides == 3 and !d.waiting);
// Slide 2 at rest: slide 1's step done at once, held at slide 2's first pause.
step(&d, &.{}, 0, .{ .next_slide = true }, slides, .{});
try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting);
try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), slides, .{}));
// A step within it, then slide 3, which holds no pause: its end.
step(&d, &.{}, 0, .{ .next = true }, slides, .{});
try std.testing.expectEqual(@as(u32, 2), d.log.count());
step(&d, &.{}, 0.5, .{ .next_slide = true }, slides, .{});
try std.testing.expect(d.slide == 3 and d.log.count() == 3 and d.t == 6);
try std.testing.expectEqual(@as(f32, 6), try shown(&d, arena.allocator(), slides, .{}));
// Back to slide 2 at rest (its steps undone), then slide 1, then the start.
step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting);
step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
try std.testing.expect(d.slide == 1 and d.t == 1 and d.log.count() == 0 and d.waiting);
try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), slides, .{}));
step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
try std.testing.expect(d.t == 0 and d.log.count() == 0);
// Past the last slide: the end.
step(&d, &.{}, 0, .{ .end = true }, slides, .{});
try std.testing.expect(d.t == 6 and d.log.count() == 3 and d.slide == 3);
}
/// Slide 2 lies after a choice: it is laid once the choice is made.
fn choosing(s: *Frame) void {
s.slide();
s.wait(1);
_ = s.gate(null) orelse return;
s.wait(1);
s.slide();
s.wait(1);
s.pause();
}
test "the next slide past a choice not made makes it, with 0" {
var d: Deck = .{};
step(&d, &.{}, 0, .{}, choosing, .{});
try std.testing.expect(d.slide == 1 and d.slides == 1);
step(&d, &.{}, 0, .{ .next_slide = true }, choosing, .{});
try std.testing.expect(d.slide == 2 and d.slides == 2 and d.t == 3 and d.waiting);
try std.testing.expect(d.log.count() == 1 and d.log.buffer[0].value == 0);
}
/// A button laid out before the pause it waits at, taking clicks on it.
fn counting(s: *Frame, app: anytype) void {
s.wait(1);
const button: sk.Rect = .{ .x = -50, .y = -50, .w = 100, .h = 100 };
if (mutable(app)) |a| for (s.events) |e| if (e.kind == .mouse_up and button.contains(e.x, e.y)) {
a.n += 1;
s.next = false;
};
s.pause();
}
test "a click a widget takes is not the presenter's next as well" {
var app: struct { n: u32 = 0 } = .{};
var d: Deck = .{};
step(&d, &.{}, 2, .{}, counting, .{&app});
try std.testing.expect(d.waiting);
// On the button, at the window's center (the scene's origin): the
// button's. The sketch made it `next`, as it makes every click.
const on: sk.Event = .{ .kind = .mouse_up, .x = width / 2, .y = height / 2, .code = 1 };
step(&d, &.{on}, 0, .{ .next = true }, counting, .{&app});
try std.testing.expect(app.n == 1 and d.log.count() == 0 and d.waiting);
// Elsewhere: the presenter's.
const off: sk.Event = .{ .kind = .mouse_up, .x = 100, .y = 100, .code = 1 };
step(&d, &.{off}, 0, .{ .next = true }, counting, .{&app});
try std.testing.expect(app.n == 1 and d.log.count() == 1);
// Drawn, the talk gets the app read-only: nothing to write through.
const app_const: *const @TypeOf(app) = &app;
try std.testing.expect(mutable(app_const) == null);
try std.testing.expect(mutable(&app).? == &app);
}
fn fadeIn(s: *Frame, o: Obj) void {
s.play(.{o.fadeIn()}, .{ .seconds = 1 });
}
fn besideAndClear(s: *Frame) void {
const a = s.circle(.{ .r = 1 });
const b = s.circle(.{ .r = 1 });
s.beside(fadeIn, .{a});
s.play(.{b.fadeIn()}, .{ .seconds = 1 });
s.clear(.{ .seconds = 1 });
}
test "beside runs alongside the main line; clear fades out what shows" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const live = Live(besideAndClear, struct {});
const mid = try live.shot(arena.allocator(), .{ .t = 0.5 });
try std.testing.expectEqual(mid.poses[0], mid.poses[1]);
try std.testing.expect(mid.poses[0].visible and mid.poses[0].opacity > 0 and mid.poses[0].opacity < 1);
const out = try live.shot(arena.allocator(), .{ .t = 1.5 });
try std.testing.expectEqual(out.poses[0], out.poses[1]);
try std.testing.expect(out.poses[0].opacity < 1);
const gone = try live.shot(arena.allocator(), .{ .t = 2 });
try std.testing.expect(!gone.poses[0].visible and !gone.poses[1].visible and gone.duration == 2);
}
/// Three squares, 100 units each, the middle one red; the right one is
/// taken as a part once the row shows, then each moves its own way.
fn partScene(s: anytype) void {
const row = s.svg(
\\<svg viewBox="0 0 300 100" width="300" height="100"><rect width="100" height="100"/>
\\<rect x="100" width="100" height="100" fill="red"/><rect x="200" width="100" height="100"/></svg>
, .{ .x = 10, .scale = 2 });
s.play(.{row.fadeIn()}, .{});
const right = s.part(row, .{ .x = 100, .w = 80, .h = 80 });
s.play(.{ right.move(.{ .y = 50 }), row.move(.{ .x = 0 }) }, .{});
}
test "a part takes its shapes from its object, stands where they stood and follows it until taken" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const compiled = Scene(struct {
fn construct(s: *Builder) void {
partScene(s);
}
}.construct);
const live = Live(struct {
fn frame(s: *Frame) void {
partScene(s);
}
}.frame, struct {});
for ([_]f32{ 0, 0.5, 1, 1.5, 2, 3 }) |t| {
const a = try compiled.shot(arena.allocator(), .{ .t = t });
const b = try live.shot(arena.allocator(), .{ .t = t });
try std.testing.expectEqualSlices(Pose, a.poses, b.poses);
try std.testing.expectEqual(a.objects[0].id(), b.objects[0].id());
try std.testing.expectEqual(a.objects[1].id(), b.objects[1].id());
}
// Fading in with the row, before it was taken; where the right square
// stood (10 + 2 * 100) once it was; then on its own.
try std.testing.expectEqual(compiled.pose(0, 0.5).opacity, compiled.pose(1, 0.5).opacity);
try std.testing.expectEqual(Pose{ .x = 210, .scale = 2, .visible = true }, compiled.pose(1, 1));
try std.testing.expectEqual(@as(f32, 50), compiled.pose(1, 2).y);
try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 2).x);
try std.testing.expectEqual(@as(f32, 210), compiled.pose(1, 2).x);
// The row keeps two squares; the part is the third, around its centre.
const no_typst = struct {
fn find(_: []const u8) ?[]const u8 {
return null;
}
};
const rest = try build(arena.allocator(), compiled.objects[0], no_typst);
const taken = try build(arena.allocator(), compiled.objects[1], no_typst);
try std.testing.expectEqual(@as(usize, 2), rest.shapes.len);
try std.testing.expectEqual(@as(usize, 1), taken.shapes.len);
try std.testing.expectEqual(vector.geom.Rect{ .x = -50, .y = -50, .w = 100, .h = 100 }, taken.bounds().rect());
try std.testing.expectEqual(vector.geom.Rect{ .x = -150, .y = -50, .w = 200, .h = 100 }, rest.bounds().rect());
}
/// Four animations a lag of 0.5 apart, then two a whole one apart.
fn lagScene(s: anytype) void {
const a = s.circle(.{ .r = 10 });
const b = s.circle(.{ .r = 10, .x = 50 });
const c = s.rect(.{ .w = 20, .h = 20, .x = 100 });
const k = s.value(0);
s.play(.{ a.fadeIn(), b.fadeIn(), camera(.{ .zoom = 2 }), k.to(1) }, .{ .seconds = 2.5, .lag = 0.5 });
s.play(.{ b.move(.{ .x = 0 }), a.transformInto(c) }, .{ .lag = 1 });
}
test "a play's lag starts each animation a fraction of its length after the one before, and the last ends with the play" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const compiled = Scene(struct {
fn construct(s: *Builder) void {
lagScene(s);
}
}.construct);
const live = Live(struct {
fn frame(s: *Frame) void {
lagScene(s);
}
}.frame, struct {});
for (0..16) |i| {
const t = @as(f32, @floatFromInt(i)) / 4;
const x = try compiled.shot(arena.allocator(), .{ .t = t });
const y = try live.shot(arena.allocator(), .{ .t = t });
try std.testing.expectEqualSlices(Pose, x.poses, y.poses);
try std.testing.expectEqualSlices(f32, x.values, y.values);
try std.testing.expectEqual(x.camera, y.camera);
try std.testing.expectEqual(x.duration, y.duration);
try std.testing.expectEqualSlices(f32, x.marks, y.marks);
if (x.poses[0].into != Pose.none) try std.testing.expectEqual(x.morphs[0], y.morphs[0]);
}
// 2.5 s for four, each 1 s long (2.5 / (1 + 3 * 0.5)), 0.5 s apart.
try std.testing.expectEqual(@as(f32, 3.5), compiled.duration);
try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 0.5).opacity, 1e-6);
try std.testing.expectEqual(@as(f32, 0), compiled.pose(1, 0.5).opacity);
try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(1, 1).opacity, 1e-6);
try std.testing.expectEqual(@as(f32, 1), compiled.view(1).zoom);
try std.testing.expectEqual(@as(f32, 2), compiled.view(2).zoom);
try std.testing.expectEqual(@as(f32, 0), compiled.values(1.5)[0]);
try std.testing.expectEqual(@as(f32, 1), compiled.values(2.5)[0]);
// A lag of 1: one after the other, half the play each.
try std.testing.expectApproxEqAbs(@as(f32, 25), compiled.pose(1, 2.75).x, 1e-4);
try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 3).morph);
try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 3.25).morph, 1e-6);
}
|