summaryrefslogtreecommitdiff
path: root/doc/api.texi
blob: 3946ecdba1cb67ad4f9a250ae4c88f804901e25b (plain)
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
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
@menu
* Kernel::                      The fundamental components.
* Math::                        Linear algebra, spatial partitioning, and more.
* Graphics::                    Eye candy.
* Audio::                       Make some noise.
* Scripting::                   Bringing the game world to life.
@end menu

@node Kernel
@section Kernel

This section of the manual covers the foundation of Chickadee: The
game loop and desktop environment interaction.

@menu
* The Game Loop::               The core event loop.
* Input Devices::               Mouse, keyboard, controller input.
* Window Manipulation::         Inspect and modify the graphical window.
* Live Coding::                 Tips for building games from the REPL.
@end menu

@node The Game Loop
@subsection The Game Loop

At the very core of Chickadee there is an event loop.  This loop, or
``kernel'', is responsible for ensuring that the game is updated at
the desired interval, handling input devices, rendering the current
state of the game world, and handling errors if they occur.  The
kernel implements what is known as a ``fixed timestep'' game loop,
meaning that the game simulation will be advanced by a fixed interval
of time and will never vary from frame to frame, unlike some other
styles of game loops.  The appropriately named @code{run-game} and
@code{abort-game} procedures are the entry and exit points to the
Chickadee game loop.

If you are using @command{chickadee play} to launch your game, then
calling @code{run-game} is already taken care of for you.

@deffn {Procedure} run-game [#:window-title "Chickadee!"] @
       [#:window-width 640] [#:window-height 480] @
       [#:window-fullscreen? @code{#f}] @
       [#:window-resizable? @code{#f}] @
       [#:update-hz 60] @
       [#:load] [#:update] [#:draw] [#:quit] @
       [#:key-press] [#:key-release] [#:text-input] @
       [#:mouse-press] [#:mouse-release] [#:mouse-move] @
       [#:controller-add] [#:controller-remove] [#:controller-press] @
       [#:controller-release] [#:controller-move] [#:error]

Run the Chickadee game loop.

A new graphical window will be opened with @var{window-width} x
@var{window-height} as its dimensions, @var{window-title} as its
title, and in fullscreen mode if @var{window-fullscreen?} is
@code{#t}.  If @var{window-resizable?} is @code{#t} then the window
can be resized by the user.

@itemize
@item
@var{load}: Called with zero arguments when the game window has opened
but before the game loop has started.  Can be used to perform
initialization that requires an open window and OpenGL context such as
loading textures.

@item
@var{update}: Called @var{update-hz} times per second with one
argument: The amount of time to advance the game simulation.

@item
@var{draw}: Called each time a frame should be rendered with a single
argument known as the @code{alpha} value.  See the documentation for
@code{run-game*} for an explanation of this value.

@item
@var{quit}: Called with zero arguments when the user tries to close
the game window.  The default behavior is to exit the game.

@item
@var{key-press}: Called with four arguments when a key is pressed on
the keyboard:

@enumerate
@item
@var{key}: The symbolic name of the key that was pressed.  For
example: @code{backspace}.

@item
@var{modifiers}: A list of the symbolic names of modifier keys that
were being held down when the key was pressed.  Possible values
include @code{ctrl}, @code{alt}, and @code{shift}.

@item
@var{repeat?}: @code{#t} if this is a repeated press of the same key.

@end enumerate

@item
@var{key-release}: Called with three arguments when a key is released
on the keyboard:

@enumerate
@item
@var{key}: The symbolic name of the key that was released.

@item
@var{modifiers}: A list of the symbolic names of modifier keys that
were being held down when the key was released.

@end enumerate

@item
@var{text-input}: Called with a single argument, a string of text,
when printable text is typed on the keyboard.

@item
@var{mouse-press}: Called with four arguments when a mouse button is
pressed:
@enumerate

@item
@var{button}: The symbolic name of the button that was pressed, such
as @code{left}, @code{middle}, or @code{right}.

@item
@var{clicks}: The number of times the button has been clicked in a row.

@item
@var{x}: The x coordinate of the mouse cursor.

@item
@var{y}: The y coordinate of the mouse cursor.

@end enumerate

@item
@var{mouse-release}: Called with three arguments when a mouse button
is released:

@enumerate

@item
@var{button}: The symbolic name of the button that was released.

@item
@var{x}: The x coordinate of the mouse cursor.

@item
@var{y}: The y coordinate of the mouse cursor.

@end enumerate

@item
@var{mouse-move}: Called with five arguments when the mouse is moved:

@enumerate

@item
@var{x}: The x coordinate of the mouse cursor.

@item
@var{y}: The y coordinate of the mouse cursor.

@item
@var{dx}: The amount the mouse has moved along the x axis since the
last mouse move event.

@item
@var{dy}: The amount the mouse has moved along the y axis since the
last mouse move event.

@item
@var{buttons}: A list of the buttons that were pressed down when the
mouse was moved.

@end enumerate

@item
@var{mouse-wheel}: Called with two arguments when the mouse wheel is
scrolled:

@enumerate

@item
@var{x}: The scroll amount along the X axis.

@item
@var{y}: The scroll amount along the Y axis.

@end enumerate

@item
@var{controller-add}: Called with a single argument, an SDL game
controller object, when a game controller is connected.

@item
@var{controller-remove}: Called with a single argument, an SDL game
controller object, when a game controller is disconnected.

@item
@var{controller-press}: Called with two arguments when a button on a
game controller is pressed:

@enumerate

@item
@var{controller}: The controller that triggered the event.

@item
@var{button}: The symbolic name of the button that was pressed.
Possible buttons are:

@itemize
@item
@code{a}
@item
@code{b}
@item
@code{x}
@item
@code{y}
@item
@code{back}
@item
@code{guide}
@item
@code{start}
@item
@code{left-stick}
@item
@code{right-stick}
@item
@code{left-shoulder}
@item
@code{right-shoulder}
@item
@code{dpad-up}
@item
@code{dpad-down}
@item
@code{dpad-left}
@item
@code{dpad-right}

@end itemize

@end enumerate

@item
@var{controller-release}: Called with two arguments when a button on a
game controller is released:

@enumerate

@item
@var{controller}: The controller that triggered the event.

@item
@var{button}: The symbolic name of the button that was released.

@end enumerate

@item
@var{controller-move}: Called with three arguments when an analog
stick or trigger on a game controller is moved:

@enumerate

@item
@var{controller}: The controller that triggered the event.

@item
@var{axis}: The symbolic name of the axis that was moved.  Possible
values are:

@itemize
@item
@code{left-x}
@item
@code{left-y}
@item
@code{right-x}
@item
@code{right-y}
@item
@code{trigger-left}
@item
@code{trigger-right}
@end itemize

@end enumerate

@item
@var{error}: Called with three arguments when an error occurs:

@enumerate

@item
@var{stack}: The call stack at the point of error.

@item
@var{key}: The exception key.

@item
@var{args}: The arguments thrown with the exception.

@end enumerate

The default behavior is to re-throw the error.

@end itemize

@end deffn

To stop the game loop, simply call @code{abort-game}.

@deffn {Procedure} abort-game
Stop the currently running Chickadee game loop.
@end deffn

The above explanation of the game loop was partially a lie.  It's true
that there is a game loop at the center of Chickadee, but
@code{run-game} is not it's true entry point.  There exists an even
lower level procedure, @code{run-game*}, in the @code{(chickadee
game-loop)} module that @code{run-game} uses under the hood.

On its own, @code{run-game*} does not do very much at all.  In order
to actually respond to input events, update game state, or render
output, the developer must provide an engine.  @code{run-game} is such
an engine, and it's likely all a developer will need.  However, what
if a developer wanted to use all of the useful Chickadee features to
make a terminal roguelike game instead?  Chickadee doesn't come with a
terminal rendering engine, but the developer could write one without
having to write their own core game loop.

@deffn {Procedure} run-game* [#:update] [#:render] [#:time] [#:error] @
       [#:update-hz 60]

Start the game loop.  This procedure will not return until
@code{abort-game} is called.

The core game loop is generic and requires four additional procedures
to operate:

@itemize
@item
@var{update}: Called @var{update-hz} times per second to advance the
game simulation.  This procedure is called with a single argument: The
amount of time that has passed since the last update, in milliseconds.
@item
@var{render}: Called each iteration of the loop to render the game to
the desired output device.  This procedure is called with a single
argument: A value in the range [0, 1] which represents how much time
has past since the last game state update relative to the upcoming
game state update, as a percentage.  Because the game state is updated
independent of rendering, it is often the case that rendering is
occuring between two updates.  If the game is rendered as it was
during the last update, a strange side-effect will occur that makes
animation appear rough or ``choppy''.  To counter this, the
@var{alpha} value can be used to perfrom a linear interpolation of a
moving object between its current position and its previous position.
This odd trick has the pleasing result of making the animation look
smooth again, but requires keeping track of previous state.
@item
@var{time}: Called to get the current time in seconds.  This procedure
is called with no arguments.
@item
@var{error}: Called when an error from the @var{update} or
@var{render} procedures reaches the game loop.  This procedure is
called with three arguments: The call stack, the error key, and the
error arguments.  If no error handler is provided, the default
behavior is to simply re-throw the error.
@end itemize

@end deffn

@deffn {Procedure} elapsed-time
Return the current value of the system timer in seconds.
@end deffn

@node Input Devices
@subsection Input Devices

While @code{run-game} provides hooks for mouse/keyboard/controller
input events, it is often necessary to query input devices for their
current state.  For example, it could be desirable to query the state
of the arrow keys every time the update hook is called to determine
which direction the player should move that frame.

@deffn {Procedure} key-pressed? key
Return @code{#t} if @var{key} is currently being pressed.
@end deffn

@deffn {Procedure} key-released? key
Return @code{#t} if @var{key} is @emph{not} currently being pressed.
@end deffn

@deffn {Procedure} mouse-x
Return the current X coordinate of the mouse cursor.
@end deffn

@deffn {Procedure} mouse-y
Return the current Y coordinate of the mouse cursor.
@end deffn

@deffn {Procedure} mouse-button-pressed? button
Return @code{#t} if @var{button} is currently being pressed.
@end deffn

@deffn {Procedure} mouse-button-released? button
Return @code{#t} if @var{button} is @emph{not} currently being
pressed.
@end deffn

@deffn {Procedure} controller-axis controller axis
Return a floating point value in the range [-1, 1] corresponding to
how much @var{axis} (an analog stick or trigger) is being pushed on
@var{controller}.  0 is returned if @var{axis} is not being pushed at
all.
@end deffn

@deffn {Procedure} controller-name controller
Return the name of @var{controller}.
@end deffn

@deffn {Procedure} controller-button-pressed? controller button
Return @code{#t} if @var{button} on @var{controller} is currently
being pressed.
@end deffn

@deffn {Procedure} controller-button-released? controller button
Return @code{#t} if @var{button} on @var{controller} is @emph{not}
currently being pressed.
@end deffn

@node Window Manipulation
@subsection Window Manipulation

@deffn {Procedure} current-window
Return the currently active game window.
@end deffn

@deffn {Procedure} window? obj
Return @code{#t} if @var{obj} is a window object.
@end deffn

@deffn {Procedure} window-title window
Return the title of @var{window}.
@end deffn

@deffn {Procedure} window-width window
Return the width of @var{window} in pixels.
@end deffn

@deffn {Procedure} window-height window
Return the height of @var{window} in pixels.
@end deffn

@deffn {Procedure} window-x window
Retun the X coordinate of the upper-left corner of @var{window}.
@end deffn

@deffn {Procedure} window-y window
Return the Y coordinate of the upper-left corner of @var{window}.
@end deffn

@deffn {Procedure} hide-window! window
Hide @var{window}.
@end deffn

@deffn {Procedure} show-window! window
Show @var{window}.
@end deffn

@deffn {Procedure} maximize-window! window
Maximize @var{window}.
@end deffn

@deffn {Procedure} minimize-window! window
Minimize @var{window}.
@end deffn

@deffn {Procedure} raise-window! window
Make @var{window} visible over all other windows.
@end deffn

@deffn {Procedure} restore-window! window
Restore the size and position of a minimized or maximized
@var{window}.
@end deffn

@deffn {Procedure} set-window-border! window border?
Enable/disable the border around @var{window}.  If @var{border?} is
@code{#f}, the border is disabled, otherwise it is enabled.
@end deffn

@deffn {Procedure} set-window-title! window title
Change the title of @var{window} to @var{title}.
@end deffn

@deffn {Procedure} set-window-size! window width height
Change the dimensions of @var{window} to @var{width} x @var{height}
pixels.
@end deffn

@deffn {Procedure} set-window-position! window x y
Move the upper-left corner of @var{window} to pixel coordinates
(@var{x}, @var{y}).
@end deffn

@deffn {Procedure} set-window-fullscreen! window fullscreen?
Enable or disable fullscreen mode for @var{window}.  If
@var{fullscreen?} is @code{#f}, fullscreen mode is disabled, otherwise
it is enabled.
@end deffn


@node Live Coding
@subsection Live Coding

One of the biggest appeals of any Lisp dialect is the ability to use
the ``read-eval-print loop'' (REPL for short) to build programs
iteratively and interactively while the program is running.  However,
programs that run in an event loop and respond to user input (such as
a video game) require special care for this workflow to be pleasant.
Chickadee provides no built-in support for live coding, but it's
fairly easy to hook up a special kind of REPL yourself.

First, create a cooperative REPL server (It's important to use Guile's
cooperative REPL server instead of the standard REPL server in
@code{(system repl server)} to avoid thread synchronization issues).
Then, in the game loop's update procedure, call
@code{poll-coop-repl-server} and pass the REPL object.  Here is a
template to follow:

@example
(use-modules (chickadee)
             (system repl coop-server))

(define repl (spawn-coop-repl-server))

(define (update dt)
  (poll-coop-repl-server repl)
  ...)

(run-game #:update update ...)
@end example

To use the REPL, connect to it via port 37146.  Telnet will do the
trick, but using the @uref{https://www.nongnu.org/geiser/, Geiser}
extension for Emacs is by far the best way to develop at the REPL with
Guile.  Use @code{M-x connect-to-guile} to connect to the REPL server.

@node Math
@section Math

Chickadee contains data types and procedures for performing the most
common computations in video game simulations such as linear algebra
with vectors and matrices and axis-aligned bounding box collision
detection.

@menu
* Basics::                      Commonly used, miscellaneous things.
* Vectors::                     Euclidean vectors.
* Rectangles::                  Axis-aligned bounding boxes.
* Matrices::                    Transformation matrices.
* Quaternions::                 Rotations about an arbitrary axis.
* Easings::                     Easing functions for interesting animations.
* Bezier Curves::               Cubic Bezier curves and paths in 2D space.
* Path Finding::                Generic A* path finding.
* Grid::                        Spatial partitioning for bounding boxes.
@end menu

@node Basics
@subsection Basics

@defvar pi
An essential constant for all trigonometry.  Pi is the ratio of a
circle's circumferences to its diameter.  Since pi is an irrational
number, the @var{pi} in Chickadee is a mere floating point
approximation that is ``good enough.''
@end defvar

@defvar pi/2
Half of @var{pi}.
@end defvar

@defvar tau
Twice @var{pi}.
@end defvar

@deffn {Procedure} cotan z
Return the cotangent of @var{z}.
@end deffn

@deffn {Procedure} clamp min max x
Restrict @var{x} to the inclusive range defined by @var{min} and
@var{max}.  This procedure assumes that @var{min} is actually less
than @var{max}.
@end deffn

@deffn {Procedure} lerp start end alpha
Linearly interpolate the numbers @var{start} and @var{end} using the
factor @var{alpha}, a number in the range [0, 1].
@end deffn

@deffn {Procedure} degrees->radians degrees
Convert @var{degrees} to radians.
@end deffn

@deffn {Procedure} radians->degrees radians
Convert @var{radians} to degrees.
@end deffn

@node Vectors
@subsection Vectors

Unlike Scheme's vector data type, which is a sequence of arbitrary
Scheme objects, Chickadee's @code{(chickadee math vector)} module
provides vectors in the linear algebra sense: Sequences of numbers
specialized for particular coordinate spaces.  As of now, Chickadee
provides 2D and 3D vectors, with 4D vector support coming in a future
release.

Here's a quick example of adding two vectors:

@example
(define v (vec2+ (vec2 1 2) (vec2 3 4)))
@end example

@emph{A Note About Performance}

A lot of time has been spent making Chickadee's vector operations
perform relatively efficiently in critical code paths where excessive
garbage generation will cause major performance issues.  The general
rule is that procedures ending with @code{!} perform an in-place
modification of one of the arguments in order to avoid allocating a
new vector.  These procedures are also inlined by Guile's compiler in
order to take advantage of optimizations relating to floating point
math operations.  The downside is that since these are not pure
functions, they do not compose well and create more verbose code.

@subsubsection 2D Vectors

@deffn {Procedure} vec2 x y
Return a new 2D vector with coordinates (@var{x}, @var{y}).
@end deffn

@deffn {Procedure} vec2/polar r theta
Return a new 2D vector containing the Cartesian representation of the
polar coordinate (@var{r}, @var{theta}).  The angle @var{theta} is
measured in radians.
@end deffn

@deffn {Procedure} vec2? obj
Return @code{#t} if @var{obj} is a 2D vector.
@end deffn

@deffn {Procedure} vec2-x v
Return the X coordinate of the 2D vector @var{v}.
@end deffn

@deffn {Procedure} vec2-y v
Return the Y coordinate of the 2D vector @var{v}.
@end deffn

@deffn {Procedure} vec2-copy v
Return a fresh copy of the 2D vector @var{v}.
@end deffn

@deffn {Procedure} vec2-magnitude v
Return the magnitude of the 2D vector @var{v}.
@end deffn

@deffn {Procedure} vec2-dot v1 v2
Return the dot product of the 2D vectors @var{v1} and @var{v2}.
@end deffn

@deffn {Procedure} vec2-normalize v
Return the normalized form of the 2D vector @var{v}.
@end deffn

@deffn {Procedure} vec2+ v x
Add @var{x}, either a 2D vector or a scalar (i.e. a real number), to
the 2D vector @var{v} and return a new vector containing the sum.
@end deffn

@deffn {Procedure} vec2- v x
Subtract @var{x}, either a 2D vector or a scalar, from the 2D vector
@var{v} and return a new vector containing the difference.
@end deffn

@deffn {Procedure} vec2* v x
Multiply the 2D vector @var{v} by @var{x}, a 2D vector or a scalar,
and return a new vector containing the product.
@end deffn

@deffn {Procedure} set-vec2-x! v x
Set the X coordinate of the 2D vector @var{v} to @var{x}.
@end deffn

@deffn {Procedure} set-vec2-y! v y
Set the Y coordinate of the 2D vector @var{v} to @var{y}.
@end deffn

@deffn {Procedure} set-vec2! v x y
Set the X and Y coordinates of the 2D vector @var{v} to @var{x} and
@var{y}, respectively.
@end deffn

@deffn {Procedure} vec2-copy! source target
Copy the 2D vector @var{source} into the 2D vector @var{target}.
@end deffn

@deffn {Procedure} vec2-add! v x
Perform an in-place modification of the 2D vector @var{v} by adding
@var{x}, a 2D vector or a scalar.
@end deffn

@deffn {Procedure} vec2-sub! v x
Perform an in-place modification of the 2D vector @var{v} by
subtracting @var{x}, a 2D vector or a scalar.
@end deffn

@deffn {Procedure} vec2-mult! v x
Perform an in-place modification of the 2D vector @var{v} by
multiplying it by @var{x}, a 2D vector or a scalar.
@end deffn

@subsubsection 3D Vectors

@deffn {Procedure} vec3 x y
Return a new 2D vector with coordinates (@var{x}, @var{y}).
@end deffn

@deffn {Procedure} vec3? obj
Return @code{#t} if @var{obj} is a 3D vector.
@end deffn

@deffn {Procedure} vec3-x v
Return the X coordinate of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3-y v
Return the Y coordinate of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3-z v
Return the Z coordinate of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3-copy v
Return a fresh copy of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3-magnitude v
Return the magnitude of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3-dot v1 v2
Return the dot product of the 3D vectors @var{v1} and @var{v2}.
@end deffn

@deffn {Procedure} vec3-cross v1 v2
Return a new 3D vector containing the cross product of @var{v1} and
@var{v2}.
@end deffn

@deffn {Procedure} vec3-normalize v
Return the normalized form of the 3D vector @var{v}.
@end deffn

@deffn {Procedure} vec3+ v x
Add @var{x}, either a 3D vector or a scalar (i.e. a real number), to
the 3D vector @var{v} and return a new vector containing the sum.
@end deffn

@deffn {Procedure} vec3- v x
Subtract @var{x}, either a 3D vector or a scalar, from the 3D vector
@var{v} and return a new vector containing the difference.
@end deffn

@deffn {Procedure} vec3* v x
Multiply the 3D vector @var{v} by @var{x}, a 3D vector or a scalar,
and return a new vector containing the product.
@end deffn

@deffn {Procedure} set-vec3-x! v x
Set the X coordinate of the 3D vector @var{v} to @var{x}.
@end deffn

@deffn {Procedure} set-vec3-y! v y
Set the Y coordinate of the 3D vector @var{v} to @var{y}.
@end deffn

@deffn {Procedure} set-vec3-z! v z
Set the Z coordinate of the 3D vector @var{v} to @var{z}.
@end deffn

@deffn {Procedure} set-vec3! v x y z
Set the X, Y, and Z coordinates of the 3D vector @var{v} to @var{x},
@var{y}, and @var{z}, respectively.
@end deffn

@deffn {Procedure} vec3-copy! source target
Copy the 3D vector @var{source} into the 3D vector @var{target}.
@end deffn

@deffn {Procedure} vec3-add! v x
Perform an in-place modification of the 3D vector @var{v} by adding
@var{x}, a 3D vector or a scalar.
@end deffn

@deffn {Procedure} vec3-sub! v x
Perform an in-place modification of the 3D vector @var{v} by
subtracting @var{x}, a 3D vector or a scalar.
@end deffn

@deffn {Procedure} vec3-mult! v x
Perform an in-place modification of the 3D vector @var{v} by
multiplying it by @var{x}, a 3D vector or a scalar.
@end deffn

@deffn {Procedure} vec3-cross! dest v1 v2
Compute the cross product of the 3D vectors @var{v1} and @var{v2} and
store the result in @var{dest}.
@end deffn

@node Rectangles
@subsection Rectangles

The @code{(chickadee math rect)} module provides an API for
manipulating axis-aligned bounding boxes (AABBs).  AABBs are often
used for collision detection in games.  Common use-cases are defining
``hitboxes'' in platformers or using them for the ``broad phase'' of a
collision detection algorithm that uses a more complex (and thus
slower) method of determining the actual collisions.

Like some of the other math modules, there exists a collection of
functions that do in-place modification of rectangles for use in
performance critical code paths.

@deffn {Procedure} rect x y width height
@deffnx {Procedure} make-rect @var{x} @var{y} @var{width} @var{height}
Create a new rectangle that is @var{width} by @var{height} in size and
whose bottom-left corner is located at (@var{x}, @var{y}).
@end deffn

@deffn {Procedure} rect? obj
Return @code{#t} if @var{obj} is a rectangle.
@end deffn

@deffn {Procedure} rect-within? rect1 rect2
Return @code{#t} if @var{rect2} is completely within @var{rect1}.
@end deffn

@deffn {Procedure} rect-intersects? rect1 rect2
Return @code{#t} if @var{rect2} overlaps @var{rect1}.
@end deffn

@deffn {Procedure} rect-contains? rect x y
Return @code{#t} if the coordinates (@var{x}, @var{y}) are within
@var{rect}.
@end deffn

@deffn {Procedure} rect-contains-vec2? rect v
Return @code{#t} if the 2D vector @var{v} is within the bounds of
@var{rect}.
@end deffn

@deffn {Procedure} rect-x rect
Return the X coordinate of the lower-left corner of @var{rect}.
@end deffn

@deffn {Procedure} rect-y rect
Return the Y coordinate of the lower-left corner of @var{rect}.
@end deffn

@deffn {Procedure} rect-left rect
Return the left-most X coordinate of @var{rect}.
@end deffn

@deffn {Procedure} rect-right rect
Return the right-most X coordinate of @var{rect}.
@end deffn

@deffn {Procedure} rect-bottom rect
Return the bottom-most Y coordinate of @var{rect}.
@end deffn

@deffn {Procedure} rect-top rect
Return the top-most Y coordinate of @var{rect}.
@end deffn

@deffn {Procedure} rect-center-x rect
Return the X coordinate of the center of @var{rect}.
@end deffn

@deffn {Procedure} rect-center-y rect
Return the Y coordinate of the center of @var{rect}.
@end deffn

@deffn {Procedure} rect-width rect
Return the width of @var{rect}.
@end deffn

@deffn {Procedure} rect-height rect
Return the height of @var{rect}.
@end deffn

@deffn {Procedure} rect-area rect
Return the surface area covered by @var{rect}.
@end deffn

@deffn {Procedure} rect-clamp-x rect x
Restrict @var{x} to the portion of the X axis covered by @var{rect}.
@end deffn

@deffn {Procedure} rect-clamp-y rect y
Restrict @var{y} to the portion of the Y axis covered by @var{rect}.
@end deffn

@deffn {Procedure} rect-clamp rect1 rect2
Return a new rect that adjusts the location of @var{rect1} so that it
is completely within @var{rect2}.  An exception is thrown in the case
that @var{rect1} cannot fit completely within @var{rect2}.
@end deffn

@deffn {Procedure} rect-move rect x y
Return a new rectangle based on @var{rect} but moved to the
coordinates (@var{x}, @var{y}).
@end deffn

@deffn {Procedure} rect-move-vec2 rect v
Return a new rectangle based on @var{rect} but moved to the
coordinates in the 2D vector @var{v}.
@end deffn

@deffn {Procedure} rect-move-by rect x y
Return a new rectangle based on @var{rect} but moved by (@var{x},
@var{y}) units relative to its current location.
@end deffn

@deffn {Procedure} rect-move-by-vec2 rect v
Return a new rectangle based on @var{rect} but moved by the 2D vector
@var{v} relative to its current location.
@end deffn

@deffn {Procedure} rect-inflate rect width height
Return a new rectangle based on @var{rect}, but expanded by
@var{width} units on the X axis and @var{height} units on the Y axis,
while keeping the rectangle centered on the same point.
@end deffn

@deffn {Procedure} rect-union rect1 rect2
Return a new rectangle that completely covers the area of @var{rect1}
and @var{rect2}.
@end deffn

@deffn {Procedure} rect-clip rect1 rect2
Return a new rectangle that is the overlapping region of @var{rect1}
and @var{rect2}.  If the two rectangles do not overlap, a rectangle of
0 width and 0 height is returned.
@end deffn

@deffn {Procedure} set-rect-x! rect x
Set the left X coordinate of @var{rect} to @var{x}.
@end deffn

@deffn {Procedure} set-rect-y! rect y
Set the bottom Y coordinate of @var{rect} to @var{y}.
@end deffn

@deffn {Procedure} set-rect-width! rect width
Set the width of @var{rect} to @var{width}.
@end deffn

@deffn {Procedure} set-rect-height! rect height
Set the height of @var{rect} to @var{height}.
@end deffn

@deffn {Procedure} rect-move! rect x y
Move @var{rect} to (@var{x}, @var{y}) in-place.
@end deffn

@deffn {Procedure} rect-move-vec2! rect v
Move @var{rect} to the 2D vector @var{v} in-place.
@end deffn

@deffn {Procedure} rect-move-by! rect x y
Move @var{rect} by (@var{x}, @var{y}) in-place.
@end deffn

@deffn {Procedure} rect-move-by-vec2! rect v
Move @var{rect} by the 2D vector @var{v} in-place.
@end deffn

@deffn {Procedure} rect-inflate! rect width height
Expand @var{rect} by @var{width} and @var{height} in-place.
@end deffn

@deffn {Procedure} rect-union! rect1 rect2
Modify @var{rect1} in-place to completely cover the area of both
@var{rect1} and @var{rect2}.
@end deffn

@deffn {Procedure} rect-clip! rect1 rect2
Modify @var{rect1} in-place to be the overlapping region of
@var{rect1} and @var{rect2}.
@end deffn

@deffn {Procedure} rect-clamp! rect1 rect2
Adjust the location of @var{rect1} in-place so that its bounds are
completely within @var{rect2}.  An exception is thrown in the case
that @var{rect1} cannot fit completely within @var{rect2}.
@end deffn

@deffn {Procedure} vec2-clamp-to-rect! v rect
Restrict the coordinates of the 2D vector @var{v} so that they are
within the bounds of @var{rect}.  @var{v} is modified in-place.
@end deffn

@node Matrices
@subsection Matrices

The @code{(chickadee math matrix)} module provides an interface for
working with the most common type of matrices in game development: 4x4
transformation matrices.

@emph{Another Note About Performance}

Much like the vector API, the matrix API is commonly used in
performance critical code paths.  In order to reduce the amount of
garbage generated and improve matrix multiplication performance, there
are many procedures that perform in-place modifications of matrix
objects.

@subsubsection 3x3 Matrices

@deffn {Procedure} make-matrix3 aa ab ac ba bb bc ca cb cc
Return a new 3x3 initialized with the given 9 values in column-major
format.
@end deffn

@deffn {Procedure} make-null-matrix3
Return a new 3x3 matrix with all values initialized to 0.
@end deffn

@deffn {Procedure} make-identity-matrix3
Return a new 3x3 identity matrix.  Any matrix multiplied by the
identity matrix yields the original matrix.  This procedure is
equivalent to the following code:

@example
(make-matrix3 1 0 0
              0 1 0
              0 0 1)
@end example

@end deffn

@deffn {Procedure} matrix3? obj
Return @code{#t} if @var{obj} is a 3x3 matrix.
@end deffn

@deffn {Procedure} matrix3* . matrices
Return a new 3x3 matrix containing the product of multiplying all of
the given @var{matrices}.

Note: Remember that matrix multiplication is @strong{not} commutative!
@end deffn

@deffn {Procedure} matrix3-translate v
Return a new 3x3 matrix that represents a translation by @var{v}, a 2D
vector.
@end deffn

@deffn {Procedure} matrix3-scale s
Return a new 3x3 matrix that represents a scaling along the x and y
axes by the scaling factor @var{s}, a number or 2D vector.
@end deffn

@deffn {Procedure} matrix3-rotate angle
Return a new 3x3 matrix that represents a rotation by @var{angle}
radians.
@end deffn

@deffn {Procedure} matrix3-transform matrix v
Return a new 2D vector that is @var{v} as transformed by the 3x3
matrix @var{matrix}.
@end deffn

@deffn {Procedure} matrix3-inverse matrix
Return the inverse of @var{matrix}.
@end deffn

The following procedures perform in-place, destructive updates to 3x3
matrix objects:

@deffn {Procedure} matrix3-identity! matrix
Modify @var{matrix} in-place to contain the identity matrix.
@end deffn

@deffn {Procedure} matrix3-mult! dest a b
Multiply the 3x3 matrix @var{a} by the 3x3 matrix @var{b} and store
the result in the 3x3 matrix @var{dest}.
@end deffn

@deffn {Procedure} matrix3-translate! matrix v
Modify @var{matrix} in-place to contain a translation by @var{v}, a 2D
vector.
@end deffn

@deffn {Procedure} matrix3-scale! matrix s
Modify @var{matrix} in-place to contain a scaling along the x and y
axes by the scaling factor @var{s}, a number or 2D vector.
@end deffn

@deffn {Procedure} matrix3-rotate! matrix angle
Modify @var{matrix} in-place to contain a rotation by @var{angle}
radians.
@end deffn

@deffn {Procedure} matrix3-transform! matrix v
Modify the 2D vector @var{v} in-place to contain @var{v} as
transformed by the 3x3 matrix @var{matrix}.
@end deffn

@deffn {Procedure} matrix3-inverse! matrix target
Compute the inverse of @var{matrix} and store the results in
@var{target}.
@end deffn

@subsubsection 4x4 Matrices

@deffn {Procedure} make-matrix4 aa ab ac ad @
                                ba bb bc bd @
                                ca cb cc cd @
                                da db dc dd

Return a new 4x4 matrix initialized with the given 16 values in
column-major format.
@end deffn

@deffn {Procedure} make-null-matrix4
Return a new 4x4 matrix with all values initialized to 0.
@end deffn

@deffn {Procedure} make-identity-matrix4
Return a new 4x4 identity matrix.  Any matrix multiplied by the
identity matrix yields the original matrix.  This procedure is
equivalent to the following code:

@example
(make-matrix4 1 0 0 0
              0 1 0 0
              0 0 1 0
              0 0 0 1)
@end example

@end deffn

@deffn {Procedure} matrix4? obj
Return @code{#t} if @var{obj} is a 4x4 matrix.
@end deffn

@deffn {Procedure} matrix4* . matrices
Return a new 4x4 matrix containing the product of multiplying all of
the given @var{matrices}.

Note: Remember that matrix multiplication is @strong{not} commutative!
@end deffn

@deffn {Procedure} orthographic-projection left right top bottom near far

Return a new 4x4 matrix that represents an orthographic (2D)
projection for the horizontal clipping plane @var{top} and
@var{bottom}, the vertical clipping plane @var{top} and @var{bottom},
and the depth clipping plane @var{near} and @var{far}.
@end deffn

@deffn {Procedure} perspective-projection fov aspect-ratio near far

Return a new 4x4 matrix that represents a perspective (3D) projection
with a field of vision of @var{fov} radians, an aspect ratio of
@var{aspect-ratio}, and a depth clipping plane defined by @var{near}
and @var{far}.
@end deffn

@deffn {Procedure} matrix4-translate x
Return a new 4x4 matrix that represents a translation by @var{x}, a 2D
vector, a 3D vector, or a rectangle (in which case the bottom-left
corner of the rectangle is used).
@end deffn

@deffn {Procedure} matrix4-scale s
Return a new 4x4 matrix that represents a scaling along the X, Y, and
Z axes by the scaling factor @var{s}, a real number.
@end deffn

@deffn {Procedure} matrix4-rotate q
Return a new 4x4 matrix that represents a rotation about an arbitrary
axis defined by the quaternion @var{q}.
@end deffn

@deffn {Procedure} matrix4-rotate-z theta
Return a new 4x4 matrix that represents a rotation about the Z axis by
@var{theta} radians.
@end deffn

@deffn {Procedure} matrix4-identity! matrix
Modify @var{matrix} in-place to contain the identity matrix.
@end deffn

@deffn {Procedure} matrix4-mult! dest a b
Multiply the 4x4 matrix @var{a} by the 4x4 matrix @var{b} and store
the result in the 4x4 matrix @var{dest}.
@end deffn

@deffn {Procedure} matrix4-translate! matrix x
Modify @var{matrix} in-place to contain a translation by @var{x}, a 2D
vector, a 3D vector, or a rectangle (in which case the bottom-left
corner of the rectangle is used).
@end deffn

@deffn {Procedure} matrix4-scale! matrix s
Modify @var{matrix} in-place to contain a scaling along the X, Y, and
Z axes by the scaling factor @var{s}, a real number.
@end deffn

@deffn {Procedure} matrix4-rotate! matrix q
Modify @var{matrix} in-place to contain a rotation about an arbitrary
axis defined by the quaternion @var{q}.
@end deffn

@deffn {Procedure} matrix4-rotate-z! matrix theta
Modify @var{matrix} in-place to contain a rotation about the Z axis by
@var{theta} radians.
@end deffn

@deffn {Procedure} matrix4-2d-transform! matrix [#:origin] @
                                         [#:position] [#:rotation] @
                                         [#:scale] [#:skew]

Modify @var{matrix} in-place to contain the transformation described
by @var{position}, a 2D vector or rectangle, @var{rotation}, a scalar
representing a rotation about the Z axis, @var{scale}, a 2D vector,
and @var{skew}, a 2D vector.  The transformation happens with respect
to @var{origin}, a 2D vector.  If an argument is not provided, that
particular transformation will not be included in the result.
@end deffn

@deffn {Procedure} matrix4-transform! matrix v
Modify the 2D vector @var{v} in-place by multiplying it by the 4x4
matrix @var{matrix}.
@end deffn

@node Quaternions
@subsection Quaternions

In game development, the quaternion is most often used to represent
rotations.  Why not use a matrix for that, you may ask.  Unlike
matrices, quaternions can be interpolated (animated) and produce a
meaningful result.  When interpolating two quaternions, there is a
smooth transition from one rotation to another, whereas interpolating
two matrices would yield garbage.

@deffn {Procedure} quaternion x y z w
Return a new quaternion with values @var{x}, @var{y}, @var{z}, and
@var{w}.
@end deffn

@deffn {Procedure} quaternion? obj
Return @code{#t} if @var{obj} is a quaternion.
@end deffn

@deffn {Procedure} quaternion-w q
Return the W component of the quaternion @var{q}.
@end deffn

@deffn {Procedure} quaternion-x q
Return the X component of the quaternion @var{q}.
@end deffn

@deffn {Procedure} quaternion-y q
Return the Y component of the quaternion @var{q}.
@end deffn

@deffn {Procedure} quaternion-z q
Return the Z component of the quaternion @var{q}.
@end deffn

@deffn {Procedure} make-identity-quaternion
Return the identity quaternion.
@end deffn

@node Easings
@subsection Easings

Easing functions are essential for animation.  Each easing function
provides a different path to go from an initial value to a final
value.  These functions make an excellent companion to the
@code{tween} procedure (@pxref{Tweening}).  Experiment with them to
figure out which function makes an animation look the best.

Pro tip: @code{smoothstep} provides nice results most of the time and
creates smoother animation than using @code{linear}.

@deffn {Procedure} linear t
@end deffn

@deffn {Procedure} smoothstep t
@end deffn

@deffn {Procedure} ease-in-quad t
@end deffn

@deffn {Procedure} ease-out-quad t
@end deffn

@deffn {Procedure} ease-in-out-quad t
@end deffn

@deffn {Procedure} ease-in-cubic t
@end deffn

@deffn {Procedure} ease-out-cubic t
@end deffn

@deffn {Procedure} ease-in-out-cubic t
@end deffn

@deffn {Procedure} ease-in-quart t
@end deffn

@deffn {Procedure} ease-out-quart t
@end deffn

@deffn {Procedure} ease-in-out-quart t
@end deffn

@deffn {Procedure} ease-in-quint t
@end deffn

@deffn {Procedure} ease-out-quint t
@end deffn

@deffn {Procedure} ease-in-out-quint t
@end deffn

@deffn {Procedure} ease-in-sine t
@end deffn

@deffn {Procedure} ease-out-sine t
@end deffn

@deffn {Procedure} ease-in-out-sine t
@end deffn

@node Bezier Curves
@subsection Bezier Curves

The @code{(chickadee math bezier)} module provides an API for
describing cubic Bezier curves in 2D space.  These curves are notably
used in font description, vector graphics programs, and when it comes
to games: path building.  With Bezier curves, it's somewhat easy to
create a smooth looking path for an enemy to move along, for example.
Bezier curves become particularly interesting when they are chained
together to form a Bezier ``path'', where the end point of one curve
becomes the starting point of the next.

@deffn {Procedure} make-bezier-curve p0 p1 p2 p3
Return a new Bezier curve object whose starting point is @var{p0},
ending point is @var{p3}, and control points are @var{p1} and
@var{p2}.  All points are 2D vectors.
@end deffn

@deffn {Procedure} bezier-curve? obj
Return @code{#t} if @var{obj} is a Bezier curve.
@end deffn

@deffn {Procedure} bezier-curve-p0 bezier
Return the starting point of @var{bezier}.
@end deffn

@deffn {Procedure} bezier-curve-p1 bezier
Return the first control point of @var{bezier}.
@end deffn

@deffn {Procedure} bezier-curve-p2 bezier
Return the second control point of @var{bezier}.
@end deffn

@deffn {Procedure} bezier-curve-p3 bezier
Return the end point of @var{bezier}.
@end deffn

@deffn {Procedure} bezier-path . control-points
Return a list of connected bezier curves defined by
@var{control-points}.  The first curve is defined by the first 4
arguments and every additional curve thereafter requires 3 additional
arguments.
@end deffn

@deffn {Procedure} bezier-curve-point-at bezier t
Return the coordinates for @var{bezier} at @var{t} (a value in the
range [0, 1] representing how far from the start of the curve to
check) as a 2D vector.
@end deffn

@deffn {Procedure} bezier-curve-point-at! dest bezier t
Modify the 2D vector @var{dest} in-place to contain the coordinates
for @var{bezier} at @var{t}.
@end deffn

@node Path Finding
@subsection Path Finding

Most game worlds have maps.  Often, these games have a need to move
non-player characters around in an unscripted fashion.  For example,
in a real-time strategy game, the player may command one of their
units to attack something in the enemy base.  To do so, the unit must
calculate the shortest route to get there.  It wouldn't be a very fun
game if units didn't know how to transport themselves efficiently.
This is where path finding algorithms come in handy.  The
@code{(chickadee math path-finding)} module provides a generic
implementation of the popular A* path finding algorithm.  Just add a
map implementation!

The example below defines a very simple town map and finds the
quickest way to get from the town common to the school.

@example
(define world-map
  '((town-common . (town-hall library))
    (town-hall . (town-common school))
    (library . (town-common cafe))
    (school . (town-hall cafe))
    (cafe . (library school))))
(define (neighbors building)
  (assq-ref town-map building))
(define (cost a b) 1)
(define (distance a b) 1)
(define pf (make-path-finder))
(a* pf 'town-common 'school neighbors cost distance)
@end example

In this case, the @code{a*} procedure will return the list
@code{(town-common town-hall school)}, which is indeed the shortest
route.  (The other possible route is @code{(town-common library cafe
school)}.)

The @code{a*} procedure does not know anything about about any kind of
map and therefore must be told how to look up neighboring nodes, which
is what the @code{neighbors} procedure in the example does. To
simulate different types of terrain, a cost procedure is used.  In
this example, it is just as easy to move between any two nodes because
@code{cost} always returns 1.  In a real game, perhaps moving from
from a field to a rocky hill would cost a lot more than moving from
one field to another.  Finally, a heuristic is used to calculate an
approximate distance between two nodes on the map.  In this simple
association list based graph it is tough to calculate a distance
between nodes, so the @code{distance} procedure isn't helpful and
always returns 1.  In a real game with a tile-based map, for example,
the heuristic could be a quick Manhattan distance calculation based on
the coordinates of the two map tiles.  Choose an appropriate heuristic
for optimal path finding!

@deffn {Procedure} make-path-finder
Return a new path finder object.
@end deffn

@deffn {Procedure} path-finder? obj
Return @code{#t} if @var{obj} is a path finder.
@end deffn

@deffn {Procedure} a* path-finder start goal neighbors cost distance

Return a list of nodes forming a path from @var{start} to @var{goal}
using @var{path-finder} to hold state.  @var{neighbors} is a procedure
that accepts a node and returns a list of nodes that neighbor it.
@var{cost} is a procedure that accepts two neighboring nodes and
returns the cost of moving from the first to the second as a real
number.  @var{distance} is a procedure that accepts two nodes and
returns an approximate distance between them.
@end deffn

@node Grid
@subsection Grid

The @code{(chickadee math grid)} module provides a simple spatial
partitioning system for axis-aligned bounding boxes
(@pxref{Rectangles}) in 2D space.  The grid divides the world into
tiles and keeps track of which rectangles occupy which tiles.  When
there are lots of moving objects in the game world that need collision
detection, the grid greatly speeds up the process.  Instead of
checking collisions of each object against every other object (an
O(n^2) operation), the grid quickly narrows down which objects could
possibly be colliding and only performs collision testing against a
small set of objects.

In addition to checking for collisions, the grid also handles the
resolution of collisions.  Exactly how each collision is resolved is
user-defined.  A player bumping into a wall may slide against it.  An
enemy colliding with a projectile shot by the player may get pushed
back in the opposite direction.  Two players colliding may not need
resolution at all and will just pass through each other.  The way this
works is that each time an object (A) is moved within the grid, the
grid looks for an object (B) that may possibly be colliding with A.  A
user-defined procedure known as a ``filter'' is then called with both
A and B.  If the filter returns @code{#f}, it means that even if A and
B are colliding, no collision resolution is needed.  In this case the
grid won't waste time checking if they really do collide because it
doesn't matter.  If A and B are collidable, then the filter returns a
procedure that implements the resolution technique.  The grid will
then perform a collision test.  If A and B are colliding, the resolver
procedure is called.  It's the resolvers job to adjust the objects
such that they are no longer colliding.  The grid module comes with a
very simple resolution procedure, @code{slide}, that adjusts object A
by the smallest amount so that it no longer overlaps with B.  By using
this filtering technique, a game can resolve collisions between
different objects in different ways.

@deffn {Procedure} make-grid [cell-size 64]
Return a new grid partitioned into @var{cell-size} tiles.
@end deffn

@deffn {Procedure} grid? obj
Return @code{#t} if @var{obj} is a grid.
@end deffn

@deffn {Procedure} cell? obj
Return @code{#t} if @var{obj} is a grid cell.
@end deffn

@deffn {Procedure} cell-count cell
Return the number of items in @var{cell}.
@end deffn

@deffn {Procedure} grid-cell-size grid
Return the cell size of @var{grid}.
@end deffn

@deffn {Procedure} grid-cell-count grid
Return the number of cells currently in @var{grid}.
@end deffn

@deffn {Procedure} grid-item-count grid
Return the number of items in @var{grid}.
@end deffn

@deffn {Procedure} grid-add grid item x y @
                            width height

Add @var{item} to @var{grid} represented by the axis-aligned bounding
box whose lower-left corner is at (@var{x}, @var{y}) and is
@var{width} x @var{height} in size.
@end deffn

@deffn {Procedure} grid-remove grid item
Return @var{item} from @var{grid}.
@end deffn

@deffn {Procedure} grid-clear grid
Remove all items from @var{grid}.
@end deffn

@deffn {Procedure} grid-move grid item position filter
Attempt to move @var{item} in @var{grid} to @var{position} (a 2D
vector) and check for collisions.  For each collision, @var{filter}
will be called with two arguments: @var{item} and the item it collided
with.  If a collision occurs, @var{position} may be modified to
resolve the colliding objects.
@end deffn

@deffn {Procedure} for-each-cell proc grid [rect]
Call @var{proc} with each cell in @var{grid} that intersects
@var{rect}, or every cell if @var{rect} is @code{#f}.
@end deffn

@deffn {Procedure} for-each-item proc grid
Call @var{proc} for each item in @var{grid}.
@end deffn

@deffn {Procedure} slide item item-rect other other-rect goal

Resolve the collision that occurs between @var{item} and @var{other}
when moving @var{item-rect} to @var{goal} by sliding @var{item-rect}
the minimum amount needed to make it no longer overlap
@var{other-rect}.
@end deffn

@node Graphics
@section Graphics

Chickadee aims to make hardware-accelerated graphics rendering as
simple and efficient as possible by providing high-level APIs that
interact with the low-level OpenGL API under the hood.  Anyone that
has worked with OpenGL directly knows that it has a steep learning
curve and a lot of effort is needed to render even a single triangle.
The Chickadee rendering engine attempts to make it easy to do common
tasks like rendering a sprite while also providing all of the building
blocks to implement additional rendering techniques.

@menu
* Colors::                      Such pretty colors...
* Textures::                    2D images.
* Sprites::                     Draw 2D images.
* 9-Patches::                   Scalable bitmap boxes.
* Fonts::                       Drawing text.
* Vector Paths::                Draw filled and stroked paths.
* Particles::                   Pretty little flying pieces!
* Tile Maps::                   Draw 2D tile maps.
* 3D Models::                   Spinning teapots everywhere.
* Blending::                    Control how pixels are combined.
* Framebuffers::                Render to texture.
* Viewports::                   Restrict rendering to a particular area.
* Rendering Engine::            Rendering state management.
* Buffers::                     Send data to the GPU.
* Shaders::                     Create custom GPU programs.
@end menu

@node Colors
@subsection Colors

Merriam-Webster defines color as ``a phenomenon of light (such as red,
brown, pink, or gray) or visual perception that enables one to
differentiate otherwise identical objects.''  In this essay, I
will@dots{}

Okay, okay.  We all know what colors are.  Chickadee provides a data
type to represent color and some convenient procedures to work with
them in the @code{(chickadee graphics color)} module.  Colors are made
up of four components, or channels: red, green, blue, and alpha
(transparency.)  Each of these values is expressed as a uniform
floating point value in the range [0, 1].  0 means that color channel
is unrepresented in the resulting color, whereas 1 means that color
channel is at full intensity.

Making a color object is easy, and there's a few ways to do it
depending on what's most convenient.  The first is @code{make-color},
where you specify each channel exactly as described above.  This is
fully opaque magenta:

@example
(make-color 1.0 0.0 1.0 1.0)
@end example

Many people are used to representing colors as 6 or 8 digit
hexadecimal numbers, so Chickadee also allows that.  Here's magenta,
again:

@example
(rgba #xFF00FFFF)
(rgb #xFF00FF) ; equivalent to the above
@end example

@deffn {Procedure} make-color r g b a
Return a new color object with a red value of @var{r}, a green value
of @var{g}, a blue value of @var{b}, and an alpha (transparency) value
of @var{a}.  All values are clamped to the range [0, 1].
@end deffn

@deffn {Procedure} rgba color-code
Return a new color object using the values of the first 32 bits of
@var{color-code}.  Each channel occupies 8 bits.  Starting from the
most significant bit, red is first, followed by green, then blue, then
alpha.  Color codes are often represented as 6 or 8 digit hexadecimal
numbers in various other programs.
@end deffn

@deffn {Procedure} rgb color-code
Like @code{rgba}, but @var{color-code} is a 24 bit code with no alpha
channel.
@end deffn

@deffn {Procedure} color? obj
Return @code{#t} if @var{obj} is a color object.
@end deffn

@deffn {Procedure} color-r color
Return the red channel of @var{color}.
@end deffn

@deffn {Procedure} color-g color
Return the green channel of @var{color}.
@end deffn

@deffn {Procedure} color-b color
Return the blue channel of @var{color}.
@end deffn

@deffn {Procedure} color-a color
Return the alpha channel of @var{color}.
@end deffn

@deffn {Procedure} transparency alpha
Return a new color that is white (RGB channels set to 1) with an alpha
channel value of @var{alpha}.  This can be useful for creating a color
that can be multiplied against another color to make it more
transparent.
@end deffn

@deffn {Procedure} string->color s
Convert the hexadecimal color code in the string @var{s} to a color
object.  The following string formats are supported:

@example
(string->color "#FF00FFFF")
(string->color "FF00FFFF")
(string->color "#FF00FF")
(string->color "FF00FF")
@end example

@end deffn

@deffn {Procedure} color* a b
Multiply the color @var{a} with the color or number @var{b} and return
a new color with the result.
@end deffn

@deffn {Procedure} color+ a b
Add the color @var{a} to the color @var{b} and return a new color with
the result.
@end deffn

@deffn {Procedure} color- a b
Subtract the color @var{b} from the color @var{a} and return a new
color with the result.
@end deffn

@deffn {Procedure} color-inverse color
Invert the red, green, and blue channels of @var{color} and return a
new color with the result.
@end deffn

@deffn {Procedure} color-lerp start end alpha
Linearly interpolate the colors @var{start} and @var{end} using the
factor @var{alpha}, a number in the range [0, 1].
@end deffn

@subsubsection Stock Colors

For convenience, Chickadee comes with some basic colors predefined:

@defvar white
@end defvar

@defvar black
@end defvar

@defvar red
@end defvar

@defvar green
@end defvar

@defvar blue
@end defvar

@defvar yellow
@end defvar

@defvar magenta
@end defvar

@defvar cyan
@end defvar

For fun, there are also predefined colors for the classic
@url{https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette,
Tango color palette}.

@defvar tango-light-butter
@end defvar

@defvar tango-butter
@end defvar

@defvar tango-dark-butter
@end defvar

@defvar tango-light-orange
@end defvar

@defvar tango-orange
@end defvar

@defvar tango-dark-orange
@end defvar

@defvar tango-light-chocolate
@end defvar

@defvar tango-chocolate
@end defvar

@defvar tango-dark-chocolate
@end defvar

@defvar tango-light-chameleon
@end defvar

@defvar tango-chameleon
@end defvar

@defvar tango-dark-chameleon
@end defvar

@defvar tango-light-sky-blue
@end defvar

@defvar tango-sky-blue
@end defvar

@defvar tango-dark-sky-blue
@end defvar

@defvar tango-light-plum
@end defvar

@defvar tango-plum
@end defvar

@defvar tango-dark-plum
@end defvar

@defvar tango-light-scarlet-red
@end defvar

@defvar tango-scarlet-red
@end defvar

@defvar tango-dark-scarlet-red
@end defvar

@defvar tango-aluminium-1
@end defvar

@defvar tango-aluminium-2
@end defvar

@defvar tango-aluminium-3
@end defvar

@defvar tango-aluminium-4
@end defvar

@defvar tango-aluminium-5
@end defvar

@defvar tango-aluminium-6
@end defvar

@node Textures
@subsection Textures

Textures are essentially images: a 2D grid of color values.  The
@code{(chickadee graphics texture)} module provides an interface for
working with texture objects.

@deffn {Procedure} load-image file [#:min-filter nearest] @
       [#:mag-filter nearest] [#:wrap-s repeat] [#:wrap-t repeat] @
       [#:transparent-color]

Load the image data from @var{file} and return a new texture object.

@var{min-filter} and @var{mag-filter} describe the method that should
be used for minification and magnification when rendering,
respectively.  Possible values are @code{nearest} and @code{linear}.

@var{wrap-s} and @var{wrap-t} describe how to interpret texture
coordinates that are greater than @code{1.0}.  Possible values are
@code{repeat}, @code{mirrored-repeat}, @code{clamp},
@code{clamp-to-border}, and @code{clamp-to-edge}.

For color-keyed images (images where a specific color should be made
transparent), specify the appropriate @var{transparent-color}.

@end deffn

@deffn {Procedure} texture? obj
Return @code{#t} if @var{obj} is a texture.
@end deffn

@deffn {Procedure} texture-region? obj
Return @code{#t} if @var{obj} is a texture region.
@end deffn

@deffn {Procedure} texture-parent texture
If @var{texture} is a texture region, return the full texture that it
is based upon.  Otherwise, return @code{#f}.
@end deffn

@deffn {Procedure} texture-min-filter texture
Return the minification filter for @var{texture}, either
@code{nearest} or @code{linear}.
@end deffn

@deffn {Procedure} texture-mag-filter texture
Return the magnification filter for @var{texture}, either
@code{nearest} or @code{linear}.
@end deffn

@deffn {Procedure} texture-wrap-s texture
Return the method used for wrapping texture coordinates along the X
axis for @var{texture}.

Possible wrapping methods:
@itemize
@item @code{repeat}
@item @code{clamp}
@item @code{clamp-to-border}
@item @code{clamp-to-edge}
@end itemize

@end deffn

@deffn {Procedure} texture-wrap-t texture
Return the method used for wrapping texture coordinates along the Y
axis for @var{texture}.
@end deffn

@deffn {Procedure} texture-width texture
Return the width of @var{texture} in pixels.
@end deffn

@deffn {Procedure} texture-height texture
Return the height of @var{texture} in pixels.
@end deffn

It is common practice to combine multiple bitmap images into a single
texture, known as a ``tile atlas'' or ``tile set'', because it is more
efficient to render many regions of a large texture than it is to
render a bunch of small textures.  Chickadee provides a tile atlas
data type for collecting texture regions into a single vector.

@deffn {Procedure} split-texture texture tile-width tile-height @
                                 [#:margin 0] [#:spacing 0]

Return a new texture atlas that splits @var{texture} into a grid of
@var{tile-width} by @var{tile-height} rectangles.  Optionally, each
tile may have @var{spacing} pixels of horizontal and vertical space
between surrounding tiles and the entire image may have @var{margin}
pixels of empty space around its border.

This type of texture atlas layout is very common for 2D tile maps.
@xref{Tile Maps} for more information.
@end deffn

@deffn {Procedure} load-tileset file-name tile-width tile-height @
                                [#:margin 0] [#:spacing 0] @
                                [#:min-filter nearest] @
                                [#:mag-filter nearest] [#:wrap-s repeat] [#:wrap-t repeat] @
                                [#:transparent-color]

Return a new texture atlas that splits the texture loaded from the
file @var{file-name} into a grid of @var{tile-width} by
@var{tile-height} rectangles.  See @code{load-image} and
@code{split-texture} for information about all keyword arguments.
@end deffn

@deffn {Procedure} texture-atlas? obj
Return @code{#t} if @var{obj} is a texture atlas.
@end deffn

@deffn {Procedure} texture-atlas-texture atlas
Return the texture that all texture regions in @var{atlas} have been created from.
@end deffn

@deffn {Procedure} texture-atlas-ref atlas index
Return the texture region in @var{atlas} at @var{index}.
@end deffn

@node Sprites
@subsection Sprites

For those who are new to this game, a sprite is a 2D rectangular
bitmap that is rendered to the screen.  For 2D games, sprites are the
most essential graphical abstraction.  They are used for drawing maps,
players, NPCs, items, particles, text, etc.

In Chickadee, the @code{(chickadee graphics sprite)} module provides the
interface for working with sprites.  Bitmaps are stored in textures
(@pxref{Textures}) and can be used to draw sprites via the
@code{draw-sprite} procedure.

@deffn {Procedure} draw-sprite texture position @
       [#:tint white] [#:origin] [#:scale] [#:rotation] [#:blend-mode] @
       [#:rect]

Draw @var{texture} at @var{position}.

Optionally, other transformations may be applied to the sprite.
@var{rotation} specifies the angle to rotate the sprite, in radians.
@var{scale} specifies the scaling factor as a 2D vector.  All
transformations are applied relative to @var{origin}, a 2D vector,
which defaults to the lower-left corner.

@var{tint} specifies the color to multiply against all the sprite's
pixels.  By default white is used, which does no tinting at all.

Alpha blending is used by default but the blending method can be
changed by specifying @var{blend-mode}.

The area drawn to is as big as the texture, by default.  To draw to an
arbitrary section of the screen, specify @var{rect}.
@end deffn

It's not uncommon to need to draw hundreds or thousands of sprites
each frame.  However, GPUs (graphics processing units) are tricky
beasts that prefer to be sent few, large chunks of data to render
rather than many, small chunks.  Using @code{draw-sprite} on its own
will involve at least one GPU call @emph{per sprite}.  This is fine
for rendering a few dozen sprites, but will become a serious
bottleneck when rendering hundreds or thousands of sprites.  To deal
with this, a technique known as ``sprite batching'' is used.  Instead
of drawing each sprite immediately, the sprite batch will build up a
large of buffer of sprites to draw and send them to the GPU all at
once.  There is one caveat, however.  Batching only works if the
sprites being drawn share a common texture.  A good strategy for
reducing the number of different textures is to stuff many bitmaps
into a single image file and create a ``texture atlas''
(@pxref{Textures}) to access the sub-images within.

@deffn {Procedure} make-sprite-batch texture [#:capacity 256]
Create a new sprite batch for @var{texture} with initial space for
@var{capacity} sprites.  Sprite batches automatically resize when they
are full to accomodate as many sprites as necessary.
@end deffn

@deffn {Procedure} sprite-batch? obj
Return @code{#t} if @var{obj} is a sprite batch.
@end deffn

@deffn {Procedure} sprite-batch-texture batch
Return the texture for @var{batch}.
@end deffn

@deffn {Procedure} set-sprite-batch-texture! batch texture
Set texture for @var{batch} to @var{texture}.
@end deffn

@deffn {Procedure} sprite-batch-add! batch position @
                   [#:origin] [#:scale] [:rotation] @
                   [#:tint @code{white}] [#:texture-region]

Add sprite located at @var{position} to @var{batch}.

To render a subsection of the batch's texture, a texture object whose
parent is the batch texture may be specified as @var{texture-region}.

See @code{draw-sprite} for information about the other arguments.
@end deffn

@deffn {Procedure} sprite-batch-clear! batch
Reset size of @var{batch} to 0.
@end deffn

@deffn {Procedure} draw-sprite-batch batch [#:blend-mode]
Render @var{batch} using @var{blend-mode}.  Alpha blending is used by
default.
@end deffn

@node 9-Patches
@subsection 9-Patches

A 9-patch is a method of rendering a texture so that it can be
stretched to cover an area of any size without becoming distorted.
This is achieved by dividing up the sprite into nine regions:

@itemize
@item
the center, which can be stretched or tiled horizontally and vertically
@item
the four corners, which are never stretched or tiled
@item
the left and right sides, which can be stretched or tiled vertically
@item
the top and bottom sides, which can be stretched or tiled horizontally
@end itemize

The most common application of this technique is for graphical user
interface widgets like buttons and dialog boxes which are often
dynamically resizable.  By using a 9-patch, they can be rendered at
any size without scaling artifacts.

@deffn {Procedure} draw-9-patch texture rect @
       [#:margin 0] [#:top-margin margin] [#:bottom-margin margin] @
       [#:left-margin margin] [#:right-margin margin] [#:mode stretch] @
       [#:origin] [#:scale] [#:rotation] [#:blend-mode] @
       [#:tint white]

Draw a 9-patch over the area @var{rect} using @var{texture} whose
stretchable/tileable patches are defined by the given margin
measurements.  The corners are never stretched/tiled, the left and
right edges will be stretched/tiled vertically, the top and bottom
edges may be stretched/tiled horizontally, and the center may be
stretched/tiled in both directions.

@var{mode} may be either @code{stretch} (the default) or @code{tile}.

@var{margin} specifies the margin size for all sides of the 9-patch.
To make margins of differing sizes, the @var{top-margin},
@var{bottom-margin}, @var{left-margin}, and @var{right-margin}
arguments may be used.

Refer to @code{draw-sprite} (@pxref{Sprites}) for information about
the other arguments as they are the same.
@end deffn

@node Fonts
@subsection Fonts

Printing text to the screen is quite easy:

@example
(draw-text "Hello, world" (vec2 100.0 100.0))
@end example

Chickadee supports OpenType/TrueType fonts (via the FreeType library),
bitmap fonts in Angel Code bmfont format, and simple sprite sheet
bitmap fonts.  A default font named Inconsolata is used for all text
rendering operations where a font is not specified, as is the case in
the above example.

The following procedures can be found in the @code{(chickadee graphics
font)} module:

@deffn {Procedure} load-font file-name point-size [#:char-set]
Load the scalable (OpenType, TrueType, etc.) font in the file
@var{file-name} and display it at the given @var{point-size}.  By
default, all the characters in the ASCII character set are loaded.
This can be changed by passing a different character set
(@pxref{Character Sets,,, guile, GNU Guile Reference Manual}) using
the @var{char-set} keyword argument.
@end deffn

@deffn {Procedure} load-bitmap-font file
Load the Angel Code font (in either XML or FNT format) in @var{file}
and return a new font object.
@end deffn

@deffn {Procedure} font? obj
Return @code{#t} if @var{obj} is a font object.
@end deffn

@deffn {Procedure} font-face font
Return the name of @var{font}.
@end deffn

@deffn {Procedure} font-line-height font
Return the line height of @var{font}.
@end deffn

@deffn {Procedure} font-line-height font
Return the line height of @var{font}.
@end deffn

@deffn {Procedure} font-bold? font
Return @code{#t} if @var{font} is a bold font.
@end deffn

@deffn {Procedure} font-italic? font
Return @code{#t} if @var{font} is an italicized font.
@end deffn

@deffn {Procedure} draw-text text position
       [#:font] [#:color] [#:origin] [#:scale] [#:rotation] [#:blend-mode]
       [#:start 0] [#:end @code{(string-length text)}]

Draw the string @var{text} with the first character starting at
@var{position} using @var{font}.  If @var{font} is not specified, a
built-in font is used.

@example
(draw-text "Hello, world!" (vec2 128.0 128.0))
@end example

To render a substring of @var{text}, use the @var{start} and @var{end}
arguments.

Refer to @code{draw-sprite} (@pxref{Sprites}) for information about
the other arguments.
@end deffn

@node Vector Paths
@subsection Vector Paths

The @code{(chickadee graphics path)} module can be used to draw lines,
curves, circles, rectangles, and more in a scalable, resolution
independent manner.  It is @emph{not} an SVG compliant renderer, nor
does it intend to be.  However, those familiar with SVG and/or the
HTML5 Canvas API should find lots of similarities.

@emph{This API is considered to be experimental and may change
substantially in future releases of Chickadee.  There are many missing
features such as gradient fills and dashed strokes.}

The first step to rendering vector graphics is to create a
@emph{path}: A series of commands that can be thought of as moving a
pen around a piece of paper.  A path can be either open or closed.  A
closed path draws a straight line from the last point in the path to
the first.

@deffn {Procedure} path . commands
Return a new path that follows @var{commands}.

@example
(path (move-to (vec2 50.0 50.0))
      (line-to (vec2 500.0 50.0))
      (line-to (vec2 400.0 200.0))
      (bezier-to (vec2 500.0 250.0) (vec2 380.0 300.0) (vec2 400.0 400.0))
      (line-to (vec2 300.0 400.0))
      (close-path))
@end example

@end deffn

Available drawing commands:

@deffn {Procedure} move-to point
Pick up the pen and move it to @var{point}.
@end deffn

@deffn {Procedure} line-to point
Draw a line from the current pen position to @var{point}.
@end deffn

@deffn {Procedure} bezier-to control1 control2 point
Draw a cubic bezier curve from the current pen position to
@var{point}.  The shape of the curve is determined by the two control
points: @var{control1} and @var{control2}.
@end deffn

@deffn {Procedure} close-path
Draw a straight line back to the first point drawn in the path.
@end deffn

@deffn {Procedure} arc center rx ry angle-start angle-end
Draw an elliptical arc spanning the angle range [@var{angle-start},
@var{angle-end}], centered at @var{center} with radii @var{rx} and
@var{ry} (set both to the same value for a circular arc.)
@end deffn

Included are some helpful procedures for generating common types of
paths:

@deffn {Procedure} line start end
Return a path that draws a straight line from @var{start} to @var{end}.
@end deffn

@deffn {Procedure} polyline . points
Return a path that draws a series of lines connecting @var{points}.
@end deffn

@deffn {Procedure} rectangle bottom-left width height
Return a path that draws a rectangle whose bottom-left corner is at
@var{bottom-left} and whose size is defined by @var{width} and
@var{height}.
@end deffn

@deffn {Procedure} square bottom-left size
Return a path draws a square whose bottom-left corner is at
@var{bottom-left} and whose size is defined by @var{size}.
@end deffn

@deffn {Procedure} rounded-rectangle bottom-left width height @
                   [#:radius 4.0] [#:radius-bottom-left] @
                   [#:radius-bottom-right] [#:radius-top-left] @
                   [#:radius-top-right]

Return a path that draws a rectangle with rounded corners whose
bottom-left corner is at @var{bottom-left} and whose size is defined
by @var{width} and @var{height}.  The argument @var{radius} is used to
define the corner radius for all corners.  To use a different radius
value for a corner, use @var{radius-bottom-left},
@var{radius-bottom-right}, @var{radius-top-left}, and/or
@var{radius-top-right}.
@end deffn

@deffn {Procedure} regular-polygon center num-sides radius
Return a path that draws a regular polygon with @var{num-sides} sides
centered on the point @var{center} with each vertex @var{radius} units
away from the center.
@end deffn

@deffn {Procedure} ellipse center rx ry
Return a path that draws an ellipsed centered on the point
@var{center} with radii @var{rx} and @var{ry}.
@end deffn

@deffn {Procedure} circle center r
Return a path that draws a circle centered on the point @var{center}
with radius @var{r}.
@end deffn

With one or more paths created, a @emph{painter} is needed to give the
path its style and placement in the final picture.  Painters can be
combined together to form arbitrarily complex pictures.

@deffn {Procedure} stroke . paths
Apply a stroked drawing style to @var{paths}.
@end deffn

@deffn {Procedure} fill . paths
Apply a filled drawing style to @var{paths}.
@end deffn

@deffn {Procedure} fill-and-stroke . paths
Apply a filled and stroked drawing style to @var{paths}.
@end deffn

@deffn {Procedure} transform matrix painter
Apply @var{matrix}, a 3x3 transformation matrix, to @var{painter}.
@end deffn

@deffn {Procedure} translate v painter
Translate @var{painter} by the 2D vector @var{v}.
@end deffn

@deffn {Procedure} rotate angle painter
Rotate @var{painter} by @var{angle} radians.
@end deffn

@deffn {Procedure} scale x painter
Scale @var{painter} by the scalar @var{x}.
@end deffn

@deffn {Procedure} pad pad-x pad-y painter
Add @var{pad-x} and @var{pad-y} amount of empty space around
@var{painter}.
@end deffn

@deffn {Procedure} superimpose . painters
Stack @var{painters} on top of each other.
@end deffn

@deffn {Procedure} beside . painters
Place @var{painters} next to each other in a row.
@end deffn

@deffn {Procedure} below . painters
Place @var{painters} next to each other in a column.
@end deffn

@deffn {Syntax} with-style ((style-name value) ...) painter
Apply all the given style settings to @var{painter}.

Possible style attributes are:

@itemize
@item blend-mode
@item fill-color
@item stroke-color
@item stroke-width
@item stroke-feather
@item stroke-cap
@end itemize

@example
(with-style ((stroke-color green)
             (stroke-width 4.0))
  (stroke (circle (vec2 100.0 100.0) 50.0)))
@end example

@end deffn

As in real life, a painter cannot paint anything without a canvas.
Once a painter has been associated with a canvas, it can finally be
rendered to the screen.

@deffn {Procedure} make-canvas painter [#:matrix]
Return a new canvas that will @var{painter} will draw on.  Optionally,
a 3x3 @var{matrix} may be specified to apply an arbitrary
transformation to the resulting image.
@end deffn

@deffn {Procedure} make-empty-canvas [#:matrix]
Return a new canvas that no painter is using. Optionally, a 3x3
@var{matrix} may be specified to apply an arbitrary transformation to
the image, should a painter later be associated with this canvas.
@end deffn

@deffn {Procedure} canvas? obj
Return @code{#t} is @var{obj} is a canvas.
@end deffn

@deffn {Procedure} set-canvas-painter! canvas painter
Associate @var{painter} with @var{canvas}.
@end deffn

@deffn {Procedure} set-canvas-matrix! canvas matrix
Set the 3x3 transformation matrix of @var{canvas} to @var{matrix}.
@end deffn

@deffn {Procedure} draw-canvas canvas
Render @var{canvas} to the screen.
@end deffn

@node Particles
@subsection Particles

Effects like smoke, fire, sparks, etc. are often achieved by animating
lots of little, short-lived sprites known as ``particles''.  In fact,
all of these effects, and more, can be accomplished by turning a few
configuration knobs in a ``particle system''.  A particle system takes
care of managing the many miniscule moving morsels so the developer
can quickly produce an effect and move on with their life.  The
@code{(chickadee graphics particles)} module provides an API for
manipulating particle systems.

Below is an example of a very simple particle system that utilizes
nearly all of the default configuration settings:

@example
(use-modules (chickadee graphics particles))
(define texture (load-image "particle.png"))
(define particles (make-particles 2000 #:texture texture))
@end example

In order to put particles into a particle system, a particle
``emitter'' is needed.  Emitters know where to spawn new particles,
how many of them to spawn, and for how long they should do it.

Below is an example of an emitter that spawns 16 particles per frame
at the coordinates @code{(320, 240)}:

@example
(use-modules (chickadee math rect))
(define emitter (make-particle-emitter (make-rect 0.0 0.0 320.0 240.0) 16))
(add-particle-emitter particles emitter)
@end example

To see all of the tweakable knobs and switches, read on!

@deffn {Procedure} make-particles capacity [#:blend-mode] @
       [#:color white] [#:end-color transparent] [#:texture] @
       [#:animation-rows 1] [#:animation-columns 1] [#:width] [#:height] @
       [#:speed-range (vec2 0.1 1.0)] [#:acceleration-range (vec2 0.0 0.1)] @
       [#:direction-range (vec2 0 (* 2 pi))] [#:lifetime 30] [#:sort]

Return a new particle system that may contain up to @var{capacity}
particles.  Achieving the desired particle effect involves tweaking
the following keyword arguments as needed:

- @var{blend-mode}: Pixel blending mode.  Alpha blending is used by default.
(@pxref{Blending} for more about blend modes).

- @var{start-color}: The tint color of the particle at the beginning of its
life.  White by default.

- @var{end-color}: The tint color of the particle at the end of of its
life.  Completely transparent by default for a fade-out effect.  The
color in the middle of a particle's life will be an interpolation of
@var{start-color} and @var{end-color}.

- @var{texture}: The texture applied to the particles.  The texture
may be subdivided into many animation frames.

- @var{animation-rows}: How many animation frame rows there are in the
texture.  Default is 1.

- @var{animation-columns}: How many animation frame columns there are
in the texture.  Default is 1.

- @var{width}: The width of each particle.  By default, the width of
an animation frame (in pixels) is used.

- @var{height}: The height of each particle.  By default, the height
of an animation frame (in pixels) is used.

- @var{speed-range}: A 2D vector containing the min and max particle
speed.  Each particle will have a speed chosen at random from this
range.  By default, speed ranges from 0.1 to 1.0.

- @var{acceleration-range}: A 2D vector containing the min and max
particle acceleration.  Each particle will have an acceleration chosen
at random from this range.  By default, acceleration ranges from 0.0
to 0.1.

- @var{direction-range}: A 2D vector containing the min and max
particle direction as an angle in radians.  Each particle will have a
direction chosen at random from this range.  By default, the range
covers all possible angles.

- @var{lifetime}: How long each particle lives, measured in
updates. 30 by default.

- @var{sort}: @code{youngest} if youngest particle should be drawn
last or @code{oldest} for the reverse.  By default, no sorting is
applied at all.
@end deffn

@deffn {Procedure} particles? obj
Return @code{#t} if @var{obj} is a particle system.
@end deffn

@deffn {Procedure} update-particles particles
Advance the simulation of @var{particles}.
@end deffn

@deffn {Procedure} draw-particles particles
Render @var{particles}.
@end deffn

@deffn {Procedure} draw-particles* particles matrix
Render @var{particles} with @var{matrix} applied.
@end deffn

@deffn {Procedure} make-particle-emitter spawn-area rate [duration]

Return a new particle emitter that spawns @var{rate} particles per
frame within @var{spawn-area} (a rectangle or 2D vector) for
@var{duration} frames.  If @var{duration} is not specified, the
emitter will spawn particles indefinitely.
@end deffn

@deffn {Procedure} particle-emitter? obj
Return @code{#t} if @var{obj} is a particle emitter.
@end deffn

@deffn {Procedure} particle-emitter-spawn-area emitter
Return the spawn area for @var{emitter}.
@end deffn

@deffn {Procedure} particle-emitter-rate emitter
Return the number of particles that @var{emitter} will spawn per
frame.
@end deffn

@deffn {Procedure} particle-emitter-life emitter
Return the number of frames remaining in @var{emitter}'s lifespan.
@end deffn

@deffn {Procedure} particle-emitter-done? emitter
Return @code{#t} if @var{emitter} has finished spawning particlces.
@end deffn

@deffn {Procedure} add-particle-emitter particles emitter
Add @var{emitter} to @var{particles}.
@end deffn

@deffn {Procedure} remove-particle-emitter particles emitter
Remove @var{emitter} to @var{particles}
@end deffn

@node Tile Maps
@subsection Tile Maps

A tile map is a scene created by composing lots of small sprites,
called ``tiles'', into a larger image.  One program for editing such
maps is called @url{http://mapeditor.org,Tiled}.  Chickadee has native
support for loading and rendering Tiled maps in the @code{(chickadee
graphics tile-map)} module.

@deffn {Procedure} load-tile-map file-name [#:chunk-size]
Load the Tiled formatted map in @var{file-name} and return a new tile
map object.
@end deffn

@deffn {Procedure} tile-map? obj
Return @code{#t} if @var{obj} is a tile map.
@end deffn

@deffn {Procedure} tile-map-orientation tile-map
Return the orientation of @var{tile-map}.
@end deffn

@deffn {Procedure} tile-map-width tile-map
Return the width of @var{tile-map} in tiles.
@end deffn

@deffn {Procedure} tile-map-height tile-map
Return the height of @var{tile-map} in tiles.
@end deffn

@deffn {Procedure} tile-map-tile-width tile-map
Return the width of tiles in @var{tile-map}.
@end deffn

@deffn {Procedure} tile-map-tile-height tile-map
Return the height of tiles in @var{tile-map}.
@end deffn

@deffn {Procedure} tile-map-tilesets tile-map
Return the tilesets for @var{tile-map}.
@end deffn

@deffn {Procedure} tile-map-layers tile-map
Return the layers of @var{tile-map}.
@end deffn

@deffn {Procedure} tile-map-properties tile-map
Return the custom properties of @var{tile-map}.
@end deffn

@deffn {Procedure} point->tile tile-map x y
Translate the pixel coordinates (@var{x}, @var{y}) into tile
coordinates.
@end deffn

@deffn {Procedure} draw-tile-map tile-map [#:layers] [#:camera] @
       [#:origin] [#:position] [#:scale] [#:rotation] [#:blend-mode] @
       [#:tint] [#:time]

Draw the layers of @var{tile-map} as viewed from @var{camera}, a 2D
vector offset.  By default, all layers are drawn.  To draw a subset of
the available layers, pass a list of layer ids using the @var{layers}
keyword argument.
@end deffn

@deffn {Procedure} tileset? obj
Return @code{#t} if @var{obj} is a tileset.
@end deffn

@deffn {Procedure} tileset-name tileset
Return the name of @var{tileset}.
@end deffn

@deffn {Procedure} tileset-first-gid tileset
Return the starting GID of @var{tileset}.
@end deffn

@deffn {Procedure} tileset-size tileset
Return the number of tiles in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-tile-width tileset
Return the width of tiles in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-tile-height tileset
Return the height of tiles in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-atlas tileset
Return the texture atlas for @var{tileset}.
@end deffn

@deffn {Procedure} tileset-tiles tileset
Return the tiles in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-rows tileset
Return the number of rows in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-columns tileset
Return the number of columns in @var{tileset}.
@end deffn

@deffn {Procedure} tileset-properties tileset
Return the custom properties of @var{tileset}.
@end deffn

@deffn {Procedure} tile? obj
Return @code{#t} if @var{obj} is a tile.
@end deffn

@deffn {Procedure} tile-id tile
Return the ID of @var{tile}.
@end deffn

@deffn {Procedure} tile-animation tile
Return the animation for @var{tile}.
@end deffn

@deffn {Procedure} tile-properties tile
Return the custom properties of @var{tile}.
@end deffn

@deffn {Procedure} animation? obj
Return @code{#t} if @var{obj} is an animation.
@end deffn

@deffn {Procedure} animation-frames animation
Return a vector of frames in @var{animation}.
@end deffn

@deffn {Procedure} animation-duration animation
Return the duration of @var{animation}.
@end deffn

@deffn {Procedure} animation-frame? obj
Return @code{#t} if @var{obj} is an animation frame.
@end deffn

@deffn {Procedure} animation-frame-tile frame
Return the tile for @var{frame}.
@end deffn

@deffn {Procedure} animation-frame-duration frame
Return the duration of @var{frame}.
@end deffn

@deffn {Procedure} tile-layer? obj
Return @code{#t} if @var{obj} is a tile layer.
@end deffn

@deffn {Procedure} tile-layer-name layer
Return the name of @var{layer}.
@end deffn

@deffn {Procedure} tile-layer-width layer
Return the width in tiles of @var{layer}.
@end deffn

@deffn {Procedure} tile-layer-height layer
Return the height in tiles of @var{layer}.
@end deffn

@deffn {Procedure} tile-layer-tiles layer
Return the tile data for @var{layer}.
@end deffn

@deffn {Procedure} tile-layer-properties layer
Return the custom properties of @var{layer}.
@end deffn

@deffn {Procedure} object-layer? obj
Return @code{#t} if @var{obj} is an object layer.
@end deffn

@deffn {Procedure} object-layer-name layer
Return the name of @var{layer}.
@end deffn

@deffn {Procedure} object-layer-objects layer
Return the objects for @var{layer}.
@end deffn

@deffn {Procedure} object-layer-properties layer
Return the custom properties of @var{layer}.
@end deffn

@deffn {Procedure} map-object? obj
Return @code{#t} if @var{obj} is a map object.
@end deffn

@deffn {Procedure} map-object-id obj
Return the ID of @var{obj}.
@end deffn

@deffn {Procedure} map-object-name obj
Return the name of @var{obj}.
@end deffn

@deffn {Procedure} map-object-type obj
Return the type of @var{obj}.
@end deffn

@deffn {Procedure} map-object-shape obj
Return the shape of @var{obj}.
@end deffn

@deffn {Procedure} map-object-properties obj
Return the custom properties of @var{obj}.
@end deffn

@deffn {Procedure} polygon? obj
Return @code{#t} if @var{obj} is a polygon.
@end deffn

@deffn {Procedure} polygon-points polygon
Return the list of points that form @var{polygon}.
@end deffn

@node 3D Models
@subsection 3D Models

@emph{Disclaimer: Chickadee is alpha software, but 3D model support is
even more alpha than that.  There are many missing features in both
the model loading and rendering components, so set your expectations
accordingly!}

Chickadee can load and render 3D models in the classic OBJ and more
modern glTF 2.0 formats.

Here's some basic boilerplate to render a 3D model:

@example
(use-modules (chickadee)
             (chickadee math)
             (chickadee math matrix)
             (chickadee graphics model))

(define model #f)
(define projection-matrix
  (perspective-projection (/ pi 3.0) (/ 4.0 3.0) 0.1 500.0))
;; Adjust these 2 matrices so that you can actually see the model.
(define view-matrix (make-identity-matrix4))
(define model-matrix (make-identity-matrix4))

(define (load)
  (set! model (load-obj "model.obj"))

(define (draw alpha)
  (with-projection projection-matrix
    (with-depth-test #t
      (draw-model model model-matrix view-matrix))))

(run-game #:load load #:draw draw)
@end example

@deffn {Procedure} load-obj file-name
Load the OBJ formatted model in @var{file-name} and return a 3D model
object.

OBJ models are rendered using a Phong lighting model, which is a
work-in-progress.
@end deffn

@deffn {Procedure} load-gltf file-name
Load the glTF 2.0 formatted model in @var{file-name} and return a 3D
model object.

glTF models are rendered using a physically based lighting model,
which is currently a stub to be implemented later.
@end deffn

@deffn {Procedure} model? obj
Return @code{#t} if @var{obj} is a 3D model.
@end deffn

@deffn {Procedure} draw-model model model-matrix view-matrix
Render @var{model} with the transformation matrices @var{model-matrix}
and @var{view-matrix} applied.
@end deffn

@node Blending
@subsection Blending

Rendering a scene often involves drawing layers of objects that
overlap each other.  Blending determines how two overlapping pixels
are combined in the final image that is rendered to the screen.

Chickadee provides the following blend modes:

@defvar blend:alpha
Blend pixels according to the values of their alpha channels.  This is
the most commonly used blend mode.
@end defvar

@defvar blend:replace
Overwrite the output pixel color with the color being drawn.
@end defvar

@defvar blend:add
Add all pixel color values together.  The more colors blended
together, the more white the final color becomes.
@end defvar

@defvar blend:subtract
Subtract all pixel color values.  The more colors blended together,
the more black the final color becomes.
@end defvar

@defvar blend:multiply
@end defvar

@defvar blend:darken
@end defvar

@defvar blend:lighten
@end defvar

@defvar blend:screen
@end defvar

Custom blend modes can be created using the @code{make-blend-mode} procedure:

@deffn {Procedure} make-blend-mode equation source-function destination-function
Return a new custom blend mode that applies @var{source-function} to
the source color, @var{destination-function} to the destination color,
and finally applies @var{equation} to the transformed
source/destination color values.  These arguments are @emph{not}
procedures, but symbolic representations of the functions that OpenGL
supports.

Valid values for @var{equation} are:

@itemize
@item @code{add}
@item @code{subtract}
@item @code{reverse-subtract}
@item @code{min}
@item @code{max}
@item @code{alpha-min}
@item @code{alpha-max}
@end itemize

Valid values for @var{source-function} are:

@itemize
@item @code{zero}
@item @code{one}
@item @code{destination-color}
@item @code{one-minus-destination-color}
@item @code{source-alpha-saturate}
@item @code{source-alpha}
@item @code{one-minus-source-alpha}
@item @code{destination-alpha}
@item @code{one-minus-destination-alpha}
@item @code{constant-color}
@item @code{one-minus-constant-color}
@item @code{constant-alpha}
@item @code{one-minus-constant-alpha}
@end itemize

Valid values for @var{destination-function} are:

@itemize
@item @code{zero}
@item @code{one}
@item @code{source-color}
@item @code{one-minus-source-color}
@item @code{source-alpha}
@item @code{one-minus-source-alpha}
@item @code{destination-alpha}
@item @code{one-minus-destination-alpha}
@item @code{constant-color}
@item @code{one-minus-constant-color}
@item @code{constant-alpha}
@item @code{one-minus-constant-alpha}
@end itemize

@end deffn

@node Framebuffers
@subsection Framebuffers

A framebuffer is a chunk of memory that the GPU can render things
onto.  By default, the framebuffer that is used for rendering is the
one belonging to the game window, but custom framebuffers can be used
as well.  A common use-case for custom framebuffers is applying
post-processing effects: The entire scene is rendered to a
framebuffer, and then the contents of that framebuffer are applied to
a post-processing shader and rendered to the game window.  The
post-processing shader could do any number of things: scaling,
antialiasing, motion blur, etc.

@deffn {Procedure} make-framebuffer width height @
                                    [#:min-filter @code{linear}] @
                                    [#:mag-filter @code{linear}] @
                                    [#:wrap-s @code{repeat}] @
                                    [#:wrap-t @code{repeat}]

Create a new framebuffer that is @var{width} pixels wide and @var{height} pixels high.

@var{min-filter} and @var{mag-filter} determine the scaling algorithm
applied to the framebuffer when rendering.  By default, linear scaling
is used in both cases. To perform no smoothing at all, use
@code{nearest} for simple nearest neighbor scaling.  This is typically
the best choice for pixel art games.
@end deffn

@deffn {Procedure} framebuffer? obj
Return @code{#t} if @var{obj} is a framebuffer.
@end deffn

@deffn {Procedure} framebuffer-texture fb
Return the texture backing the framebuffer @var{fb}.
@end deffn

@deffn {Procedure} framebuffer-viewport fb
Return the default viewport (@pxref{Viewports}) used by the
framebuffer @var{fb}.
@end deffn

@deffn {Procedure} null-framebuffer
The default framebuffer.
@end deffn

@node Viewports
@subsection Viewports

A viewport represents a subset of the screen (or framebuffer).  When
rendering a frame, the resulting image will only appear within that
viewport.  These aren't often needed, and Chickadee's default viewport
occupies the entire screen, but there are certain situations where
they are useful.  For example, a split-screen multiplayer game may
render to two different viewports, each occupying a different half of
the screen.  For information about how to set the current viewport,
see @code{with-viewport} in @ref{Rendering Engine}.

The @code{(chickadee graphics viewport)} module provides the following
API:

@deffn {Procedure} make-viewport x y width height @
                                 [#:clear-color] [#:clear-flags]

Create a viewport that covers an area of the window starting from
coordinates (@var{x}, @var{y}) and spanning @var{width} @code{x}
@var{height} pixels.  Fill the viewport with @var{clear-color} when
clearing the screen.  Clear the buffers denoted by the list of symbols
in @var{clear-flags}.

Possible values for @var{clear-flags} are @var{color-buffer},
@var{depth-buffer}, @var{accum-buffer}, and @var{stencil-buffer}.
@end deffn

@deffn {Procedure} viewport? obj
Return @code{#t} if @var{obj} is a viewport.
@end deffn

@deffn {Procedure} viewport-x viewport
Return the left edge of @var{viewport}.
@end deffn

@deffn {Procedure} viewport-y viewport
Return the bottom edge of @var{viewport}.
@end deffn

@deffn {Procedure} viewport-width viewport
Return the width of @var{viewport}.
@end deffn

@deffn {Procedure} viewport-height viewport
Return the height of @var{viewport}.
@end deffn

@deffn {Procedure} viewport-clear-color viewport
Return the clear color for @var{viewport}.
@end deffn

@deffn {Procedure} viewport-clear-flags viewport
Return the list of clear flags for @var{viewport}.
@end deffn

@node Rendering Engine
@subsection Rendering Engine

Chickadee defines rendering using a metaphor familiar to Scheme
programmers: procedure application.  A shader (@pxref{Shaders}) is
like a procedure for the GPU to apply.  Shaders are passed arguments:
A vertex array containing the geometry to render (@pxref{Buffers}) and
zero or more keyword arguments that the shader understands.  Similar
to how Scheme has @code{apply} for calling procedures, Chickadee
provides @code{shader-apply} for calling shaders.

Additionally, there is some dynamic state that effects how
@code{shader-apply} will behave.  Things like the current viewport,
framebuffer, and blend mode are stored as dynamic state because it
would be tedious to have to have to specify them each time
@code{shader-apply} is called.

The following procedures and syntax can be found in the
@code{(chickadee graphics)} module.

@deffn {Syntax} shader-apply shader vertex-array @
                          [#:uniform-key uniform-value @dots{}]
@deffnx {Syntax} shader-apply* shader vertex-array count @
                            [#:uniform-key uniform-value @dots{}]

Render @var{vertex-array} using @var{shader} with the uniform values
specified in the following keyword arguments.

While @code{shader-apply} will draw every vertex in @var{vertex-array},
@code{shader-apply*} will only draw @var{count} vertices.
@end deffn

@deffn {Syntax} shader-apply/instanced shader vertex-array @
       n [#:uniform-key uniform-value @dots{}]
@deffnx {Syntax} shader-apply/instanced shader vertex-array @
        count n [#:uniform-key uniform-value @dots{}]

Render @var{vertex-array} @var{n} times using @var{shader} with the
uniform values specified in the following keyword arguments.

Instanced rendering is very beneficial for rendering the same object
many times with only small differences for each one.  For example, the
particle effects described in @ref{Particles} use instanced rendering.

While @code{shader-apply/instanced} will draw every vertex in
@var{vertex-array}, @code{shader-apply*} will only draw @var{count}
vertices.
@end deffn

@deffn {Procedure} current-viewport
Return the currently bound viewport (@pxref{Viewports}).
@end deffn

@deffn {Procedure} current-framebuffer
Return the currently bound framebuffer (@pxref{Framebuffers}).
@end deffn

@deffn {Procedure} current-blend-mode
Return the currently bound blend mode (@pxref{Blending}).
@end deffn

@deffn {Procedure} current-depth-test
Return @code{#t} if depth testing is currently enabled (@pxref{Blending}).
@end deffn

@deffn {Procedure} current-texture
Return the currently bound texture (@pxref{Textures}).
@end deffn

@deffn {Procedure} current-projection
Return the currently bound projection matrix (@pxref{Matrices}).
@end deffn

@deffn {Syntax} with-viewport viewport body @dots{}
Evaluate @var{body} with the current viewport bound to @var{viewport} (@pxref{Viewports}).
@end deffn

@deffn {Syntax} with-framebuffer framebuffer body @dots{}
Evaluate @var{body} with the current framebuffer bound to
@var{framebuffer} (@pxref{Framebuffers}).
@end deffn

@deffn {Syntax} with-blend-mode blend-mode body @dots{}
Evaluate @var{body} with the current blend mode bound to
@var{blend-mode} (@pxref{Blending}).
@end deffn

@deffn {Syntax} with-depth-test depth-test? body @dots{}
Evaluate @var{body} with the depth-test disabled if @var{depth-test?}
is @code{#f}, or enabled otherwise (@pxref{Blending}).
@end deffn

@deffn {Syntax} with-texture texture body @dots{}
Evaluate @var{body} with the current texture bound to @var{texture}
(@pxref{Textures}).
@end deffn

@deffn {Syntax} with-projection projection body @dots{}
Evaluate @var{body} with the current projection matrix bound to
@var{projection} (@pxref{Matrices}).
@end deffn

@node Buffers
@subsection Buffers

Alright, let's brush aside all of those pretty high level abstractions
and discuss what is going on under the hood.  The GPU exists as a
discrete piece of hardware separate from the CPU.  In order to make it
draw things, we must ship lots of data out of our memory space and
into the GPU.  The @code{(chickadee graphics buffer}) module provides an
API for manipulating GPU buffers.

In OpenGL terminology, a chunk of data allocated on the GPU is a
``vertex buffer object'' or VBO.  For example, here is a bytevector
that could be transformed into a GPU buffer that packs together vertex
position and texture coordinates:

@example
(use-modules (chickadee graphics buffer) (srfi srfi-4))
(define data
  (f32vector -8.0 -8.0 ; 2D vertex
             0.0 0.0   ; 2D texture coordinate
             8.0 -8.0  ; 2D vertex
             1.0 0.0   ; 2D texture coordinate
             8.0 8.0   ; 2D vertex
             1.0 1.0   ; 2D texture coordinate
             -8.0 8.0  ; 2D vertex
             0.0 1.0)) ; 2D texture coordinate
@end example

This data represents a textured 16x16 square centered on the
origin. To send this data to the GPU, the @code{make-buffer} procedure
is needed:

@example
(define buffer (make-buffer data #:stride 16))
@end example

The @code{#:stride} keyword argument indicates how many bytes make up
each element of the buffer.  In this case, there are 4 floats per
element: 2 for the vertex, and 2 for the texture coordinate.  A 32-bit
float is 4 bytes in length, so the buffer's stride is 16.

Within a VBO, one or more ``attributes'', as OpenGL calls them, may be
present.  Attributes are subregions within the buffer that have a
particular data type.  In this case, there are two attributes packed
into the buffer.  To define vertex attributes, the
@code{make-vertex-attribute} procedure is needed:

@example
(define vertices
  (make-vertex-attribute #:buffer buffer
                         #:type 'vec2
                         #:component-type 'float
                         #:length 4))
(define texcoords
  (make-vertex-attribute #:buffer buffer
                         #:type 'vec2
                         #:component-type 'float
                         #:length 4
                         #:offset 8))
@end example

To render a square, the GPU needs to draw two triangles, which means
we need 6 vertices in total.  However, the above buffer only contains
data for 4 vertices.  This is because there are only 4 unique vertices
for a square, but 2 of them must be repeated for each triangle.  To
work with deduplicated vertex data, an ``index buffer'' must be
created.

@example
(define index-buffer
  (make-buffer (u32vector 0 3 2 0 2 1)
               #:target 'index)
(define indices
  (make-vertex-attribute #:type 'scalar
                         #:component-type 'unsigned-int
                         #:buffer index-buffer))
@end example

Note the use of the @code{#:target} keyword argument.  It is required
because the GPU treats index data in a special way and must be told
which data is index data.

Now that the vertex attributes have been created, all that's left is
to bind them all together in a vertex array.  Vertex arrays associate
each vertex attribute with an attribute index on the GPU.  The indices
that are chosen must correspond with the indices that the shader
(@pxref{Shaders}) expects for each attribute.

@example
(define vertex-array
  (make-vertex-array #:indices indices
                     #:attributes `((0 . ,vertices)
                                    (1 . ,texcoords))))
@end example

With the vertex array created, the GPU is now fully aware of how to
interpret the data that it has been given in the original buffer.
Actually rendering this square is left as an exercise to the reader.
See the @ref{Shaders} section and the @code{shader-apply} procedure in
@ref{Rendering Engine} for the remaining pieces of a successful draw
call.  Additionally, consider reading the source code for sprites,
shapes, or particles to see GPU buffers in action.

Without further ado, the API reference:

@deffn {Procedure} make-buffer data [#:name "anonymous"] @
       [#:length] [#:offset 0] [#:stride 0] [#:target @code{vertex}] @
       [#:usage @code{static}]

Upload @var{data}, a bytevector, to the GPU.  By default, the entire
bytevector is uploaded.  A subset of the data may be uploaded by
specifying the @var{offset}, the index of the first byte to be
uploaded, and @var{length}, the number of bytes to upload.

If @var{data} is @code{#f}, allocate @var{length} bytes of fresh GPU
memory instead.

@var{target} and @var{usage} are hints that tell the GPU how the
buffer is intended to be used.

@var{target} may be:

@itemize
@item @code{vertex}
Vertex attribute data.

@item @code{index}
Index buffer data.

@end itemize

@var{usage} may be:

@itemize
@item @code{static}
The buffer data will not be modified after creation.

@item @code{stream}
The buffer data will be modified frequently.

@end itemize

@var{name} is simply an arbitrary string for debugging purposes that
is never sent to the GPU.
@end deffn

@deffn {Procedure} buffer? obj
Return @code{#t} if @var{obj} is a GPU buffer.
@end deffn

@deffn {Procedure} index-buffer? buffer
Return @code{#t} if @var{buffer} is an index buffer.
@end deffn

@defvar null-buffer
Represents the absence of a buffer.
@end defvar

@deffn {Procedure} buffer-name buffer
Return the name of @var{buffer}.
@end deffn

@deffn {Procedure} buffer-length buffer
Return the length of @var{buffer}.
@end deffn

@deffn {Procedure} buffer-stride buffer
Return the amount of space, in bytes, between each element in
@var{buffer}.
@end deffn

@deffn {Procedure} buffer-target buffer
Return the the intended usage of @var{buffer}, either @code{vertex} or
@code{index}.
@end deffn

@deffn {Procedure} buffer-usage buffer
Return the intended usage of @var{buffer}, either @code{static} for
buffer data that will not change once sent to the GPU, or
@code{stream} for buffer data that will be frequently updated from the
client-side.
@end deffn

@deffn {Procedure} buffer-data buffer
Return a bytevector containing all the data within @var{buffer}.  If
@var{buffer} has not been mapped (see @code{with-mapped-buffer}) then
this procedure will return @code{#f}.
@end deffn

@deffn {Syntax} with-mapped-buffer buffer body @dots{}
Evaluate @var{body} in the context of @var{buffer} having its data
synced from GPU memory to RAM.  In this context, @code{buffer-data}
will return a bytevector of all the data stored in @var{buffer}.  When
program execution exits this form, the data (including any
modifications) is synced back to the GPU.

This form is useful for streaming buffers that need to update their
contents dynamically, such as a sprite batch.
@end deffn

@deffn {Procedure} make-vertex-attribute #:buffer #:type @
       #:component-type #:length [#:offset @code{0}] [#:divisor @code{1}] @
       [#:name @code{"anonymous"}]

Return a new vertex attribute for @var{buffer} starting at byte index
@var{offset} of @var{length} elements, where each element is of
@var{type} and composed of @var{component-type} values.

Valid values for @var{type} are:

@itemize
@item @code{scalar}
single number

@item @code{vec2}
2D vector

@item @code{vec3}
3D vector

@item @code{vec4}
4D vector

@item @code{mat2}
2x2 matrix

@item @code{mat3}
3x3 matrix

@item @code{mat4}
4x4 matrix
@end itemize

Valid values for @var{component-type} are:

@itemize

@item @code{byte}
@item @code{unsigned-byte}
@item @code{short}
@item @code{unsigned-short}
@item @code{int}
@item @code{unsigned-int}
@item @code{float}
@item @code{double}

@end itemize

@var{divisor} is only needed for instanced rendering applications (see
@code{shader-apply/instanced} in @ref{Rendering Engine}) and represents
how many instances each vertex element applies to.  A divisor of 0
means that a single element is used for every instance and is used for
the data being instanced.  A divisor of 1 means that each element is
used for 1 instance.  A divisor of 2 means that each element is used
for 2 instances, and so on.
@end deffn

@deffn {Procedure} vertex-attribute? obj
Return @code{#t} if @var{obj} is a vertex attribute.
@end deffn

@deffn {Procedure} vertex-attribute->buffer vertex-attribute
Return the buffer that @var{vertex-attribute} is using.
@end deffn

@deffn {Procedure} vertex-attribute-name vertex-attribute
Return the name of @var{vertex-attribute}.
@end deffn

@deffn {Procedure} vertex-attribute-offset vertex-attribute
Return the byte offset of @var{vertex-attribute}.
@end deffn

@deffn {Procedure} vertex-attribute-type vertex-attribute
Return the data type of @var{vertex-attribute}.
@end deffn

@deffn {Procedure} vertex-attribute-component-type vertex-attribute
Return the component data type of @var{vertex-attribute}
@end deffn

@deffn {Procedure} vertex-attribute-divisor vertex-attribute
Return the instance divisor for @var{vertex-attribute}.
@end deffn

@deffn {Syntax} with-mapped-vertex-attribute vertex-attribute body @dots{}

Evaluate @var{body} in the context of @var{vertex-attribute} having
its data synced from GPU memory to RAM.  See @code{with-mapped-buffer}
for more information.
@end deffn

@deffn {Procedure} make-vertex-array #:indices #:attributes @
       [#:mode @code{triangles}]

Return a new vertex array using the index data within the vertex
attributes @var{indices} and the vertex attribute data within
@var{attributes}.

@var{attributes} is an alist mapping shader attribute indices to
vertex attributes:

@example
`((1 . ,vertex-attribute-a)
  (2 . ,vertex-attribute-b)
  @dots{})
@end example

By default, the vertex array is interpreted as containing a series of
triangles.  If another primtive type is desired, the @var{mode}
keyword argument may be overridden.  The following values are
supported:

@itemize
@item @code{points}
@item @code{lines}
@item @code{line-loop}
@item @code{line-strip}
@item @code{triangles}
@item @code{triangle-strip}
@item @code{triangle-fan}
@end itemize

@end deffn

@defvar null-vertex-array
Represents the absence of a vertex array.
@end defvar

@deffn {Procedure} vertex-array? obj
Return @code{#t} if @var{obj} is a vertex array.
@end deffn

@deffn {Procedure} vertex-array-indices vertex-array
Return the buffer view containing index data for @var{vertex-array}.
@end deffn

@deffn {Procedure} vertex-array-attributes vertex-array
Return the attribute index -> buffer view mapping of vertex attribute
data for @var{vertex-array}.
@end deffn

@deffn {Procedure} vertex-array-mode vertex-array
Return the primitive rendering mode for @var{vertex-array}.
@end deffn

@node Shaders
@subsection Shaders

Shaders are programs that the GPU can evaluate that allow the
programmer to completely customized the final output of a GPU draw
call.  The @code{(chickadee graphics shader)} module provides an API for
building custom shaders.

Shaders are written in the OpenGL Shading Language, or GLSL for short.
Chickadee aspires to provide a domain specific language for writing
shaders in Scheme, but we are not there yet.

Shader programs consist of two components: A vertex shader and a
fragment shader.  A vertex shader receives vertex data (position
coordinates, texture coordinates, normals, etc.) and transforms them
as desired, whereas a fragment shader controls the color of each
pixel.

Sample vertex shader:

@example
@verbatim
#version 130

in vec2 position;
in vec2 tex;
out vec2 fragTex;
uniform mat4 mvp;

void main(void) {
    fragTex = tex;
    gl_Position = mvp * vec4(position.xy, 0.0, 1.0);
}
@end verbatim
@end example

Sample fragment shader:

@example
@verbatim
#version 130

in vec2 fragTex;
uniform sampler2D colorTexture;

void main (void) {
    gl_FragColor = texture2D(colorTexture, fragTex);
}
@end verbatim
@end example

This manual will not cover GLSL features and syntax as there is lots
of information already available about this topic.

One way to think about rendering with shaders, and the metaphor
Chickadee uses, is to think about it as a function call: The shader is
a function, and it is applied to some ``attributes'' (positional
arguments), and some ``uniforms'' (keyword arguments).

@example
(define my-shader (load-shader "vert.glsl" "frag.glsl"))
(define vertices (make-vertex-array @dots{}))
(shader-apply my-shader vertices #:color red)
@end example

@xref{Rendering Engine} for more details about the @code{shader-apply}
procedure.

Shaders are incredibly powerful tools, and there's more information
about them than we could ever fit into this manual, so we highly
recommend searching the web for more information and examples.  What
we can say, though, is how to use our API:

@deffn {Procedure} strings->shader vertex-source fragment-source
Compile @var{vertex-source}, the GLSL code for the vertex shader, and
@var{fragment-source}, the GLSL code for the fragment shader, into a
GPU shader program.
@end deffn

@deffn {Procedure} load-shader vertex-source-file fragment-source-file
Compile the GLSL source code within @var{vertex-source-file} and
@var{fragment-source-file} into a GPU shader program.
@end deffn

@deffn {Procedure} make-shader vertex-port fragment-port
Read GLSL source from @var{vertex-port} and @var{fragment-port} and
compile them into a GPU shader program.
@end deffn

@deffn {Procedure} shader? obj
Return @code{#t} if @var{obj} is a shader.
@end deffn

@defvar null-shader
Represents the absence shader program.
@end defvar

@deffn {Procedure} shader-uniform shader name
Return the metadata for the uniform @var{name} in @var{shader}.
@end deffn

@deffn {Procedure} shader-uniforms shader
Return a hash table of uniforms for @var{shader}.
@end deffn

@deffn {Procedure} shader-attributes shader
Return a hash table of attributes for @var{shader}.
@end deffn

@deffn {Procedure} shader-uniform-set! shader uniform value
@end deffn

@subsubsection Attributes

@deffn {Procedure} attribute? obj
Return @code{#t} if @var{obj} is an attribute.
@end deffn

@deffn {Procedure} attribute-name attribute
Return the variable name of @var{attribute}.
@end deffn

@deffn {Procedure} attribute-location attribute
Return the binding location of @var{attribute}.
@end deffn

@deffn {Procedure} attribute-type attribute
Return the data type of @var{attribute}.
@end deffn

@subsubsection Uniforms

@deffn {Procedure} uniform? obj
Return @code{#t} if @var{obj} is a uniform.
@end deffn

@deffn {Procedure} uniform-name uniform
Return the variable name of @var{uniform}.
@end deffn

@deffn {Procedure} uniform-type uniform
Return the data type of @var{uniform}.
@end deffn

@deffn {Procedure} uniform-value uniform
Return the current value of @var{uniform}.
@end deffn

@subsubsection User-Defined Shader Types

The shader examples in this manual thus far have only shown uniforms
defined using primitive types.  However, GLSL shaders support
user-defined compound structs, such as this one:

@example
@verbatim
struct DirectionalLight {
    vec3 direction;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

uniform DirectionalLight light;
@end verbatim
@end example

While @code{light} is declared as a single uniform in the shader code,
OpenGL translates this into @emph{four} uniforms in this case: One
uniform each member of the @code{DirectionalLight} struct.  This poses
a problem for sending Scheme data to the GPU.  How can compound Scheme
data translate into compound uniform data on the GPU?  The answer is
with shader types.  Shader types are a special kind of Guile struct
that provide a one-to-one mapping between a Scheme data structure and
a shader struct.

Some example code will explain this concept best.  Here is the Scheme
equivalent of the @code{DirectionalLight} struct:

@example
(define-shader-type <directional-light>
  make-directional-light
  directional-light?
  (float-vec3 direction directional-light-direction)
  (float-vec3 ambient directional-light-ambient)
  (float-vec3 diffuse directional-light-diffuse)
  (float-vec3 specular directional-light-specular)
  (float shininess directional-light-shininess))
@end example

The macro @code{define-shader-type} closely resembles the familiar
@code{define-record-type} from SRFI-9, but with one notable
difference: Each struct field contains type information.  The type
must be one of several primitive types (documented below) or another
shader type in the case of a nested structure.

It is important to note that the names of the shader type fields
@emph{must} match the names of the struct members in the GLSL code,
otherwise Chickadee will be unable to perform the proper translation.

As of this writing, this interface is new and experimental.  It
remains to be seen if this model is robust enough for all use-cases.

Primitive data types:

@defvar bool
Either @code{#t} or @code{#f}.
@end defvar

@defvar int
An integer.
@end defvar

@defvar unsigned-int
An unsigned integer.
@end defvar

@defvar float
A floating point number.
@end defvar

@defvar float-vec2
A 2D vector (@pxref{Vectors}.)
@end defvar

@defvar float-vec3
A 3D vector (@pxref{Vectors}.)
@end defvar

@defvar float-vec4
A color.
@end defvar

@defvar mat4
A matrix (@pxref{Matrices}.)
@end defvar

@defvar sampler-2d
A texture (@pxref{Textures}.)
@end defvar

@defvar local-field
A special type that means that the data is for the client-side
(Scheme-side) only and should not be sent to the GPU.  Any object may
be stored in a local field.
@end defvar

@deffn {Syntax} define-shader-type <name> constructor predicate @
                (field-type field-name [field-getter] [field-setter]) @dots{}

Define a new shader data type called @var{<name>}.

Instances of this data type are created by calling the
@var{constructor} procedure.  This procedure maps each field to a
keyword argument.  A shader data type with the fields @code{foo},
@code{bar}, and @code{baz} would have a constructor that accepts the
keyword arguments @code{#:foo}, @code{#:bar}, and @code{#:baz}.

A procedure named @var{predicate} will test if an object is a
@var{<name>} shader data type.

Fields follow the format @code{(field-type field-name [field-getter]
[field-setter])}.  @var{field-type} and @var{field-name} are required
for each field, but @var{field-getter} and @var{field-setter} are
optional.

@end deffn

@deffn {Procedure} shader-data-type? obj
Return @code{#t} if @var{obj} is a shader data type object.
@end deffn

@node Audio
@section Audio

A game isn't complete without sound.  Most games play some cool
background music to set the mood and have many sound effects to play
when events happen.  The @code{(chickadee audio)} module provides a
robust audio API backed by the OpenAL 3D audio system.

@menu
* Audio Files::                 Not audiophiles.
* Sources::                     Audio emitters.
* The Listener::                The player's ears.
* The Environment::             Global sound model settings.
@end menu

The basics of playing audio are very simple.  Just load an audio file
in the load hook (or anywhere else once the game loop is running) and
play it!

@example
(use-modules (chickadee audio))

(define audio #f)

(define (load)
  (set! audio (load-audio "neat-sound-effect.wav"))
  (audio-play audio))

(run-game #:load load)
@end example

For more advanced usage, check out the full API reference in the
following sections.

@node Audio Files
@subsection Audio Files

Sound data is represented by a special @code{<audio>} data type that
stores not only the audio samples themselves, but metadata such as
sample rate, number of channels, and how many bits are used for each
sample.

@deffn {Procedure} load-audio file-name [#:mode @code{static}]
Load audio within @var{file-name}.  The following file formats are
currently supported:

@itemize
@item WAV
@item MP3
@item Ogg Vorbis
@end itemize

Audio files can be loaded in two different ways, as indicated by
@var{mode}:

@itemize
@item static:
Load the entire audio file into memory.
@item stream:
Load chunks of the audio file as needed.
@end itemize

Generally speaking, sound effects don't take up much space and should
be loaded statically, but music files are much larger and should use
streaming.  Static loading is the default.
@end deffn

@deffn {Procedure} audio? @var{obj}
Return @code{#t} if @var{obj} is an audio object.
@end deffn

@deffn {Procedure} streaming-audio? @var{audio}
Return @code{#t} if @var{audio} uses stream loading.
@end deffn

@deffn {Procedure} static-audio?
Return @code{#t} if @var{audio} uses static loading.
@end deffn

@deffn {Procedure} audio-mode audio
Return the loading mode for @var{audio}, either @code{static} or
@code{stream}.
@end deffn

@deffn {Procedure} audio-duration audio
Return the duration of @var{audio} in seconds.
@end deffn

@deffn {Procedure} audio-bits-per-sample audio
Return the number of bits per sample in @var{audio}.
@end deffn

@deffn {Procedure} audio-channels audio
Return the number of channels in @var{audio}.
@end deffn

@deffn {Procedure} audio-sample-rate audio
Return the sample rate of @var{audio}.
@end deffn

@deffn {Procedure} audio-play audio [#:pitch 1.0] [#:volume 1.0] @
                   [#:min-volume 0.0] [#:max-volume 1.0] [#:max-distance] @
                   [#:reference-distance 0.0] [#:rolloff-factor 1.0] @
                   [#:cone-outer-volume 0.0] [#:cone-inner-angle 0.0] @
                   [#:cone-outer-angle] @
                   [#:position @code{(vec3 0.0 0.0 0.0)}] @
                   [#:velocity @code{(vec3 0.0 0.0 0.0)}] @
                   [#:direction @code{(vec3 0.0 0.0 0.0)}] @
                   [#:relative? @code{#f}]

Play @var{audio}.  There are many, many knobs to tweak that will
affect the sound that comes out of the player's speakers.:

@itemize
@item @var{pitch}:
Pitch multiplier.  The default value of 1.0 means no change in pitch.
@item @var{volume}:
Volume multiplier.  The default value of 1.0 means no change in volume.
@item @var{min-volume}:
Minimum volume.
@item @var{max-volume}:
Maximum volume.
@item @var{max-distance}:
Used with the inverse clamped distance model (the default model) to
set the distance where there will no longer be any attenuation of the
source.
@item @var{reference-distance}:
The distance where the volume for the audio would drop by half (before
being influenced by the rolloff factor or maximum distance.)
@item @var{rolloff-factor}:
For slowing down or speeding up the rate of attenuation.  The default
of 1.0 means no attenuation adjustment is made.
@item @var{cone-outer-volume}:
The volume when outside the oriented cone.
@item @var{cone-inner-angle}:
Inner angle of the sound cone, in radians.  The default value is 0.
@item @var{cone-outer-angle}:
Outer angle of the sound cone, in radians.  The default value is 2pi
radians, or 360 degrees.
@item @var{position}:
The source of the sound emitter in 3D space.
@item @var{velocity}:
The velocity of the sound emitter in 3D space.
@item @var{direction}:
The direction of the sound emitter in 3D space.
@item @var{relative?}:
A flag that determines whether the position is in absolute coordinates
or relative to the listener's location.  Absolute coordinates are used
by default.
@end itemize

For games with basic sound needs (that is to say they don't need 3D
sound modeling), the only things that really matter are @var{volume}
and @var{pitch}.

@end deffn

@node Sources
@subsection Sources

While the @code{audio-play} procedure provides a quick and convenient
way to play audio, it has some limitations.  What if the audio is a
long piece of music that might need to be paused or stopped later?
What if the audio should be looped?  What if the volume or pitch needs
to be altered?  For manipulating audio in these ways, a ``source'' is
required.  Sources can be thought of like a boombox: They sit
somewhere in the room and play sound.  The pause or stop buttons can
be pressed; it can be moved somewhere else; the volume knob can be
adjusted; the CD can be changed.

Sources are a great fit for handling background music, among other
things.  For quick, one-off sound effects, @code{audio-play} is a
better fit.

@deffn {Procedure} make-source audio loop? [#:pitch 1.0] [#:volume 1.0] @
                   [#:min-volume 0.0] [#:max-volume 1.0] [#:max-distance] @
                   [#:reference-distance 0.0] [#:rolloff-factor 1.0] @
                   [#:cone-outer-volume 0.0] [#:cone-inner-angle 0.0] @
                   [#:cone-outer-angle] @
                   [#:position @code{(vec3 0.0 0.0 0.0)}] @
                   [#:velocity @code{(vec3 0.0 0.0 0.0)}] @
                   [#:direction @code{(vec3 0.0 0.0 0.0)}] @
                   [#:relative? @code{#f}]

Return a new audio source.  @var{audio} is the audio data to use when
playing.  @var{loop?} specifies whether or not to loop the audio
during playback.

Refer to @code{audio-play} (@pxref{Audio Files}) for information about
the optional keyword arguments.
@end deffn

@deffn {Procedure} source? obj
Return @code{#t} if @var{obj} is an audio source object.
@end deffn

@deffn {Procedure} streaming-source? source
Return @code{#t} if @var{source} contains streaming audio.
@end deffn

@deffn {Procedure} static-source? source
Return @code{#t} if @var{source} contains static audio.
@end deffn

@deffn {Procedure} source-playing? source
Return @code{#t} if @var{source} is currently playing.
@end deffn

@deffn {Procedure} source-paused? source
Return @code{#t} if @var{source} is currently paused.
@end deffn

@deffn {Procedure} source-stopped? source
Return @code{#t} if @var{source} is currently stopped.
@end deffn

@deffn {Procedure} source-pitch source
Return the pitch multiplier of @var{source}.
@end deffn

@deffn {Procedure} source-volume source
Return the volume multiplier of @var{source}.
@end deffn

@deffn {Procedure} source-min-volume source
Return the minimum volume of @var{source}.
@end deffn

@deffn {Procedure} source-max-volume source
Return the maximum volume of @var{source}.
@end deffn

@deffn {Procedure} source-max-distance source
Return the maximum distance of @var{source}.
@end deffn

@deffn {Procedure} source-reference-distance source
Return the reference distance of @var{source}.
@end deffn

@deffn {Procedure} source-rolloff-factor source
Return the rolloff factor of @var{source}.
@end deffn

@deffn {Procedure} source-cone-outer-volume source
Return the volume of @var{source} when outside the oriented cone.
@end deffn

@deffn {Procedure} source-cone-inner-angle source
Return the inner angle of the sound cone of @var{source} in radians.
@end deffn

@deffn {Procedure} source-cone-outer-angle source
Return the outer angle of the sound cone of @var{source} in radians.
@end deffn

@deffn {Procedure} source-position source
Return the position of @var{source} as a 3D vector.
@end deffn

@deffn {Procedure} source-velocity source
Return the velocity of @var{source} as a 3D vector.
@end deffn

@deffn {Procedure} source-direction source
Return the direction of @var{source} as a 3D vector.
@end deffn

@deffn {Procedure} source-relative? source
Return @code{#t} if the position of @var{source} is relative to the
listener's position.
@end deffn

@deffn {Procedure} source-play source
Begin/resume playback of @var{source}.
@end deffn

@deffn {Procedure} source-pause source
Pause playback of @var{source}.
@end deffn

@deffn {Procedure} source-toggle source
Play @var{source} if it is currently paused or pause @var{source} if
it is currently playing.
@end deffn

@deffn {Procedure} source-stop [source]
Stop playing @var{source} or, if no source is specified, stop playing
@emph{all} sources.
@end deffn

@deffn {Procedure} source-rewind source
Rewind @var{source} to the beginning of the audio stream.
@end deffn

@deffn {Procedure} set-source-audio! source audio
Set the playback stream for @var{source} to @var{audio}.
@end deffn

@deffn {Procedure} set-source-loop! source loop?
Configure whether or not @var{source} should loop the audio stream.
@end deffn

@deffn {Procedure} set-source-pitch! source pitch
Set the pitch multiplier of @var{source} to @var{pitch}
@end deffn

@deffn {Procedure} set-source-volume! source volume
Set the volume of @var{source} to @var{volume}.  A value of 1.0 is
100% volume.
@end deffn

@deffn {Procedure} set-source-min-volume! source volume
Set the minimum volume of @var{source} to @var{volume}.
@end deffn

@deffn {Procedure} set-source-max-volume! source volume
Set the maximum volume of @var{source} to @var{volume}.
@end deffn

@deffn {Procedure} set-source-max-distance! source distance
Set the distance where there will no longer be any attenuation of
@var{source} to @var{distance}.
@end deffn

@deffn {Procedure} set-source-reference-distance! source distance
Set the reference distance of @var{source} to @var{distance}.
@end deffn

@deffn {Procedure} set-source-rolloff-factor! source factor
Set the rolloff factor for @var{source} to @var{factor}.
@end deffn

@deffn {Procedure} set-source-cone-outer-volume! source volume
Set the volume for @var{source} when outside the sound cone to @var{volume}.
@end deffn

@deffn {Procedure} set-source-cone-inner-angle! source angle
Set the inner angle of the sound cone of @var{source} to @var{angle} radians.
@end deffn

@deffn {Procedure} set-source-cone-outer-angle! source angle
Set the outer angle of the sound cone of @var{source} to @var{angle} radians.
@end deffn

@deffn {Procedure} set-source-position! source position
Set the position of @var{source} to the 3D vector @var{position}.
@end deffn

@deffn {Procedure} set-source-velocity! source velocity
Set the velocity of @var{source} to the 3D vector @var{velocity}.
@end deffn

@deffn {Procedure} set-source-direction! source direction
Set the velocity of @var{source} to the 3D vector @var{direction}.
@end deffn

@deffn {Procedure} set-source-relative! source relative?
If @var{relative?} is @code{#t}, the position of @var{source} is
interpreted as relative to the listener's position.  Otherwise, the
position of @var{source} is in absolute coordinates.
@end deffn

@node The Listener
@subsection The Listener

The listener is a collection of global state that represents the
player within the 3D sound model.  For games that do not need 3D sound
modeling, manipulating the listener's master volume is the only
interesting thing to do here.

@deffn {Procedure} listener-volume
Return the current master volume of the listener.
@end deffn

@deffn {Procedure} listener-position
Return the current position of the listener.
@end deffn

@deffn {Procedure} listener-velocity
Return the current velocity of the listener.
@end deffn

@deffn {Procedure} listener-orientation
Return the current orientation of the listener.
@end deffn

@deffn {Procedure} set-listener-volume! volume
Set the listener's master volume to @var{volume}, a value in the range [0,
1].
@end deffn

@deffn {Procedure} set-listener-position! position
Set the listener's position to the 3D vector @var{position}.
@end deffn

@deffn {Procedure} set-listener-velocity! velocity
Set the listener's velocity to the 3D vector @var{velocity}.
@end deffn

@deffn {Procedure} set-listener-orientation! at up
Set the listener's orientation to the 3D vectors @var{at} and
@var{up}.
@end deffn

@node The Environment
@subsection The Environment

The environment defines global parameters that govern how sound is
processed within the 3D modeling space.

@deffn {Procedure} doppler-factor
Return the current doppler factor.
@end deffn

@deffn {Procedure} speed-of-sound
Return the current speed of sound.
@end deffn

@deffn {Procedure} distance-model
Return the current distance model.

Possible return values are:

@itemize
@item @code{none}
@item @code{inverse-distance}
@item @code{inverse-distance-clamped} (the default)
@item @code{linear-distance}
@item @code{linear-distance-clamped}
@item @code{exponent-distance}
@item @code{exponent-distance-clamped}
@end itemize

@end deffn

@deffn {Procedure} set-doppler-factor! doppler-factor
Change the doppler factor to @var{doppler-factor}.
@end deffn

@deffn {Procedure} set-speed-of-sound! speed-of-sound
Change the speed of sound to @var{speed-of-sound}.
@end deffn

@deffn {Procedure} set-distance-model! distance-model
Change the distance model to @var{distance-model}.  Valid distance
models are:

@itemize
@item @code{none}
@item @code{inverse-distance}
@item @code{inverse-distance-clamped}
@item @code{linear-distance}
@item @code{linear-distance-clamped}
@item @code{exponent-distance}
@item @code{exponent-distance-clamped}
@end itemize

@end deffn

@node Scripting
@section Scripting

Game logic is a web of asynchronous events that are carefully
coordinated to bring the game world to life.  In order to make an
enemy follow and attack the player, or move an NPC back and forth in
front of the item shop, or do both at the same time, a scripting
system is a necessity.  Chickadee comes with an asynchronous
programming system in the @code{(chickadee scripting)} module.
Lightweight, cooperative threads known as ``scripts'' allow the
programmer to write asynchronous code as if it were synchronous, and
allow many such ``threads'' to run concurrently.

But before we dig deeper into scripts, let's discuss the simple act
of scheduling tasks.

@menu
* Agendas::                     Scheduling tasks.
* Scripts::                     Cooperative multitasking.
* Tweening::                    Animations.
* Channels::                    Publish data to listeners.
@end menu

@node Agendas
@subsection Agendas

To schedule a task to be performed later, an ``agenda'' is used.
There is a default, global agenda that is ready to be used, or
additional agendas may be created for different purposes.  The
following example prints the text ``hello'' when the agenda has
advanced to time unit 10.

@example
(at 10 (display "hello\n"))
@end example

Most of the time it is more convenient to schedule tasks relative to
the current time.  This is where @code{after} comes in handy:

@example
(after 10 (display "hello\n"))
@end example

Time units in the agenda are in no way connected to real time.  It's
up to the programmer to decide what agenda time means.  A simple and
effective approach is to map each call of the update procedure
(@pxref{Kernel}) to 1 unit of agenda time, like so:

@example
(define (update dt)
  (update-agenda 1))
@end example

It is important to call @code{update-agenda} periodically, otherwise
no tasks will ever be run!

In addition to using the global agenda, it is useful to have multiple
agendas for different purposes.  For example, the game world can use a
different agenda than the user interface, so that pausing the game is
a simple matter of not updating the world's agenda while continuing to
update the user interface's agenda.  The current agenda is dynamically
scoped and can be changed using the @code{with-agenda} special form:

@example
(define game-world-agenda (make-agenda))

(with-agenda game-world-agenda
  (at 60 (spawn-goblin))
  (at 120 (spawn-goblin))
  (at 240 (spawn-goblin-king)))
@end example

@deffn {Procedure} make-agenda
Return a new task scheduler.
@end deffn

@deffn {Procedure} agenda? obj
Return @code{#t} if @var{obj} is an agenda.
@end deffn

@deffn {Procedure} current-agenda
@deffnx {Procedure} current-agenda agenda
When called with no arguments, return the current agenda.  When called
with one argument, set the current agenda to @var{agenda}.
@end deffn

@deffn {Syntax} with-agenda agenda body @dots{}
Evaluate @var{body} with the current agenda set to @var{agenda}.
@end deffn

@deffn {Procedure} agenda-time
Return the current agenda time.
@end deffn

@deffn {Procedure} update-agenda dt
Advance the current agenda by @var{dt}.
@end deffn

@deffn {Procedure} schedule-at time thunk
Schedule @var{thunk}, a procedure of zero arguments, to be run at
@var{time}.
@end deffn

@deffn {Procedure} schedule-after delay thunk
Schedule @var{thunk}, a procedure of zero arguments, to be run after
@var{delay}.
@end deffn

@deffn {Procedure} schedule-every interval thunk [n]
Schedule @var{thunk}, a procedure of zero arguments, to be run every
@var{interval} amount of time.  Repeat this @var{n} times, or
indefinitely if not specified.
@end deffn

@deffn {Syntax} at time body @dots{}
Schedule @var{body} to be evaluated at @var{time}.
@end deffn

@deffn {Syntax} after delay body @dots{}
Schedule @var{body} to be evaluated after @var{delay}.
@end deffn

@deffn {Syntax} every interval body @dots{}
@deffnx {Syntax} every (interval n) body @dots{}
Schedule @var{body} to be evaluated every @var{interval} amount of
time.  Repeat this @var{n} times, or indefinitely if not specified.
@end deffn

It is also possible to schedule things that are not dependent on how
much time passes.  The agenda will periodically poll to see if any
registered conditions are met.

@deffn {Procedure} call-when pred thunk
Call @var{thunk} sometime in the future when @var{pred} is satisfied
(returns a value other than @code{#f}.)
@end deffn

@node Scripts
@subsection Scripts

Now that we can schedule tasks, let's take things to the next level.
It sure would be great if we could make procedures that described a
series of actions that happened over time, especially if we could do
so without contorting our code into a nest of callback procedures.
This is where scripts come in.  With scripts we can write code in a
linear way, in a manner that appears to be synchronous, but with the
ability to suspend periodically in order to let other scripts have a
turn and prevent blocking the game loop.  Building on top of the
scheduling that agendas provide, here is a script that models a child
trying to get their mother's attention:

@example
(script
  (while #t
    (display "mom!")
    (newline)
    (sleep 60))) ; where 60 = 1 second of real time
@end example

This code runs in an endless loop, but the @code{sleep} procedure
suspends the script and schedules it to be run later by the agenda.
So, after each iteration of the loop, control is returned back to the
game loop and the program is not stuck spinning in a loop that will
never exit.  Pretty neat, eh?

Scripts can suspend to any capable handler, not just the agenda.
The @code{yield} procedure will suspend the current script and pass
its ``continuation'' to a handler procedure.  This handler procedure
could do anything.  Perhaps the handler stashes the continuation
somewhere where it will be resumed when the user presses a specific
key on the keyboard, or maybe it will be resumed when the player picks
up an item off of the dungeon floor; the sky is the limit.

Sometimes it is necessary to abruptly terminate a script after it has
been started.  For example, when an enemy is defeated their AI routine
needs to be shut down.  When a script is spawned, a handle to that
script is returned that can be used to cancel it when desired.

@example
(define script (script (while #t (display "hey\n") (sleep 60))))
;; sometime later
(cancel-script script)
@end example

@deffn {Procedure} spawn-script thunk
Apply @var{thunk} as a script and return a handle to it.
@end deffn

@deffn {Syntax} script body @dots{}
Evaluate @var{body} as a script and return a handle to it.
@end deffn

@deffn {Procedure} script? obj
Return @code{#t} if @var{obj} is a script handle.
@end deffn

@deffn {Procedure} script-cancelled? obj
Return @code{#t} if @var{obj} has been cancelled.
@end deffn

@deffn {Procedure} script-running? obj
Return @code{#t} if @var{obj} has not yet terminated or been
cancelled.
@end deffn

@deffn {Procedure} script-complete? obj
Return @code{#t} if @var{obj} has terminated.
@end deffn

@deffn {Procedure} cancel-script co
Prevent further execution of the script @var{co}.
@end deffn

@deffn {Procedure} yield handler
Suspend the current script and pass its continuation to the
procedure @var{handler}.
@end deffn

@deffn {Procedure} sleep duration
Wait @var{duration} before resuming the current script.
@end deffn

@deffn {Syntax} wait-until condition
Wait until @var{condition} is met before resuming the current script.

@example
(script
  (wait-until (key-pressed? 'z))
  (display "you pressed the Z key!\n"))
@end example

@end deffn

@deffn {Syntax} forever body @dots{}
Evaluate @var{body} in an endless loop.
@end deffn

@node Tweening
@subsection Tweening

Tweening is the process of transitioning something from an initial
state to a final state over a pre-determined period of time.  In other
words, tweening is a way to create animation.  The @code{tween}
procedure can be used within any script like so:

@example
(define x 0)
(script
  ;; 0 to 100 in 60 ticks of the agenda.
  (tween 60 0 100 (lambda (y) (set! x y))))
@end example

@deffn {Procedure} tween duration start end proc @
                         [#:step @code{1}] [#:ease @code{smoothstep}] @
                         #:interpolate @code{lerp}]
Transition a value from @var{start} to @var{end} over @var{duration},
sending each succesive value to @var{proc}.  @var{step} controls the
amount of time between each update of the animation.

To control how the animation goes from the initial to final state, an
``easing'' procedure may be specified.  By default, the
@code{smoothstep} easing is used, which is a more pleasing default
than a simplistic linear function.  @xref{Easings} for a complete list
of available easing procedures.

The @var{interpolate} procedure computes the values in between
@var{start} and @var{end}.  By default, linear interpolation (``lerp''
for short) is used.
@end deffn

@node Channels
@subsection Channels

Channels are a tool for communicating amongst different scripts.  One
script can write a value to the channel and another can read from it.
Reading or writing to a channel suspends that script until there is
someone on the other end of the line to complete the transaction.

Here's a simplistic example:

@example
(define c (make-channel))

(script
 (forever
  (let ((item (channel-get c)))
    (pk 'got item))))

(script
 (channel-put c 'sword)
 (channel-put c 'shield)
 (channel-put c 'potion))
@end example

@deffn {Procedure} make-channel
Return a new channel
@end deffn

@deffn {Procedure} channel? obj
Return @code{#t} if @var{obj} is a channel.
@end deffn

@deffn {Procedure} channel-get channel
Retrieve a value from @var{channel}.  The current script suspends
until a value is available.
@end deffn

@deffn {Procedure} channel-put channel data
Send @var{data} to @var{channel}.  The current script suspends until
another script is available to retrieve the value.
@end deffn

A low-level API also exists for using channels outside of a script via
callback procedures:

@deffn {Procedure} channel-get! channel proc
Asynchronously retrieve a value from @var{channel} and call @var{proc}
with that value.
@end deffn

@deffn {Procedure} channel-put! channel data [thunk]
Asynchronously send @var{data} to @var{channel} and call @var{thunk}
after it has been received.
@end deffn

@deffn {Procedure} channel-clear! channel
Clear all messages and scripts awaiting messages in @var{channel}.
@end deffn