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
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
|
/**********************************************************************************************
*
* raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms
*
* PLATFORMS SUPPORTED:
* - PLATFORM_DESKTOP: Windows (Win32, Win64)
* - PLATFORM_DESKTOP: Linux (X11 desktop mode)
* - PLATFORM_DESKTOP: FreeBSD, OpenBSD, NetBSD, DragonFly (X11 desktop)
* - PLATFORM_DESKTOP: OSX/macOS
* - PLATFORM_ANDROID: Android 4.0 (ARM, ARM64)
* - PLATFORM_RPI: Raspberry Pi 0,1,2,3,4 (Raspbian)
* - PLATFORM_WEB: HTML5 with asm.js (Chrome, Firefox)
* - PLATFORM_UWP: Windows 10 App, Windows Phone, Xbox One
*
* CONFIGURATION:
*
* #define PLATFORM_DESKTOP
* Windowing and input system configured for desktop platforms: Windows, Linux, OSX, FreeBSD, OpenBSD, NetBSD, DragonFly
* NOTE: Oculus Rift CV1 requires PLATFORM_DESKTOP for mirror rendering - View [rlgl] module to enable it
*
* #define PLATFORM_ANDROID
* Windowing and input system configured for Android device, app activity managed internally in this module.
* NOTE: OpenGL ES 2.0 is required and graphic device is managed by EGL
*
* #define PLATFORM_RPI
* Windowing and input system configured for Raspberry Pi i native mode (no X.org required, tested on Raspbian),
* graphic device is managed by EGL and inputs are processed is raw mode, reading from /dev/input/
*
* #define PLATFORM_WEB
* Windowing and input system configured for HTML5 (run on browser), code converted from C to asm.js
* using emscripten compiler. OpenGL ES 2.0 required for direct translation to WebGL equivalent code.
*
* #define PLATFORM_UWP
* Universal Windows Platform support, using OpenGL ES 2.0 through ANGLE on multiple Windows platforms,
* including Windows 10 App, Windows Phone and Xbox One platforms.
*
* #define SUPPORT_DEFAULT_FONT (default)
* Default font is loaded on window initialization to be available for the user to render simple text.
* NOTE: If enabled, uses external module functions to load default raylib font (module: text)
*
* #define SUPPORT_CAMERA_SYSTEM
* Camera module is included (camera.h) and multiple predefined cameras are available: free, 1st/3rd person, orbital
*
* #define SUPPORT_GESTURES_SYSTEM
* Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag
*
* #define SUPPORT_MOUSE_GESTURES
* Mouse gestures are directly mapped like touches and processed by gestures system.
*
* #define SUPPORT_TOUCH_AS_MOUSE
* Touch input and mouse input are shared. Mouse functions also return touch information.
*
* #define SUPPORT_SSH_KEYBOARD_RPI (Raspberry Pi only)
* Reconfigure standard input to receive key inputs, works with SSH connection.
* WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other running processes or
* blocking the device is not restored properly. Use with care.
*
* #define SUPPORT_MOUSE_CURSOR_RPI (Raspberry Pi only)
* Draw a mouse reference on screen (square cursor box)
*
* #define SUPPORT_BUSY_WAIT_LOOP
* Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used
*
* #define SUPPORT_HALFBUSY_WAIT_LOOP
* Use a half-busy wait loop, in this case frame sleeps for some time and runs a busy-wait-loop at the end
*
* #define SUPPORT_EVENTS_WAITING
* Wait for events passively (sleeping while no events) instead of polling them actively every frame
*
* #define SUPPORT_SCREEN_CAPTURE
* Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()
*
* #define SUPPORT_GIF_RECORDING
* Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()
*
* #define SUPPORT_HIGH_DPI
* Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP)
* NOTE: This flag is forced on macOS, since most displays are high-DPI
*
* #define SUPPORT_COMPRESSION_API
* Support CompressData() and DecompressData() functions, those functions use zlib implementation
* provided by stb_image and stb_image_write libraries, so, those libraries must be enabled on textures module
* for linkage
*
* #define SUPPORT_DATA_STORAGE
* Support saving binary data automatically to a generated storage.data file. This file is managed internally.
*
* DEPENDENCIES:
* rglfw - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX. FreeBSD, OpenBSD, NetBSD, DragonFly)
* raymath - 3D math functionality (Vector2, Vector3, Matrix, Quaternion)
* camera - Multiple 3D camera modes (free, orbital, 1st person, 3rd person)
* gestures - Gestures system for touch-ready devices (or simulated from mouse inputs)
*
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2013-2020 Ramon Santamaria (@raysan5)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#include "raylib.h" // Declares module functions
// Check if config flags have been externally provided on compilation line
#if !defined(EXTERNAL_CONFIG_FLAGS)
#include "config.h" // Defines module configuration flags
#else
#define RAYLIB_VERSION "3.0"
#endif
#include "utils.h" // Required for: TRACELOG macros
#if (defined(__linux__) || defined(PLATFORM_WEB)) && _POSIX_C_SOURCE < 199309L
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext.
#endif
#define RAYMATH_IMPLEMENTATION // Define external out-of-line implementation of raymath here
#include "raymath.h" // Required for: Vector3 and Matrix functions
#define RLGL_IMPLEMENTATION
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
#if defined(SUPPORT_GESTURES_SYSTEM)
#define GESTURES_IMPLEMENTATION
#include "gestures.h" // Gestures detection functionality
#endif
#if defined(SUPPORT_CAMERA_SYSTEM)
#define CAMERA_IMPLEMENTATION
#include "camera.h" // Camera system functionality
#endif
#if defined(SUPPORT_GIF_RECORDING)
#define RGIF_MALLOC RL_MALLOC
#define RGIF_FREE RL_FREE
#define RGIF_IMPLEMENTATION
#include "external/rgif.h" // Support GIF recording
#endif
#if defined(__APPLE__)
#define SUPPORT_HIGH_DPI // Force HighDPI support on macOS
#endif
#include <stdlib.h> // Required for: srand(), rand(), atexit()
#include <stdio.h> // Required for: sprintf() [Used in OpenURL()]
#include <string.h> // Required for: strrchr(), strcmp(), strlen()
#include <time.h> // Required for: time() [Used in InitTimer()]
#include <math.h> // Required for: tan() [Used in BeginMode3D()]
#include <sys/stat.h> // Required for: stat() [Used in GetFileModTime()]
#if (defined(PLATFORM_DESKTOP) || defined(PLATFORM_UWP)) && defined(_WIN32) && (defined(_MSC_VER) || defined(__TINYC__))
#define DIRENT_MALLOC RL_MALLOC
#define DIRENT_FREE RL_FREE
#include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()]
#else
#include <dirent.h> // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()]
#endif
#if defined(_WIN32)
#include <direct.h> // Required for: _getch(), _chdir()
#define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir()
#define CHDIR _chdir
#include <io.h> // Required for _access() [Used in FileExists()]
#else
#include <unistd.h> // Required for: getch(), chdir() (POSIX), access()
#define GETCWD getcwd
#define CHDIR chdir
#endif
#if defined(PLATFORM_DESKTOP)
#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3
// NOTE: Already provided by rlgl implementation (on glad.h)
#include <GLFW/glfw3.h> // GLFW3 library: Windows, OpenGL context and Input management
// NOTE: GLFW3 already includes gl.h (OpenGL) headers
// Support retrieving native window handlers
#if defined(_WIN32)
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // WARNING: It requires customization to avoid windows.h inclusion!
#if !defined(SUPPORT_BUSY_WAIT_LOOP)
// NOTE: Those functions require linking with winmm library
unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod);
unsigned int __stdcall timeEndPeriod(unsigned int uPeriod);
#endif
#elif defined(__linux__)
#include <sys/time.h> // Required for: timespec, nanosleep(), select() - POSIX
//#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type
//#define GLFW_EXPOSE_NATIVE_WAYLAND
//#define GLFW_EXPOSE_NATIVE_MIR
#include <GLFW/glfw3native.h> // Required for: glfwGetX11Window()
#elif defined(__APPLE__)
#include <unistd.h> // Required for: usleep()
//#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition
#include <GLFW/glfw3native.h> // Required for: glfwGetCocoaWindow()
#endif
#endif
#if defined(__linux__)
#define MAX_FILEPATH_LENGTH 4096 // Use Linux PATH_MAX value
#else
#define MAX_FILEPATH_LENGTH 512 // Use common value
#endif
#if defined(PLATFORM_ANDROID)
//#include <android/sensor.h> // Android sensors functions (accelerometer, gyroscope, light...)
#include <android/window.h> // Defines AWINDOW_FLAG_FULLSCREEN and others
#include <android_native_app_glue.h> // Defines basic app state struct and manages activity
#include <EGL/egl.h> // Khronos EGL library - Native platform display device control functions
#include <GLES2/gl2.h> // Khronos OpenGL ES 2.0 library
#endif
#if defined(PLATFORM_RPI)
#include <fcntl.h> // POSIX file control definitions - open(), creat(), fcntl()
#include <unistd.h> // POSIX standard function definitions - read(), close(), STDIN_FILENO
#include <termios.h> // POSIX terminal control definitions - tcgetattr(), tcsetattr()
#include <pthread.h> // POSIX threads management (inputs reading)
#include <dirent.h> // POSIX directory browsing
#include <sys/ioctl.h> // UNIX System call for device-specific input/output operations - ioctl()
#include <linux/kd.h> // Linux: KDSKBMODE, K_MEDIUMRAM constants definition
#include <linux/input.h> // Linux: Keycodes constants definition (KEY_A, ...)
#include <linux/joystick.h> // Linux: Joystick support library
#include "bcm_host.h" // Raspberry Pi VideoCore IV access functions
#include "EGL/egl.h" // Khronos EGL library - Native platform display device control functions
#include "EGL/eglext.h" // Khronos EGL library - Extensions
#include "GLES2/gl2.h" // Khronos OpenGL ES 2.0 library
#endif
#if defined(PLATFORM_UWP)
#include "EGL/egl.h" // Khronos EGL library - Native platform display device control functions
#include "EGL/eglext.h" // Khronos EGL library - Extensions
#include "GLES2/gl2.h" // Khronos OpenGL ES 2.0 library
#endif
#if defined(PLATFORM_WEB)
#define GLFW_INCLUDE_ES2 // GLFW3: Enable OpenGL ES 2.0 (translated to WebGL)
#include <GLFW/glfw3.h> // GLFW3 library: Windows, OpenGL context and Input management
#include <sys/time.h> // Required for: timespec, nanosleep(), select() - POSIX
#include <emscripten/emscripten.h> // Emscripten library - LLVM to JavaScript compiler
#include <emscripten/html5.h> // Emscripten HTML5 library
#endif
#if defined(SUPPORT_COMPRESSION_API)
// NOTE: Those declarations require stb_image and stb_image_write definitions, included in textures module
unsigned char *stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality);
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen);
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#if defined(PLATFORM_RPI)
#define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event<N> number
// Old device inputs system
#define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input
#define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...)
#define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events
// New device input events (evdev) (must be detected)
//#define DEFAULT_KEYBOARD_DEV "/dev/input/eventN"
//#define DEFAULT_MOUSE_DEV "/dev/input/eventN"
//#define DEFAULT_GAMEPAD_DEV "/dev/input/eventN"
#define MOUSE_SENSITIVITY 0.8f
#endif
#define MAX_GAMEPADS 4 // Max number of gamepads supported
#define MAX_GAMEPAD_AXIS 8 // Max number of axis supported (per gamepad)
#define MAX_GAMEPAD_BUTTONS 32 // Max bumber of buttons supported (per gamepad)
#define MAX_CHARS_QUEUE 16 // Max number of characters in the input queue
#if defined(SUPPORT_DATA_STORAGE)
#define STORAGE_DATA_FILE "storage.data"
#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
#if defined(PLATFORM_RPI)
typedef struct {
pthread_t threadId; // Event reading thread id
int fd; // File descriptor to the device it is assigned to
int eventNum; // Number of 'event<N>' device
Rectangle absRange; // Range of values for absolute pointing devices (touchscreens)
int touchSlot; // Hold the touch slot number of the currently being sent multitouch block
bool isMouse; // True if device supports relative X Y movements
bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH
bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH
bool isKeyboard; // True if device has letter keycodes
bool isGamepad; // True if device has gamepad buttons
} InputEventWorker;
typedef struct {
int contents[8]; // Key events FIFO contents (8 positions)
char head; // Key events FIFO head position
char tail; // Key events FIFO tail position
} KeyEventFifo;
#endif
typedef struct { int x; int y; } Point;
typedef struct { unsigned int width; unsigned int height; } Size;
#if defined(PLATFORM_UWP)
extern EGLNativeWindowType handle; // Native window handler for UWP (external, defined in UWP App)
#endif
// Core global state context data
typedef struct CoreData {
struct {
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
GLFWwindow *handle; // Native window handle (graphic device)
#endif
#if defined(PLATFORM_RPI)
// NOTE: RPI4 does not support Dispmanx anymore, system should be redesigned
EGL_DISPMANX_WINDOW_T handle; // Native window handle (graphic device)
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
EGLDisplay device; // Native display device (physical screen connection)
EGLSurface surface; // Surface to draw on, framebuffers (connected to context)
EGLContext context; // Graphic context, mode in which drawing can be done
EGLConfig config; // Graphic config
#endif
unsigned int flags; // Configuration flags (bit based)
const char *title; // Window text title const pointer
bool ready; // Flag to check if window has been initialized successfully
bool minimized; // Flag to check if window has been minimized
bool resized; // Flag to check if window has been resized
bool fullscreen; // Flag to check if fullscreen mode required
bool alwaysRun; // Flag to keep window update/draw running on minimized
bool shouldClose; // Flag to set window for closing
Point position; // Window position on screen (required on fullscreen toggle)
Size display; // Display width and height (monitor, device-screen, LCD, ...)
Size screen; // Screen width and height (used render area)
Size currentFbo; // Current render width and height, it could change on BeginTextureMode()
Size render; // Framebuffer width and height (render area, including black bars if required)
Point renderOffset; // Offset from render area (must be divided by 2)
Matrix screenScale; // Matrix to scale screen (framebuffer rendering)
char **dropFilesPath; // Store dropped files paths as strings
int dropFilesCount; // Count dropped files strings
} Window;
#if defined(PLATFORM_ANDROID)
struct {
bool appEnabled; // Flag to detect if app is active ** = true
struct android_app *app; // Android activity
struct android_poll_source *source; // Android events polling source
const char *internalDataPath; // Android internal data path to write data (/data/data/<package>/files)
bool contextRebindRequired; // Used to know context rebind required
} Android;
#endif
struct {
#if defined(PLATFORM_RPI)
InputEventWorker eventWorker[10]; // List of worker threads for every monitored "/dev/input/event<N>"
#endif
struct {
int exitKey; // Default exit key
char currentKeyState[512]; // Registers current frame key state
char previousKeyState[512]; // Registers previous frame key state
int keyPressedQueue[MAX_CHARS_QUEUE]; // Input characters queue
int keyPressedQueueCount; // Input characters queue count
#if defined(PLATFORM_RPI)
int defaultMode; // Default keyboard mode
struct termios defaultSettings; // Default keyboard settings
KeyEventFifo lastKeyPressed; // Buffer for holding keydown events as they arrive (Needed due to multitreading of event workers)
#endif
} Keyboard;
struct {
Vector2 position; // Mouse position on screen
Vector2 offset; // Mouse offset
Vector2 scale; // Mouse scaling
bool cursorHidden; // Track if cursor is hidden
bool cursorOnScreen; // Tracks if cursor is inside client area
#if defined(PLATFORM_WEB)
bool cursorLockRequired; // Ask for cursor pointer lock on next click
#endif
char currentButtonState[3]; // Registers current mouse button state
char previousButtonState[3]; // Registers previous mouse button state
int currentWheelMove; // Registers current mouse wheel variation
int previousWheelMove; // Registers previous mouse wheel variation
#if defined(PLATFORM_RPI)
char currentButtonStateEvdev[3]; // Holds the new mouse state for the next polling event to grab (Can't be written directly due to multithreading, app could miss the update)
#endif
} Mouse;
struct {
Vector2 position[MAX_TOUCH_POINTS]; // Touch position on screen
char currentTouchState[MAX_TOUCH_POINTS]; // Registers current touch state
char previousTouchState[MAX_TOUCH_POINTS]; // Registers previous touch state
} Touch;
struct {
int lastButtonPressed; // Register last gamepad button pressed
int axisCount; // Register number of available gamepad axis
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP)
bool ready[MAX_GAMEPADS]; // Flag to know if gamepad is ready
float axisState[MAX_GAMEPADS][MAX_GAMEPAD_AXIS]; // Gamepad axis state
char currentState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state
char previousState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Previous gamepad buttons state
#endif
#if defined(PLATFORM_RPI)
pthread_t threadId; // Gamepad reading thread id
int streamId[MAX_GAMEPADS]; // Gamepad device file descriptor
char name[64]; // Gamepad name holder
#endif
} Gamepad;
} Input;
struct {
double current; // Current time measure
double previous; // Previous time measure
double update; // Time measure for frame update
double draw; // Time measure for frame draw
double frame; // Time measure for one frame
double target; // Desired time for one frame, if 0 not applied
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
unsigned long long base; // Base time measure for hi-res timer
#endif
} Time;
} CoreData;
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
static CoreData CORE = { 0 }; // Global CORE state context
static char **dirFilesPath = NULL; // Store directory files paths as strings
static int dirFilesCount = 0; // Count directory files strings
#if defined(SUPPORT_SCREEN_CAPTURE)
static int screenshotCounter = 0; // Screenshots counter
#endif
#if defined(SUPPORT_GIF_RECORDING)
static int gifFramesCounter = 0; // GIF frames counter
static bool gifRecording = false; // GIF recording state
#endif
//-----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Other Modules Functions Declaration (required by core)
//----------------------------------------------------------------------------------
#if defined(SUPPORT_DEFAULT_FONT)
extern void LoadFontDefault(void); // [Module: text] Loads default font on InitWindow()
extern void UnloadFontDefault(void); // [Module: text] Unloads default font from GPU memory
#endif
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
static bool InitGraphicsDevice(int width, int height); // Initialize graphics device
static void SetupFramebuffer(int width, int height); // Setup main framebuffer
static void SetupViewport(int width, int height); // Set viewport for a provided width and height
static void SwapBuffers(void); // Copy back buffer to front buffers
static void InitTimer(void); // Initialize timer
static void Wait(float ms); // Wait for some milliseconds (stop program execution)
static int GetGamepadButton(int button); // Get gamepad button generic to all platforms
static int GetGamepadAxis(int axis); // Get gamepad axis generic to all platforms
static void PollInputEvents(void); // Register user events
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); // GLFW3 Keyboard Callback, runs on key pressed
static void MouseButtonCallback(GLFWwindow *window, int button, int action, int mods); // GLFW3 Mouse Button Callback, runs on mouse button pressed
static void MouseCursorPosCallback(GLFWwindow *window, double x, double y); // GLFW3 Cursor Position Callback, runs on mouse move
static void CharCallback(GLFWwindow *window, unsigned int key); // GLFW3 Char Key Callback, runs on key pressed (get char value)
static void ScrollCallback(GLFWwindow *window, double xoffset, double yoffset); // GLFW3 Srolling Callback, runs on mouse wheel
static void CursorEnterCallback(GLFWwindow *window, int enter); // GLFW3 Cursor Enter Callback, cursor enters client area
static void WindowSizeCallback(GLFWwindow *window, int width, int height); // GLFW3 WindowSize Callback, runs when window is resized
static void WindowIconifyCallback(GLFWwindow *window, int iconified); // GLFW3 WindowIconify Callback, runs when window is minimized/restored
static void WindowDropCallback(GLFWwindow *window, int count, const char **paths); // GLFW3 Window Drop Callback, runs when drop files into window
#endif
#if defined(PLATFORM_ANDROID)
static void AndroidCommandCallback(struct android_app *app, int32_t cmd); // Process Android activity lifecycle commands
static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event); // Process Android inputs
#endif
#if defined(PLATFORM_WEB)
static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *event, void *userData);
static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData);
static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData);
static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData);
static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData);
#endif
#if defined(PLATFORM_RPI)
#if defined(SUPPORT_SSH_KEYBOARD_RPI)
static void InitKeyboard(void); // Init raw keyboard system (standard input reading)
static void ProcessKeyboard(void); // Process keyboard events
static void RestoreKeyboard(void); // Restore keyboard system
#else
static void InitTerminal(void); // Init terminal (block echo and signal short cuts)
static void RestoreTerminal(void); // Restore terminal
#endif
static void InitEvdevInput(void); // Evdev inputs initialization
static void EventThreadSpawn(char *device); // Identifies a input device and spawns a thread to handle it if needed
static void *EventThread(void *arg); // Input device events reading thread
static void InitGamepad(void); // Init raw gamepad input
static void *GamepadThread(void *arg); // Mouse reading thread
#endif // PLATFORM_RPI
#if defined(_WIN32)
// NOTE: We include Sleep() function signature here to avoid windows.h inclusion
void __stdcall Sleep(unsigned long msTimeout); // Required for Wait()
#endif
//----------------------------------------------------------------------------------
// Module Functions Definition - Window and OpenGL Context Functions
//----------------------------------------------------------------------------------
#if defined(PLATFORM_ANDROID)
// To allow easier porting to android, we allow the user to define a
// main function which we call from android_main, defined by ourselves
extern int main(int argc, char *argv[]);
void android_main(struct android_app *app)
{
char arg0[] = "raylib"; // NOTE: argv[] are mutable
CORE.Android.app = app;
// TODO: Should we maybe report != 0 return codes somewhere?
(void)main(1, (char *[]) { arg0, NULL });
}
// TODO: Add this to header (if apps really need it)
struct android_app *GetAndroidApp(void)
{
return CORE.Android.app;
}
#endif
#if defined(PLATFORM_RPI) && !defined(SUPPORT_SSH_KEYBOARD_RPI)
// Init terminal (block echo and signal short cuts)
static void InitTerminal(void)
{
TRACELOG(LOG_INFO, "RPI: Reconfiguring terminal...");
// Save terminal keyboard settings and reconfigure terminal with new settings
struct termios keyboardNewSettings;
tcgetattr(STDIN_FILENO, &CORE.Input.Keyboard.defaultSettings); // Get current keyboard settings
keyboardNewSettings = CORE.Input.Keyboard.defaultSettings;
// New terminal settings for keyboard: turn off buffering (non-canonical mode), echo
// NOTE: ISIG controls if ^C and ^Z generate break signals or not
keyboardNewSettings.c_lflag &= ~(ICANON | ECHO | ISIG);
keyboardNewSettings.c_cc[VMIN] = 1;
keyboardNewSettings.c_cc[VTIME] = 0;
// Set new keyboard settings (change occurs immediately)
tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings);
// Save old keyboard mode to restore it at the end
if (ioctl(STDIN_FILENO, KDGKBMODE, &CORE.Input.Keyboard.defaultMode) < 0)
{
// NOTE: It could mean we are using a remote keyboard through ssh or from the desktop
TRACELOG(LOG_WARNING, "RPI: Failed to change keyboard mode (not a local terminal)");
}
else ioctl(STDIN_FILENO, KDSKBMODE, K_XLATE);
// Register terminal restore when program finishes
atexit(RestoreTerminal);
}
// Restore terminal
static void RestoreTerminal(void)
{
TRACELOG(LOG_INFO, "RPI: Restoring terminal...");
// Reset to default keyboard settings
tcsetattr(STDIN_FILENO, TCSANOW, &CORE.Input.Keyboard.defaultSettings);
// Reconfigure keyboard to default mode
ioctl(STDIN_FILENO, KDSKBMODE, CORE.Input.Keyboard.defaultMode);
}
#endif
// Initialize window and OpenGL context
// NOTE: data parameter could be used to pass any kind of required data to the initialization
void InitWindow(int width, int height, const char *title)
{
TRACELOG(LOG_INFO, "Initializing raylib %s", RAYLIB_VERSION);
CORE.Window.title = title;
// Initialize required global values different than 0
CORE.Input.Keyboard.exitKey = KEY_ESCAPE;
CORE.Input.Mouse.scale = (Vector2){ 1.0f, 1.0f };
CORE.Input.Gamepad.lastButtonPressed = -1;
#if defined(PLATFORM_ANDROID)
CORE.Window.screen.width = width;
CORE.Window.screen.height = height;
CORE.Window.currentFbo.width = width;
CORE.Window.currentFbo.height = height;
// Input data is android app pointer
CORE.Android.internalDataPath = CORE.Android.app->activity->internalDataPath;
// Set desired windows flags before initializing anything
ANativeActivity_setWindowFlags(CORE.Android.app->activity, AWINDOW_FLAG_FULLSCREEN, 0); //AWINDOW_FLAG_SCALED, AWINDOW_FLAG_DITHER
int orientation = AConfiguration_getOrientation(CORE.Android.app->config);
if (orientation == ACONFIGURATION_ORIENTATION_PORT) TRACELOG(LOG_INFO, "ANDROID: Window orientation set as portrait");
else if (orientation == ACONFIGURATION_ORIENTATION_LAND) TRACELOG(LOG_INFO, "ANDROID: Window orientation set as landscape");
// TODO: Automatic orientation doesn't seem to work
if (width <= height)
{
AConfiguration_setOrientation(CORE.Android.app->config, ACONFIGURATION_ORIENTATION_PORT);
TRACELOG(LOG_WARNING, "ANDROID: Window orientation changed to portrait");
}
else
{
AConfiguration_setOrientation(CORE.Android.app->config, ACONFIGURATION_ORIENTATION_LAND);
TRACELOG(LOG_WARNING, "ANDROID: Window orientation changed to landscape");
}
//AConfiguration_getDensity(CORE.Android.app->config);
//AConfiguration_getKeyboard(CORE.Android.app->config);
//AConfiguration_getScreenSize(CORE.Android.app->config);
//AConfiguration_getScreenLong(CORE.Android.app->config);
CORE.Android.app->onAppCmd = AndroidCommandCallback;
CORE.Android.app->onInputEvent = AndroidInputCallback;
InitAssetManager(CORE.Android.app->activity->assetManager, CORE.Android.app->activity->internalDataPath);
TRACELOG(LOG_INFO, "ANDROID: App initialized successfully");
// Android ALooper_pollAll() variables
int pollResult = 0;
int pollEvents = 0;
// Wait for window to be initialized (display and context)
while (!CORE.Window.ready)
{
// Process events loop
while ((pollResult = ALooper_pollAll(0, NULL, &pollEvents, (void**)&CORE.Android.source)) >= 0)
{
// Process this event
if (CORE.Android.source != NULL) CORE.Android.source->process(CORE.Android.app, CORE.Android.source);
// NOTE: Never close window, native activity is controlled by the system!
//if (CORE.Android.app->destroyRequested != 0) CORE.Window.shouldClose = true;
}
}
#else
// Init graphics device (display device and OpenGL context)
// NOTE: returns true if window and graphic device has been initialized successfully
CORE.Window.ready = InitGraphicsDevice(width, height);
if (!CORE.Window.ready) return;
// Init hi-res timer
InitTimer();
#if defined(SUPPORT_DEFAULT_FONT)
// Load default font
// NOTE: External functions (defined in module: text)
LoadFontDefault();
Rectangle rec = GetFontDefault().recs[95];
// NOTE: We setup a 1px padding on char rectangle to avoid pixel bleeding on MSAA filtering
SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 1, rec.y + 1, rec.width - 2, rec.height - 2 });
#endif
#if defined(PLATFORM_DESKTOP) && defined(SUPPORT_HIGH_DPI)
// Set default font texture filter for HighDPI (blurry)
SetTextureFilter(GetFontDefault().texture, FILTER_BILINEAR);
#endif
#if defined(PLATFORM_RPI)
// Init raw input system
InitEvdevInput(); // Evdev inputs initialization
InitGamepad(); // Gamepad init
#if defined(SUPPORT_SSH_KEYBOARD_RPI)
InitKeyboard(); // Keyboard init
#else
InitTerminal(); // Terminal init
#endif
#endif
#if defined(PLATFORM_WEB)
// Detect fullscreen change events
emscripten_set_fullscreenchange_callback("#canvas", NULL, 1, EmscriptenFullscreenChangeCallback);
// Support keyboard events
emscripten_set_keypress_callback("#canvas", NULL, 1, EmscriptenKeyboardCallback);
// Support mouse events
emscripten_set_click_callback("#canvas", NULL, 1, EmscriptenMouseCallback);
// Support touch events
emscripten_set_touchstart_callback("#canvas", NULL, 1, EmscriptenTouchCallback);
emscripten_set_touchend_callback("#canvas", NULL, 1, EmscriptenTouchCallback);
emscripten_set_touchmove_callback("#canvas", NULL, 1, EmscriptenTouchCallback);
emscripten_set_touchcancel_callback("#canvas", NULL, 1, EmscriptenTouchCallback);
// Support gamepad events (not provided by GLFW3 on emscripten)
emscripten_set_gamepadconnected_callback(NULL, 1, EmscriptenGamepadCallback);
emscripten_set_gamepaddisconnected_callback(NULL, 1, EmscriptenGamepadCallback);
#endif
CORE.Input.Mouse.position.x = (float)CORE.Window.screen.width/2.0f;
CORE.Input.Mouse.position.y = (float)CORE.Window.screen.height/2.0f;
#endif // PLATFORM_ANDROID
}
// Close window and unload OpenGL context
void CloseWindow(void)
{
#if defined(SUPPORT_GIF_RECORDING)
if (gifRecording)
{
GifEnd();
gifRecording = false;
}
#endif
#if defined(SUPPORT_DEFAULT_FONT)
UnloadFontDefault();
#endif
rlglClose(); // De-init rlgl
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
glfwDestroyWindow(CORE.Window.handle);
glfwTerminate();
#endif
#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32)
timeEndPeriod(1); // Restore time period
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
// Close surface, context and display
if (CORE.Window.device != EGL_NO_DISPLAY)
{
eglMakeCurrent(CORE.Window.device, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (CORE.Window.surface != EGL_NO_SURFACE)
{
eglDestroySurface(CORE.Window.device, CORE.Window.surface);
CORE.Window.surface = EGL_NO_SURFACE;
}
if (CORE.Window.context != EGL_NO_CONTEXT)
{
eglDestroyContext(CORE.Window.device, CORE.Window.context);
CORE.Window.context = EGL_NO_CONTEXT;
}
eglTerminate(CORE.Window.device);
CORE.Window.device = EGL_NO_DISPLAY;
}
#endif
#if defined(PLATFORM_RPI)
// Wait for mouse and gamepad threads to finish before closing
// NOTE: Those threads should already have finished at this point
// because they are controlled by CORE.Window.shouldClose variable
CORE.Window.shouldClose = true; // Added to force threads to exit when the close window is called
for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i)
{
if (CORE.Input.eventWorker[i].threadId)
{
pthread_join(CORE.Input.eventWorker[i].threadId, NULL);
}
}
if (CORE.Input.Gamepad.threadId) pthread_join(CORE.Input.Gamepad.threadId, NULL);
#endif
TRACELOG(LOG_INFO, "Window closed successfully");
}
// Check if window has been initialized successfully
bool IsWindowReady(void)
{
return CORE.Window.ready;
}
// Check if KEY_ESCAPE pressed or Close icon pressed
bool WindowShouldClose(void)
{
#if defined(PLATFORM_WEB)
// Emterpreter-Async required to run sync code
// https://github.com/emscripten-core/emscripten/wiki/Emterpreter#emterpreter-async-run-synchronous-code
// By default, this function is never called on a web-ready raylib example because we encapsulate
// frame code in a UpdateDrawFrame() function, to allow browser manage execution asynchronously
// but now emscripten allows sync code to be executed in an interpreted way, using emterpreter!
emscripten_sleep(16);
return false;
#endif
#if defined(PLATFORM_DESKTOP)
if (CORE.Window.ready)
{
// While window minimized, stop loop execution
while (!CORE.Window.alwaysRun && CORE.Window.minimized) glfwWaitEvents();
CORE.Window.shouldClose = glfwWindowShouldClose(CORE.Window.handle);
return CORE.Window.shouldClose;
}
else return true;
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
if (CORE.Window.ready) return CORE.Window.shouldClose;
else return true;
#endif
}
// Check if window has been minimized (or lost focus)
bool IsWindowMinimized(void)
{
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP)
return CORE.Window.minimized;
#else
return false;
#endif
}
// Check if window has been resized
bool IsWindowResized(void)
{
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP)
return CORE.Window.resized;
#else
return false;
#endif
}
// Check if window is currently hidden
bool IsWindowHidden(void)
{
#if defined(PLATFORM_DESKTOP)
return (glfwGetWindowAttrib(CORE.Window.handle, GLFW_VISIBLE) == GL_FALSE);
#endif
return false;
}
// Check if window is currently fullscreen
bool IsWindowFullscreen(void)
{
return CORE.Window.fullscreen;
}
// Toggle fullscreen mode (only PLATFORM_DESKTOP)
void ToggleFullscreen(void)
{
CORE.Window.fullscreen = !CORE.Window.fullscreen; // Toggle fullscreen flag
#if defined(PLATFORM_DESKTOP)
// NOTE: glfwSetWindowMonitor() doesn't work properly (bugs)
if (CORE.Window.fullscreen)
{
// Store previous window position (in case we exit fullscreen)
glfwGetWindowPos(CORE.Window.handle, &CORE.Window.position.x, &CORE.Window.position.y);
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
TRACELOG(LOG_WARNING, "GLFW: Failed to get monitor");
glfwSetWindowMonitor(CORE.Window.handle, glfwGetPrimaryMonitor(), 0, 0, CORE.Window.screen.width, CORE.Window.screen.height, GLFW_DONT_CARE);
return;
}
const GLFWvidmode *mode = glfwGetVideoMode(monitor);
glfwSetWindowMonitor(CORE.Window.handle, glfwGetPrimaryMonitor(), 0, 0, CORE.Window.screen.width, CORE.Window.screen.height, mode->refreshRate);
// Try to enable GPU V-Sync, so frames are limited to screen refresh rate (60Hz -> 60 FPS)
// NOTE: V-Sync can be enabled by graphic driver configuration
if (CORE.Window.flags & FLAG_VSYNC_HINT) glfwSwapInterval(1);
}
else glfwSetWindowMonitor(CORE.Window.handle, NULL, CORE.Window.position.x, CORE.Window.position.y, CORE.Window.screen.width, CORE.Window.screen.height, GLFW_DONT_CARE);
#endif
#if defined(PLATFORM_WEB)
if (CORE.Window.fullscreen) EM_ASM(Module.requestFullscreen(false, false););
else EM_ASM(document.exitFullscreen(););
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI)
TRACELOG(LOG_WARNING, "SYSTEM: Failed to toggle to windowed mode");
#endif
}
// Set icon for window (only PLATFORM_DESKTOP)
// NOTE: Image must be in RGBA format, 8bit per channel
void SetWindowIcon(Image image)
{
#if defined(PLATFORM_DESKTOP)
if (image.format == UNCOMPRESSED_R8G8B8A8)
{
GLFWimage icon[1] = { 0 };
icon[0].width = image.width;
icon[0].height = image.height;
icon[0].pixels = (unsigned char *)image.data;
// NOTE 1: We only support one image icon
// NOTE 2: The specified image data is copied before this function returns
glfwSetWindowIcon(CORE.Window.handle, 1, icon);
}
else TRACELOG(LOG_WARNING, "GLFW: Window icon image must be in R8G8B8A8 pixel format");
#endif
}
// Set title for window (only PLATFORM_DESKTOP)
void SetWindowTitle(const char *title)
{
CORE.Window.title = title;
#if defined(PLATFORM_DESKTOP)
glfwSetWindowTitle(CORE.Window.handle, title);
#endif
}
// Set window position on screen (windowed mode)
void SetWindowPosition(int x, int y)
{
#if defined(PLATFORM_DESKTOP)
glfwSetWindowPos(CORE.Window.handle, x, y);
#endif
}
// Set monitor for the current window (fullscreen mode)
void SetWindowMonitor(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount = 0;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
TRACELOG(LOG_INFO, "GLFW: Selected fullscreen monitor: [%i] %s", monitor, glfwGetMonitorName(monitors[monitor]));
const GLFWvidmode *mode = glfwGetVideoMode(monitors[monitor]);
glfwSetWindowMonitor(CORE.Window.handle, monitors[monitor], 0, 0, mode->width, mode->height, mode->refreshRate);
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
}
// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
void SetWindowMinSize(int width, int height)
{
#if defined(PLATFORM_DESKTOP)
const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowSizeLimits(CORE.Window.handle, width, height, mode->width, mode->height);
#endif
}
// Set window dimensions
// TODO: Issues on HighDPI scaling
void SetWindowSize(int width, int height)
{
#if defined(PLATFORM_DESKTOP)
glfwSetWindowSize(CORE.Window.handle, width, height);
#endif
#if defined(PLATFORM_WEB)
emscripten_set_canvas_size(width, height); // DEPRECATED!
// TODO: Below functions should be used to replace previous one but
// they do not seem to work properly
//emscripten_set_canvas_element_size("canvas", width, height);
//emscripten_set_element_css_size("canvas", width, height);
#endif
}
// Show the window
void UnhideWindow(void)
{
#if defined(PLATFORM_DESKTOP)
glfwShowWindow(CORE.Window.handle);
#endif
}
// Hide the window
void HideWindow(void)
{
#if defined(PLATFORM_DESKTOP)
glfwHideWindow(CORE.Window.handle);
#endif
}
// Get current screen width
int GetScreenWidth(void)
{
return CORE.Window.screen.width;
}
// Get current screen height
int GetScreenHeight(void)
{
return CORE.Window.screen.height;
}
// Get native window handle
void *GetWindowHandle(void)
{
#if defined(PLATFORM_DESKTOP) && defined(_WIN32)
// NOTE: Returned handle is: void *HWND (windows.h)
return glfwGetWin32Window(CORE.Window.handle);
#elif defined(__linux__)
// NOTE: Returned handle is: unsigned long Window (X.h)
// typedef unsigned long XID;
// typedef XID Window;
//unsigned long id = (unsigned long)glfwGetX11Window(window);
return NULL; // TODO: Find a way to return value... cast to void *?
#elif defined(__APPLE__)
// NOTE: Returned handle is: (objc_object *)
return NULL; // TODO: return (void *)glfwGetCocoaWindow(window);
#else
return NULL;
#endif
}
// Get number of monitors
int GetMonitorCount(void)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
glfwGetMonitors(&monitorCount);
return monitorCount;
#else
return 1;
#endif
}
// Get primary monitor width
int GetMonitorWidth(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
const GLFWvidmode *mode = glfwGetVideoMode(monitors[monitor]);
return mode->width;
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
return 0;
}
// Get primary monitor width
int GetMonitorHeight(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
const GLFWvidmode *mode = glfwGetVideoMode(monitors[monitor]);
return mode->height;
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
return 0;
}
// Get primary montior physical width in millimetres
int GetMonitorPhysicalWidth(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
int physicalWidth;
glfwGetMonitorPhysicalSize(monitors[monitor], &physicalWidth, NULL);
return physicalWidth;
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
return 0;
}
// Get primary monitor physical height in millimetres
int GetMonitorPhysicalHeight(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
int physicalHeight;
glfwGetMonitorPhysicalSize(monitors[monitor], NULL, &physicalHeight);
return physicalHeight;
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
return 0;
}
// Get window position XY on monitor
Vector2 GetWindowPosition(void)
{
int x = 0;
int y = 0;
#if defined(PLATFORM_DESKTOP)
glfwGetWindowPos(CORE.Window.handle, &x, &y);
#endif
return (Vector2){ (float)x, (float)y };
}
// Get the human-readable, UTF-8 encoded name of the primary monitor
const char *GetMonitorName(int monitor)
{
#if defined(PLATFORM_DESKTOP)
int monitorCount;
GLFWmonitor **monitors = glfwGetMonitors(&monitorCount);
if ((monitor >= 0) && (monitor < monitorCount))
{
return glfwGetMonitorName(monitors[monitor]);
}
else TRACELOG(LOG_WARNING, "GLFW: Failed to find selected monitor");
#endif
return "";
}
// Get clipboard text content
// NOTE: returned string is allocated and freed by GLFW
const char *GetClipboardText(void)
{
#if defined(PLATFORM_DESKTOP)
return glfwGetClipboardString(CORE.Window.handle);
#else
return NULL;
#endif
}
// Set clipboard text content
void SetClipboardText(const char *text)
{
#if defined(PLATFORM_DESKTOP)
glfwSetClipboardString(CORE.Window.handle, text);
#endif
}
// Show mouse cursor
void ShowCursor(void)
{
#if defined(PLATFORM_DESKTOP)
glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
#endif
#if defined(PLATFORM_UWP)
UWPMessage *msg = CreateUWPMessage();
msg->type = UWP_MSG_SHOW_MOUSE;
SendMessageToUWP(msg);
#endif
CORE.Input.Mouse.cursorHidden = false;
}
// Hides mouse cursor
void HideCursor(void)
{
#if defined(PLATFORM_DESKTOP)
glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
#endif
#if defined(PLATFORM_UWP)
UWPMessage *msg = CreateUWPMessage();
msg->type = UWP_MSG_HIDE_MOUSE;
SendMessageToUWP(msg);
#endif
CORE.Input.Mouse.cursorHidden = true;
}
// Check if cursor is not visible
bool IsCursorHidden(void)
{
return CORE.Input.Mouse.cursorHidden;
}
// Enables cursor (unlock cursor)
void EnableCursor(void)
{
#if defined(PLATFORM_DESKTOP)
glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
#endif
#if defined(PLATFORM_WEB)
CORE.Input.Mouse.cursorLockRequired = true;
#endif
#if defined(PLATFORM_UWP)
UWPMessage *msg = CreateUWPMessage();
msg->type = UWP_MSG_LOCK_MOUSE;
SendMessageToUWP(msg);
#endif
CORE.Input.Mouse.cursorHidden = false;
}
// Disables cursor (lock cursor)
void DisableCursor(void)
{
#if defined(PLATFORM_DESKTOP)
glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
#endif
#if defined(PLATFORM_WEB)
CORE.Input.Mouse.cursorLockRequired = true;
#endif
#if defined(PLATFORM_UWP)
UWPMessage *msg = CreateUWPMessage();
msg->type = UWP_MSG_UNLOCK_MOUSE;
SendMessageToUWP(msg);
#endif
CORE.Input.Mouse.cursorHidden = true;
}
// Set background color (framebuffer clear color)
void ClearBackground(Color color)
{
rlClearColor(color.r, color.g, color.b, color.a); // Set clear color
rlClearScreenBuffers(); // Clear current framebuffers
}
// Setup canvas (framebuffer) to start drawing
void BeginDrawing(void)
{
CORE.Time.current = GetTime(); // Number of elapsed seconds since InitTimer()
CORE.Time.update = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling
//rlTranslatef(0.375, 0.375, 0); // HACK to have 2D pixel-perfect drawing on OpenGL 1.1
// NOTE: Not required with OpenGL 3.3+
}
// End canvas drawing and swap buffers (double buffering)
void EndDrawing(void)
{
#if defined(PLATFORM_RPI) && defined(SUPPORT_MOUSE_CURSOR_RPI)
// On RPI native mode we have no system mouse cursor, so,
// we draw a small rectangle for user reference
DrawRectangle(CORE.Input.Mouse.position.x, CORE.Input.Mouse.position.y, 3, 3, MAROON);
#endif
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
#if defined(SUPPORT_GIF_RECORDING)
#define GIF_RECORD_FRAMERATE 10
if (gifRecording)
{
gifFramesCounter++;
// NOTE: We record one gif frame every 10 game frames
if ((gifFramesCounter%GIF_RECORD_FRAMERATE) == 0)
{
// Get image data for the current frame (from backbuffer)
// NOTE: This process is very slow... :(
unsigned char *screenData = rlReadScreenPixels(CORE.Window.screen.width, CORE.Window.screen.height);
GifWriteFrame(screenData, CORE.Window.screen.width, CORE.Window.screen.height, 10, 8, false);
RL_FREE(screenData); // Free image data
}
if (((gifFramesCounter/15)%2) == 1)
{
DrawCircle(30, CORE.Window.screen.height - 20, 10, RED);
DrawText("RECORDING", 50, CORE.Window.screen.height - 25, 10, MAROON);
}
rlglDraw(); // Draw RECORDING message
}
#endif
SwapBuffers(); // Copy back buffer to front buffer
PollInputEvents(); // Poll user events
// Frame time control system
CORE.Time.current = GetTime();
CORE.Time.draw = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
CORE.Time.frame = CORE.Time.update + CORE.Time.draw;
// Wait for some milliseconds...
if (CORE.Time.frame < CORE.Time.target)
{
Wait((float)(CORE.Time.target - CORE.Time.frame)*1000.0f);
CORE.Time.current = GetTime();
double waitTime = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
CORE.Time.frame += waitTime; // Total frame time: update + draw + wait
//SetWindowTitle(FormatText("Update: %f, Draw: %f, Req.Wait: %f, Real.Wait: %f, Total: %f, Target: %f\n",
// (float)CORE.Time.update, (float)CORE.Time.draw, (float)(CORE.Time.target - (CORE.Time.update + CORE.Time.draw)),
// (float)waitTime, (float)CORE.Time.frame, (float)CORE.Time.target));
}
}
// Initialize 2D mode with custom camera (2D)
void BeginMode2D(Camera2D camera)
{
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
// Apply 2d camera transformation to modelview
rlMultMatrixf(MatrixToFloat(GetCameraMatrix2D(camera)));
// Apply screen scaling if required
rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale));
}
// Ends 2D mode with custom camera
void EndMode2D(void)
{
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required
}
// Initializes 3D mode with custom camera (3D)
void BeginMode3D(Camera3D camera)
{
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
rlPushMatrix(); // Save previous matrix, which contains the settings for the 2d ortho projection
rlLoadIdentity(); // Reset current matrix (PROJECTION)
float aspect = (float)CORE.Window.currentFbo.width/(float)CORE.Window.currentFbo.height;
if (camera.type == CAMERA_PERSPECTIVE)
{
// Setup perspective projection
double top = 0.01*tan(camera.fovy*0.5*DEG2RAD);
double right = top*aspect;
rlFrustum(-right, right, -top, top, DEFAULT_NEAR_CULL_DISTANCE, DEFAULT_FAR_CULL_DISTANCE);
}
else if (camera.type == CAMERA_ORTHOGRAPHIC)
{
// Setup orthographic projection
double top = camera.fovy/2.0;
double right = top*aspect;
rlOrtho(-right, right, -top,top, DEFAULT_NEAR_CULL_DISTANCE, DEFAULT_FAR_CULL_DISTANCE);
}
// NOTE: zNear and zFar values are important when computing depth buffer values
rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
// Setup Camera view
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
rlMultMatrixf(MatrixToFloat(matView)); // Multiply MODELVIEW matrix by view matrix (camera)
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
}
// Ends 3D mode and returns to default 2D orthographic mode
void EndMode3D(void)
{
rlglDraw(); // Process internal buffers (update + draw)
rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
rlPopMatrix(); // Restore previous matrix (PROJECTION) from matrix stack
rlMatrixMode(RL_MODELVIEW); // Get back to modelview matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required
rlDisableDepthTest(); // Disable DEPTH_TEST for 2D
}
// Initializes render texture for drawing
void BeginTextureMode(RenderTexture2D target)
{
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlEnableRenderTexture(target.id); // Enable render target
// Set viewport to framebuffer size
rlViewport(0, 0, target.texture.width, target.texture.height);
rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix
rlLoadIdentity(); // Reset current matrix (PROJECTION)
// Set orthographic projection to current framebuffer size
// NOTE: Configured top-left corner as (0, 0)
rlOrtho(0, target.texture.width, target.texture.height, 0, 0.0f, 1.0f);
rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
//rlScalef(0.0f, -1.0f, 0.0f); // Flip Y-drawing (?)
// Setup current width/height for proper aspect ratio
// calculation when using BeginMode3D()
CORE.Window.currentFbo.width = target.texture.width;
CORE.Window.currentFbo.height = target.texture.height;
}
// Ends drawing to render texture
void EndTextureMode(void)
{
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlDisableRenderTexture(); // Disable render target
// Set viewport to default framebuffer size
SetupViewport(CORE.Window.render.width, CORE.Window.render.height);
// Reset current screen size
CORE.Window.currentFbo.width = GetScreenWidth();
CORE.Window.currentFbo.height = GetScreenHeight();
}
// Begin scissor mode (define screen area for following drawing)
// NOTE: Scissor rec refers to bottom-left corner, we change it to upper-left
void BeginScissorMode(int x, int y, int width, int height)
{
rlglDraw(); // Force drawing elements
rlEnableScissorTest();
rlScissor(x, GetScreenHeight() - (y + height), width, height);
}
// End scissor mode
void EndScissorMode(void)
{
rlglDraw(); // Force drawing elements
rlDisableScissorTest();
}
// Returns a ray trace from mouse position
Ray GetMouseRay(Vector2 mouse, Camera camera)
{
Ray ray;
// Calculate normalized device coordinates
// NOTE: y value is negative
float x = (2.0f*mouse.x)/(float)GetScreenWidth() - 1.0f;
float y = 1.0f - (2.0f*mouse.y)/(float)GetScreenHeight();
float z = 1.0f;
// Store values in a vector
Vector3 deviceCoords = { x, y, z };
// Calculate view matrix from camera look at
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
Matrix matProj = MatrixIdentity();
if (camera.type == CAMERA_PERSPECTIVE)
{
// Calculate projection matrix from perspective
matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)GetScreenWidth()/(double)GetScreenHeight()), DEFAULT_NEAR_CULL_DISTANCE, DEFAULT_FAR_CULL_DISTANCE);
}
else if (camera.type == CAMERA_ORTHOGRAPHIC)
{
float aspect = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
double top = camera.fovy/2.0;
double right = top*aspect;
// Calculate projection matrix from orthographic
matProj = MatrixOrtho(-right, right, -top, top, 0.01, 1000.0);
}
// Unproject far/near points
Vector3 nearPoint = rlUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView);
Vector3 farPoint = rlUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView);
// Unproject the mouse cursor in the near plane.
// We need this as the source position because orthographic projects, compared to perspect doesn't have a
// convergence point, meaning that the "eye" of the camera is more like a plane than a point.
Vector3 cameraPlanePointerPos = rlUnproject((Vector3){ deviceCoords.x, deviceCoords.y, -1.0f }, matProj, matView);
// Calculate normalized direction vector
Vector3 direction = Vector3Normalize(Vector3Subtract(farPoint, nearPoint));
if (camera.type == CAMERA_PERSPECTIVE) ray.position = camera.position;
else if (camera.type == CAMERA_ORTHOGRAPHIC) ray.position = cameraPlanePointerPos;
// Apply calculated vectors to ray
ray.direction = direction;
return ray;
}
// Get transform matrix for camera
Matrix GetCameraMatrix(Camera camera)
{
return MatrixLookAt(camera.position, camera.target, camera.up);
}
// Returns camera 2d transform matrix
Matrix GetCameraMatrix2D(Camera2D camera)
{
Matrix matTransform = { 0 };
// The camera in world-space is set by
// 1. Move it to target
// 2. Rotate by -rotation and scale by (1/zoom)
// When setting higher scale, it's more intuitive for the world to become bigger (= camera become smaller),
// not for the camera getting bigger, hence the invert. Same deal with rotation.
// 3. Move it by (-offset);
// Offset defines target transform relative to screen, but since we're effectively "moving" screen (camera)
// we need to do it into opposite direction (inverse transform)
// Having camera transform in world-space, inverse of it gives the modelview transform.
// Since (A*B*C)' = C'*B'*A', the modelview is
// 1. Move to offset
// 2. Rotate and Scale
// 3. Move by -target
Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f);
Matrix matRotation = MatrixRotate((Vector3){ 0.0f, 0.0f, 1.0f }, camera.rotation*DEG2RAD);
Matrix matScale = MatrixScale(camera.zoom, camera.zoom, 1.0f);
Matrix matTranslation = MatrixTranslate(camera.offset.x, camera.offset.y, 0.0f);
matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation);
return matTransform;
}
// Returns the screen space position from a 3d world space position
Vector2 GetWorldToScreen(Vector3 position, Camera camera)
{
Vector2 screenPosition = GetWorldToScreenEx(position, camera, GetScreenWidth(), GetScreenHeight());
return screenPosition;
}
// Returns size position for a 3d world space position (useful for texture drawing)
Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height)
{
// Calculate projection matrix (from perspective instead of frustum
Matrix matProj = MatrixIdentity();
if (camera.type == CAMERA_PERSPECTIVE)
{
// Calculate projection matrix from perspective
matProj = MatrixPerspective(camera.fovy * DEG2RAD, ((double)width/(double)height), DEFAULT_NEAR_CULL_DISTANCE, DEFAULT_FAR_CULL_DISTANCE);
}
else if (camera.type == CAMERA_ORTHOGRAPHIC)
{
float aspect = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
double top = camera.fovy/2.0;
double right = top*aspect;
// Calculate projection matrix from orthographic
matProj = MatrixOrtho(-right, right, -top, top, DEFAULT_NEAR_CULL_DISTANCE, DEFAULT_FAR_CULL_DISTANCE);
}
// Calculate view matrix from camera look at (and transpose it)
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
// Convert world position vector to quaternion
Quaternion worldPos = { position.x, position.y, position.z, 1.0f };
// Transform world position to view
worldPos = QuaternionTransform(worldPos, matView);
// Transform result to projection (clip space position)
worldPos = QuaternionTransform(worldPos, matProj);
// Calculate normalized device coordinates (inverted y)
Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w };
// Calculate 2d screen position vector
Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)width, (ndcPos.y + 1.0f)/2.0f*(float)height };
return screenPosition;
}
// Returns the screen space position for a 2d camera world space position
Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera)
{
Matrix matCamera = GetCameraMatrix2D(camera);
Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, matCamera);
return (Vector2){ transform.x, transform.y };
}
// Returns the world space position for a 2d camera screen space position
Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera)
{
Matrix invMatCamera = MatrixInvert(GetCameraMatrix2D(camera));
Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, invMatCamera);
return (Vector2){ transform.x, transform.y };
}
// Set target FPS (maximum)
void SetTargetFPS(int fps)
{
if (fps < 1) CORE.Time.target = 0.0;
else CORE.Time.target = 1.0/(double)fps;
TRACELOG(LOG_INFO, "TIMER: Target time per frame: %02.03f milliseconds", (float)CORE.Time.target*1000);
}
// Returns current FPS
// NOTE: We calculate an average framerate
int GetFPS(void)
{
#define FPS_CAPTURE_FRAMES_COUNT 30 // 30 captures
#define FPS_AVERAGE_TIME_SECONDS 0.5f // 500 millisecondes
#define FPS_STEP (FPS_AVERAGE_TIME_SECONDS/FPS_CAPTURE_FRAMES_COUNT)
static int index = 0;
static float history[FPS_CAPTURE_FRAMES_COUNT] = { 0 };
static float average = 0, last = 0;
float fpsFrame = GetFrameTime();
if (fpsFrame == 0) return 0;
if ((GetTime() - last) > FPS_STEP)
{
last = GetTime();
index = (index + 1)%FPS_CAPTURE_FRAMES_COUNT;
average -= history[index];
history[index] = fpsFrame/FPS_CAPTURE_FRAMES_COUNT;
average += history[index];
}
return (int)roundf(1.0f/average);
}
// Returns time in seconds for last frame drawn
float GetFrameTime(void)
{
return (float)CORE.Time.frame;
}
// Get elapsed time measure in seconds since InitTimer()
// NOTE: On PLATFORM_DESKTOP InitTimer() is called on InitWindow()
// NOTE: On PLATFORM_DESKTOP, timer is initialized on glfwInit()
double GetTime(void)
{
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
return glfwGetTime(); // Elapsed time since glfwInit()
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI)
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
unsigned long long int time = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;
return (double)(time - CORE.Time.base)*1e-9; // Elapsed time since InitTimer()
#endif
#if defined(PLATFORM_UWP)
// Updated through messages
return CORE.Time.current;
#endif
}
// Returns hexadecimal value for a Color
int ColorToInt(Color color)
{
return (((int)color.r << 24) | ((int)color.g << 16) | ((int)color.b << 8) | (int)color.a);
}
// Returns color normalized as float [0..1]
Vector4 ColorNormalize(Color color)
{
Vector4 result;
result.x = (float)color.r/255.0f;
result.y = (float)color.g/255.0f;
result.z = (float)color.b/255.0f;
result.w = (float)color.a/255.0f;
return result;
}
// Returns color from normalized values [0..1]
Color ColorFromNormalized(Vector4 normalized)
{
Color result;
result.r = normalized.x*255.0f;
result.g = normalized.y*255.0f;
result.b = normalized.z*255.0f;
result.a = normalized.w*255.0f;
return result;
}
// Returns HSV values for a Color
// NOTE: Hue is returned as degrees [0..360]
Vector3 ColorToHSV(Color color)
{
Vector3 hsv = { 0 };
Vector3 rgb = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
float min, max, delta;
min = rgb.x < rgb.y? rgb.x : rgb.y;
min = min < rgb.z? min : rgb.z;
max = rgb.x > rgb.y? rgb.x : rgb.y;
max = max > rgb.z? max : rgb.z;
hsv.z = max; // Value
delta = max - min;
if (delta < 0.00001f)
{
hsv.y = 0.0f;
hsv.x = 0.0f; // Undefined, maybe NAN?
return hsv;
}
if (max > 0.0f)
{
// NOTE: If max is 0, this divide would cause a crash
hsv.y = (delta/max); // Saturation
}
else
{
// NOTE: If max is 0, then r = g = b = 0, s = 0, h is undefined
hsv.y = 0.0f;
hsv.x = NAN; // Undefined
return hsv;
}
// NOTE: Comparing float values could not work properly
if (rgb.x >= max) hsv.x = (rgb.y - rgb.z)/delta; // Between yellow & magenta
else
{
if (rgb.y >= max) hsv.x = 2.0f + (rgb.z - rgb.x)/delta; // Between cyan & yellow
else hsv.x = 4.0f + (rgb.x - rgb.y)/delta; // Between magenta & cyan
}
hsv.x *= 60.0f; // Convert to degrees
if (hsv.x < 0.0f) hsv.x += 360.0f;
return hsv;
}
// Returns a Color from HSV values
// Implementation reference: https://en.wikipedia.org/wiki/HSL_and_HSV#Alternative_HSV_conversion
// NOTE: Color->HSV->Color conversion will not yield exactly the same color due to rounding errors
Color ColorFromHSV(Vector3 hsv)
{
Color color = { 0, 0, 0, 255 };
float h = hsv.x, s = hsv.y, v = hsv.z;
// Red channel
float k = fmod((5.0f + h/60.0f), 6);
float t = 4.0f - k;
k = (t < k)? t : k;
k = (k < 1)? k : 1;
k = (k > 0)? k : 0;
color.r = (v - v*s*k)*255;
// Green channel
k = fmod((3.0f + h/60.0f), 6);
t = 4.0f - k;
k = (t < k)? t : k;
k = (k < 1)? k : 1;
k = (k > 0)? k : 0;
color.g = (v - v*s*k)*255;
// Blue channel
k = fmod((1.0f + h/60.0f), 6);
t = 4.0f - k;
k = (t < k)? t : k;
k = (k < 1)? k : 1;
k = (k > 0)? k : 0;
color.b = (v - v*s*k)*255;
return color;
}
// Returns a Color struct from hexadecimal value
Color GetColor(int hexValue)
{
Color color;
color.r = (unsigned char)(hexValue >> 24) & 0xFF;
color.g = (unsigned char)(hexValue >> 16) & 0xFF;
color.b = (unsigned char)(hexValue >> 8) & 0xFF;
color.a = (unsigned char)hexValue & 0xFF;
return color;
}
// Returns a random value between min and max (both included)
int GetRandomValue(int min, int max)
{
if (min > max)
{
int tmp = max;
max = min;
min = tmp;
}
return (rand()%(abs(max - min) + 1) + min);
}
// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f
Color Fade(Color color, float alpha)
{
if (alpha < 0.0f) alpha = 0.0f;
else if (alpha > 1.0f) alpha = 1.0f;
return (Color){color.r, color.g, color.b, (unsigned char)(255.0f*alpha)};
}
// Setup window configuration flags (view FLAGS)
void SetConfigFlags(unsigned int flags)
{
CORE.Window.flags = flags;
if (CORE.Window.flags & FLAG_FULLSCREEN_MODE) CORE.Window.fullscreen = true;
if (CORE.Window.flags & FLAG_WINDOW_ALWAYS_RUN) CORE.Window.alwaysRun = true;
}
// NOTE TRACELOG() function is located in [utils.h]
// Takes a screenshot of current screen (saved a .png)
// NOTE: This function could work in any platform but some platforms: PLATFORM_ANDROID and PLATFORM_WEB
// have their own internal file-systems, to dowload image to user file-system some additional mechanism is required
void TakeScreenshot(const char *fileName)
{
unsigned char *imgData = rlReadScreenPixels(CORE.Window.render.width, CORE.Window.render.height);
Image image = { imgData, CORE.Window.render.width, CORE.Window.render.height, 1, UNCOMPRESSED_R8G8B8A8 };
char path[512] = { 0 };
#if defined(PLATFORM_ANDROID)
strcpy(path, CORE.Android.internalDataPath);
strcat(path, "/");
strcat(path, fileName);
#else
strcpy(path, fileName);
#endif
ExportImage(image, path);
RL_FREE(imgData);
#if defined(PLATFORM_WEB)
// Download file from MEMFS (emscripten memory filesystem)
// saveFileFromMEMFSToDisk() function is defined in raylib/src/shell.html
emscripten_run_script(TextFormat("saveFileFromMEMFSToDisk('%s','%s')", GetFileName(path), GetFileName(path)));
#endif
// TODO: Verification required for log
TRACELOG(LOG_INFO, "SYSTEM: [%s] Screenshot taken successfully", path);
}
// Check if the file exists
bool FileExists(const char *fileName)
{
bool result = false;
#if defined(_WIN32)
if (_access(fileName, 0) != -1) result = true;
#else
if (access(fileName, F_OK) != -1) result = true;
#endif
return result;
}
// Check file extension
// NOTE: Extensions checking is not case-sensitive
bool IsFileExtension(const char *fileName, const char *ext)
{
bool result = false;
const char *fileExt = GetExtension(fileName);
if (fileExt != NULL)
{
int extCount = 0;
const char **checkExts = TextSplit(ext, ';', &extCount);
char fileExtLower[16] = { 0 };
strcpy(fileExtLower, TextToLower(fileExt));
for (int i = 0; i < extCount; i++)
{
if (TextIsEqual(fileExtLower, TextToLower(checkExts[i] + 1)))
{
result = true;
break;
}
}
}
return result;
}
// Check if a directory path exists
bool DirectoryExists(const char *dirPath)
{
bool result = false;
DIR *dir = opendir(dirPath);
if (dir != NULL)
{
result = true;
closedir(dir);
}
return result;
}
// Get pointer to extension for a filename string
const char *GetExtension(const char *fileName)
{
const char *dot = strrchr(fileName, '.');
if (!dot || dot == fileName) return NULL;
return (dot + 1);
}
// String pointer reverse break: returns right-most occurrence of charset in s
static const char *strprbrk(const char *s, const char *charset)
{
const char *latestMatch = NULL;
for (; s = strpbrk(s, charset), s != NULL; latestMatch = s++) { }
return latestMatch;
}
// Get pointer to filename for a path string
const char *GetFileName(const char *filePath)
{
const char *fileName = NULL;
if (filePath != NULL) fileName = strprbrk(filePath, "\\/");
if (!fileName || (fileName == filePath)) return filePath;
return fileName + 1;
}
// Get filename string without extension (uses static string)
const char *GetFileNameWithoutExt(const char *filePath)
{
#define MAX_FILENAMEWITHOUTEXT_LENGTH 128
static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH];
memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH);
if (filePath != NULL) strcpy(fileName, GetFileName(filePath)); // Get filename with extension
int len = strlen(fileName);
for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++)
{
if (fileName[i] == '.')
{
// NOTE: We break on first '.' found
fileName[i] = '\0';
break;
}
}
return fileName;
}
// Get directory for a given filePath
const char *GetDirectoryPath(const char *filePath)
{
/*
// NOTE: Directory separator is different in Windows and other platforms,
// fortunately, Windows also support the '/' separator, that's the one should be used
#if defined(_WIN32)
char separator = '\\';
#else
char separator = '/';
#endif
*/
const char *lastSlash = NULL;
static char dirPath[MAX_FILEPATH_LENGTH];
memset(dirPath, 0, MAX_FILEPATH_LENGTH);
// In case provided path does not contains a root drive letter (C:\, D:\),
// we add the current directory path to dirPath
if (filePath[1] != ':')
{
// For security, we set starting path to current directory,
// obtained path will be concated to this
dirPath[0] = '.';
dirPath[1] = '/';
}
lastSlash = strprbrk(filePath, "\\/");
if (lastSlash)
{
// NOTE: Be careful, strncpy() is not safe, it does not care about '\0'
strncpy(dirPath + ((filePath[1] != ':')? 2 : 0), filePath, strlen(filePath) - (strlen(lastSlash) - 1));
dirPath[strlen(filePath) - strlen(lastSlash) + ((filePath[1] != ':')? 2 : 0)] = '\0'; // Add '\0' manually
}
return dirPath;
}
// Get previous directory path for a given path
const char *GetPrevDirectoryPath(const char *dirPath)
{
static char prevDirPath[MAX_FILEPATH_LENGTH];
memset(prevDirPath, 0, MAX_FILEPATH_LENGTH);
int pathLen = strlen(dirPath);
if (pathLen <= 3) strcpy(prevDirPath, dirPath);
for (int i = (pathLen - 1); (i > 0) && (pathLen > 3); i--)
{
if ((dirPath[i] == '\\') || (dirPath[i] == '/'))
{
if (i == 2) i++; // Check for root: "C:\"
strncpy(prevDirPath, dirPath, i);
break;
}
}
return prevDirPath;
}
// Get current working directory
const char *GetWorkingDirectory(void)
{
static char currentDir[MAX_FILEPATH_LENGTH];
memset(currentDir, 0, MAX_FILEPATH_LENGTH);
GETCWD(currentDir, MAX_FILEPATH_LENGTH - 1);
return currentDir;
}
// Get filenames in a directory path (max 512 files)
// NOTE: Files count is returned by parameters pointer
char **GetDirectoryFiles(const char *dirPath, int *fileCount)
{
#define MAX_DIRECTORY_FILES 512
ClearDirectoryFiles();
// Memory allocation for MAX_DIRECTORY_FILES
dirFilesPath = (char **)RL_MALLOC(sizeof(char *)*MAX_DIRECTORY_FILES);
for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
int counter = 0;
struct dirent *entity;
DIR *dir = opendir(dirPath);
if (dir != NULL) // It's a directory
{
// TODO: Reading could be done in two passes,
// first one to count files and second one to read names
// That way we can allocate required memory, instead of a limited pool
while ((entity = readdir(dir)) != NULL)
{
strcpy(dirFilesPath[counter], entity->d_name);
counter++;
}
closedir(dir);
}
else TRACELOG(LOG_WARNING, "FILEIO: Failed to open requested directory"); // Maybe it's a file...
dirFilesCount = counter;
*fileCount = dirFilesCount;
return dirFilesPath;
}
// Clear directory files paths buffers
void ClearDirectoryFiles(void)
{
if (dirFilesCount > 0)
{
for (int i = 0; i < MAX_DIRECTORY_FILES; i++) RL_FREE(dirFilesPath[i]);
RL_FREE(dirFilesPath);
}
dirFilesCount = 0;
}
// Change working directory, returns true if success
bool ChangeDirectory(const char *dir)
{
return (CHDIR(dir) == 0);
}
// Check if a file has been dropped into window
bool IsFileDropped(void)
{
if (CORE.Window.dropFilesCount > 0) return true;
else return false;
}
// Get dropped files names
char **GetDroppedFiles(int *count)
{
*count = CORE.Window.dropFilesCount;
return CORE.Window.dropFilesPath;
}
// Clear dropped files paths buffer
void ClearDroppedFiles(void)
{
if (CORE.Window.dropFilesCount > 0)
{
for (int i = 0; i < CORE.Window.dropFilesCount; i++) RL_FREE(CORE.Window.dropFilesPath[i]);
RL_FREE(CORE.Window.dropFilesPath);
CORE.Window.dropFilesCount = 0;
}
}
// Get file modification time (last write time)
long GetFileModTime(const char *fileName)
{
struct stat result = { 0 };
if (stat(fileName, &result) == 0)
{
time_t mod = result.st_mtime;
return (long)mod;
}
return 0;
}
// Compress data (DEFLATE algorythm)
unsigned char *CompressData(unsigned char *data, int dataLength, int *compDataLength)
{
#define COMPRESSION_QUALITY_DEFLATE 8
unsigned char *compData = NULL;
#if defined(SUPPORT_COMPRESSION_API)
compData = stbi_zlib_compress(data, dataLength, compDataLength, COMPRESSION_QUALITY_DEFLATE);
#endif
return compData;
}
// Decompress data (DEFLATE algorythm)
unsigned char *DecompressData(unsigned char *compData, int compDataLength, int *dataLength)
{
char *data = NULL;
#if defined(SUPPORT_COMPRESSION_API)
data = stbi_zlib_decode_malloc((char *)compData, compDataLength, dataLength);
#endif
return (unsigned char *)data;
}
// Save integer value to storage file (to defined position)
// NOTE: Storage positions is directly related to file memory layout (4 bytes each integer)
void SaveStorageValue(unsigned int position, int value)
{
#if defined(SUPPORT_DATA_STORAGE)
char path[512] = { 0 };
#if defined(PLATFORM_ANDROID)
strcpy(path, CORE.Android.internalDataPath);
strcat(path, "/");
strcat(path, STORAGE_DATA_FILE);
#else
strcpy(path, STORAGE_DATA_FILE);
#endif
unsigned int dataSize = 0;
unsigned int newDataSize = 0;
unsigned char *fileData = LoadFileData(path, &dataSize);
unsigned char *newFileData = NULL;
if (fileData != NULL)
{
if (dataSize <= (position*sizeof(int)))
{
// Increase data size up to position and store value
newDataSize = (position + 1)*sizeof(int);
newFileData = (unsigned char *)RL_REALLOC(fileData, newDataSize);
if (newFileData != NULL)
{
// RL_REALLOC succeded
int *dataPtr = (int *)newFileData;
dataPtr[position] = value;
}
else
{
// RL_REALLOC failed
TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to realloc data (%u), position in bytes (%u) bigger than actual file size", path, dataSize, position*sizeof(int));
// We store the old size of the file
newFileData = fileData;
newDataSize = dataSize;
}
}
else
{
// Store the old size of the file
newFileData = fileData;
newDataSize = dataSize;
// Replace value on selected position
int *dataPtr = (int *)newFileData;
dataPtr[position] = value;
}
SaveFileData(path, newFileData, newDataSize);
RL_FREE(newFileData);
}
else
{
TRACELOG(LOG_INFO, "FILEIO: [%s] File not found, creating it", path);
dataSize = (position + 1)*sizeof(int);
fileData = (unsigned char *)RL_MALLOC(dataSize);
int *dataPtr = (int *)fileData;
dataPtr[position] = value;
SaveFileData(path, fileData, dataSize);
RL_FREE(fileData);
}
#endif
}
// Load integer value from storage file (from defined position)
// NOTE: If requested position could not be found, value 0 is returned
int LoadStorageValue(unsigned int position)
{
int value = 0;
#if defined(SUPPORT_DATA_STORAGE)
char path[512] = { 0 };
#if defined(PLATFORM_ANDROID)
strcpy(path, CORE.Android.internalDataPath);
strcat(path, "/");
strcat(path, STORAGE_DATA_FILE);
#else
strcpy(path, STORAGE_DATA_FILE);
#endif
unsigned int dataSize = 0;
unsigned char *fileData = LoadFileData(path, &dataSize);
if (fileData != NULL)
{
if (dataSize < (position*4)) TRACELOG(LOG_WARNING, "SYSTEM: Failed to find storage position");
else
{
int *dataPtr = (int *)fileData;
value = dataPtr[position];
}
RL_FREE(fileData);
}
#endif
return value;
}
// Open URL with default system browser (if available)
// NOTE: This function is only safe to use if you control the URL given.
// A user could craft a malicious string performing another action.
// Only call this function yourself not with user input or make sure to check the string yourself.
// CHECK: https://github.com/raysan5/raylib/issues/686
void OpenURL(const char *url)
{
// Small security check trying to avoid (partially) malicious code...
// sorry for the inconvenience when you hit this point...
if (strchr(url, '\'') != NULL)
{
TRACELOG(LOG_WARNING, "SYSTEM: Provided URL is not valid");
}
else
{
#if defined(PLATFORM_DESKTOP)
char *cmd = (char *)RL_CALLOC(strlen(url) + 10, sizeof(char));
#if defined(_WIN32)
sprintf(cmd, "explorer %s", url);
#elif defined(__linux__)
sprintf(cmd, "xdg-open '%s'", url); // Alternatives: firefox, x-www-browser
#elif defined(__APPLE__)
sprintf(cmd, "open '%s'", url);
#endif
system(cmd);
RL_FREE(cmd);
#endif
#if defined(PLATFORM_WEB)
emscripten_run_script(TextFormat("window.open('%s', '_blank')", url));
#endif
}
}
//----------------------------------------------------------------------------------
// Module Functions Definition - Input (Keyboard, Mouse, Gamepad) Functions
//----------------------------------------------------------------------------------
// Detect if a key has been pressed once
bool IsKeyPressed(int key)
{
bool pressed = false;
if ((CORE.Input.Keyboard.previousKeyState[key] == 0) && (CORE.Input.Keyboard.currentKeyState[key] == 1)) pressed = true;
else pressed = false;
return pressed;
}
// Detect if a key is being pressed (key held down)
bool IsKeyDown(int key)
{
if (CORE.Input.Keyboard.currentKeyState[key] == 1) return true;
else return false;
}
// Detect if a key has been released once
bool IsKeyReleased(int key)
{
bool released = false;
if ((CORE.Input.Keyboard.previousKeyState[key] == 1) && (CORE.Input.Keyboard.currentKeyState[key] == 0)) released = true;
else released = false;
return released;
}
// Detect if a key is NOT being pressed (key not held down)
bool IsKeyUp(int key)
{
if (CORE.Input.Keyboard.currentKeyState[key] == 0) return true;
else return false;
}
// Get the last key pressed
int GetKeyPressed(void)
{
int value = 0;
if (CORE.Input.Keyboard.keyPressedQueueCount > 0)
{
// Get character from the queue head
value = CORE.Input.Keyboard.keyPressedQueue[0];
// Shift elements 1 step toward the head.
for (int i = 0; i < (CORE.Input.Keyboard.keyPressedQueueCount - 1); i++) CORE.Input.Keyboard.keyPressedQueue[i] = CORE.Input.Keyboard.keyPressedQueue[i + 1];
// Reset last character in the queue
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 0;
CORE.Input.Keyboard.keyPressedQueueCount--;
}
return value;
}
// Set a custom key to exit program
// NOTE: default exitKey is ESCAPE
void SetExitKey(int key)
{
#if !defined(PLATFORM_ANDROID)
CORE.Input.Keyboard.exitKey = key;
#endif
}
// NOTE: Gamepad support not implemented in emscripten GLFW3 (PLATFORM_WEB)
// Detect if a gamepad is available
bool IsGamepadAvailable(int gamepad)
{
bool result = false;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad]) result = true;
#endif
return result;
}
// Check gamepad name (if available)
bool IsGamepadName(int gamepad, const char *name)
{
bool result = false;
#if !defined(PLATFORM_ANDROID)
const char *currentName = NULL;
if (CORE.Input.Gamepad.ready[gamepad]) currentName = GetGamepadName(gamepad);
if ((name != NULL) && (currentName != NULL)) result = (strcmp(name, currentName) == 0);
#endif
return result;
}
// Return gamepad internal name id
const char *GetGamepadName(int gamepad)
{
#if defined(PLATFORM_DESKTOP)
if (CORE.Input.Gamepad.ready[gamepad]) return glfwGetJoystickName(gamepad);
else return NULL;
#elif defined(PLATFORM_RPI)
if (CORE.Input.Gamepad.ready[gamepad]) ioctl(CORE.Input.Gamepad.streamId[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name);
return CORE.Input.Gamepad.name;
#else
return NULL;
#endif
}
// Return gamepad axis count
int GetGamepadAxisCount(int gamepad)
{
#if defined(PLATFORM_RPI)
int axisCount = 0;
if (CORE.Input.Gamepad.ready[gamepad]) ioctl(CORE.Input.Gamepad.streamId[gamepad], JSIOCGAXES, &axisCount);
CORE.Input.Gamepad.axisCount = axisCount;
#endif
return CORE.Input.Gamepad.axisCount;
}
// Return axis movement vector for a gamepad
float GetGamepadAxisMovement(int gamepad, int axis)
{
float value = 0;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (axis < MAX_GAMEPAD_AXIS)) value = CORE.Input.Gamepad.axisState[gamepad][axis];
#endif
return value;
}
// Detect if a gamepad button has been pressed once
bool IsGamepadButtonPressed(int gamepad, int button)
{
bool pressed = false;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) &&
(CORE.Input.Gamepad.currentState[gamepad][button] != CORE.Input.Gamepad.previousState[gamepad][button]) &&
(CORE.Input.Gamepad.currentState[gamepad][button] == 1)) pressed = true;
#endif
return pressed;
}
// Detect if a gamepad button is being pressed
bool IsGamepadButtonDown(int gamepad, int button)
{
bool result = false;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) &&
(CORE.Input.Gamepad.currentState[gamepad][button] == 1)) result = true;
#endif
return result;
}
// Detect if a gamepad button has NOT been pressed once
bool IsGamepadButtonReleased(int gamepad, int button)
{
bool released = false;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) &&
(CORE.Input.Gamepad.currentState[gamepad][button] != CORE.Input.Gamepad.previousState[gamepad][button]) &&
(CORE.Input.Gamepad.currentState[gamepad][button] == 0)) released = true;
#endif
return released;
}
// Detect if a mouse button is NOT being pressed
bool IsGamepadButtonUp(int gamepad, int button)
{
bool result = false;
#if !defined(PLATFORM_ANDROID)
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) &&
(CORE.Input.Gamepad.currentState[gamepad][button] == 0)) result = true;
#endif
return result;
}
// Get the last gamepad button pressed
int GetGamepadButtonPressed(void)
{
return CORE.Input.Gamepad.lastButtonPressed;
}
// Detect if a mouse button has been pressed once
bool IsMouseButtonPressed(int button)
{
bool pressed = false;
if ((CORE.Input.Mouse.currentButtonState[button] == 1) && (CORE.Input.Mouse.previousButtonState[button] == 0)) pressed = true;
// Map touches to mouse buttons checking
if ((CORE.Input.Touch.currentTouchState[button] == 1) && (CORE.Input.Touch.previousTouchState[button] == 0)) pressed = true;
return pressed;
}
// Detect if a mouse button is being pressed
bool IsMouseButtonDown(int button)
{
bool down = false;
if (CORE.Input.Mouse.currentButtonState[button] == 1) down = true;
// Map touches to mouse buttons checking
if (CORE.Input.Touch.currentTouchState[button] == 1) down = true;
return down;
}
// Detect if a mouse button has been released once
bool IsMouseButtonReleased(int button)
{
bool released = false;
if ((CORE.Input.Mouse.currentButtonState[button] == 0) && (CORE.Input.Mouse.previousButtonState[button] == 1)) released = true;
// Map touches to mouse buttons checking
if ((CORE.Input.Touch.currentTouchState[button] == 0) && (CORE.Input.Touch.previousTouchState[button] == 1)) released = true;
return released;
}
// Detect if a mouse button is NOT being pressed
bool IsMouseButtonUp(int button)
{
return !IsMouseButtonDown(button);
}
// Returns mouse position X
int GetMouseX(void)
{
#if defined(PLATFORM_ANDROID)
return (int)CORE.Input.Touch.position[0].x;
#else
return (int)((CORE.Input.Mouse.position.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x);
#endif
}
// Returns mouse position Y
int GetMouseY(void)
{
#if defined(PLATFORM_ANDROID)
return (int)CORE.Input.Touch.position[0].y;
#else
return (int)((CORE.Input.Mouse.position.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y);
#endif
}
// Returns mouse position XY
Vector2 GetMousePosition(void)
{
Vector2 position = { 0 };
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB)
position = GetTouchPosition(0);
#else
position.x = (CORE.Input.Mouse.position.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x;
position.y = (CORE.Input.Mouse.position.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y;
#endif
return position;
}
// Set mouse position XY
void SetMousePosition(int x, int y)
{
CORE.Input.Mouse.position = (Vector2){ (float)x, (float)y };
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
// NOTE: emscripten not implemented
glfwSetCursorPos(CORE.Window.handle, CORE.Input.Mouse.position.x, CORE.Input.Mouse.position.y);
#endif
#if defined(PLATFORM_UWP)
UWPMessage *msg = CreateUWPMessage();
msg->type = UWP_MSG_SET_MOUSE_LOCATION;
msg->paramVector0.x = CORE.Input.Mouse.position.x;
msg->paramVector0.y = CORE.Input.Mouse.position.y;
SendMessageToUWP(msg);
#endif
}
// Set mouse offset
// NOTE: Useful when rendering to different size targets
void SetMouseOffset(int offsetX, int offsetY)
{
CORE.Input.Mouse.offset = (Vector2){ (float)offsetX, (float)offsetY };
}
// Set mouse scaling
// NOTE: Useful when rendering to different size targets
void SetMouseScale(float scaleX, float scaleY)
{
CORE.Input.Mouse.scale = (Vector2){ scaleX, scaleY };
}
// Returns mouse wheel movement Y
int GetMouseWheelMove(void)
{
#if defined(PLATFORM_ANDROID)
return 0;
#elif defined(PLATFORM_WEB)
return CORE.Input.Mouse.previousWheelMove/100;
#else
return CORE.Input.Mouse.previousWheelMove;
#endif
}
// Returns touch position X for touch point 0 (relative to screen size)
int GetTouchX(void)
{
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB)
return (int)CORE.Input.Touch.position[0].x;
#else // PLATFORM_DESKTOP, PLATFORM_RPI
return GetMouseX();
#endif
}
// Returns touch position Y for touch point 0 (relative to screen size)
int GetTouchY(void)
{
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB)
return (int)CORE.Input.Touch.position[0].y;
#else // PLATFORM_DESKTOP, PLATFORM_RPI
return GetMouseY();
#endif
}
// Returns touch position XY for a touch point index (relative to screen size)
// TODO: Touch position should be scaled depending on display size and render size
Vector2 GetTouchPosition(int index)
{
Vector2 position = { -1.0f, -1.0f };
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) || defined(PLATFORM_RPI)
if (index < MAX_TOUCH_POINTS) position = CORE.Input.Touch.position[index];
else TRACELOG(LOG_WARNING, "INPUT: Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS);
#if defined(PLATFORM_ANDROID)
if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
{
position.x = position.x*((float)CORE.Window.screen.width/(float)(CORE.Window.display.width - CORE.Window.renderOffset.x)) - CORE.Window.renderOffset.x/2;
position.y = position.y*((float)CORE.Window.screen.height/(float)(CORE.Window.display.height - CORE.Window.renderOffset.y)) - CORE.Window.renderOffset.y/2;
}
else
{
position.x = position.x*((float)CORE.Window.render.width/(float)CORE.Window.display.width) - CORE.Window.renderOffset.x/2;
position.y = position.y*((float)CORE.Window.render.height/(float)CORE.Window.display.height) - CORE.Window.renderOffset.y/2;
}
#endif
#elif defined(PLATFORM_DESKTOP)
// TODO: GLFW is not supporting multi-touch input just yet
// https://www.codeproject.com/Articles/668404/Programming-for-Multi-Touch
// https://docs.microsoft.com/en-us/windows/win32/wintouch/getting-started-with-multi-touch-messages
if (index == 0) position = GetMousePosition();
#endif
return position;
}
//----------------------------------------------------------------------------------
// Module specific Functions Definition
//----------------------------------------------------------------------------------
// Initialize display device and framebuffer
// NOTE: width and height represent the screen (framebuffer) desired size, not actual display size
// If width or height are 0, default display size will be used for framebuffer size
// NOTE: returns false in case graphic device could not be created
static bool InitGraphicsDevice(int width, int height)
{
CORE.Window.screen.width = width; // User desired width
CORE.Window.screen.height = height; // User desired height
CORE.Window.screenScale = MatrixIdentity(); // No draw scaling required by default
// NOTE: Framebuffer (render area - CORE.Window.render.width, CORE.Window.render.height) could include black bars...
// ...in top-down or left-right to match display aspect ratio (no weird scalings)
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
glfwSetErrorCallback(ErrorCallback);
#if defined(__APPLE__)
glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, GLFW_FALSE);
#endif
if (!glfwInit())
{
TRACELOG(LOG_WARNING, "GLFW: Failed to initialize GLFW");
return false;
}
// NOTE: Getting video modes is not implemented in emscripten GLFW3 version
#if defined(PLATFORM_DESKTOP)
// Find monitor resolution
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
TRACELOG(LOG_WARNING, "GLFW: Failed to get primary monitor");
return false;
}
const GLFWvidmode *mode = glfwGetVideoMode(monitor);
CORE.Window.display.width = mode->width;
CORE.Window.display.height = mode->height;
// Screen size security check
if (CORE.Window.screen.width <= 0) CORE.Window.screen.width = CORE.Window.display.width;
if (CORE.Window.screen.height <= 0) CORE.Window.screen.height = CORE.Window.display.height;
#endif // PLATFORM_DESKTOP
#if defined(PLATFORM_WEB)
CORE.Window.display.width = CORE.Window.screen.width;
CORE.Window.display.height = CORE.Window.screen.height;
#endif // PLATFORM_WEB
glfwDefaultWindowHints(); // Set default windows hints:
//glfwWindowHint(GLFW_RED_BITS, 8); // Framebuffer red color component bits
//glfwWindowHint(GLFW_GREEN_BITS, 8); // Framebuffer green color component bits
//glfwWindowHint(GLFW_BLUE_BITS, 8); // Framebuffer blue color component bits
//glfwWindowHint(GLFW_ALPHA_BITS, 8); // Framebuffer alpha color component bits
//glfwWindowHint(GLFW_DEPTH_BITS, 24); // Depthbuffer bits
//glfwWindowHint(GLFW_REFRESH_RATE, 0); // Refresh rate for fullscreen window
//glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API
//glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers
#if defined(PLATFORM_DESKTOP) && defined(SUPPORT_HIGH_DPI)
// Resize window content area based on the monitor content scale.
// NOTE: This hint only has an effect on platforms where screen coordinates and pixels always map 1:1 such as Windows and X11.
// On platforms like macOS the resolution of the framebuffer is changed independently of the window size.
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on
#endif
// Check some Window creation flags
if (CORE.Window.flags & FLAG_WINDOW_HIDDEN) glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // Visible window
else glfwWindowHint(GLFW_VISIBLE, GL_TRUE); // Window initially hidden
if (CORE.Window.flags & FLAG_WINDOW_RESIZABLE) glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // Resizable window
else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Avoid window being resizable
if (CORE.Window.flags & FLAG_WINDOW_UNDECORATED) glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); // Border and buttons on Window
else glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); // Decorated window
// FLAG_WINDOW_TRANSPARENT not supported on HTML5 and not included in any released GLFW version yet
#if defined(GLFW_TRANSPARENT_FRAMEBUFFER)
if (CORE.Window.flags & FLAG_WINDOW_TRANSPARENT) glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); // Transparent framebuffer
else glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE); // Opaque framebuffer
#endif
if (CORE.Window.flags & FLAG_MSAA_4X_HINT) glfwWindowHint(GLFW_SAMPLES, 4); // Tries to enable multisampling x4 (MSAA), default is 0
// NOTE: When asking for an OpenGL context version, most drivers provide highest supported version
// with forward compatibility to older OpenGL versions.
// For example, if using OpenGL 1.1, driver can provide a 4.3 context forward compatible.
// Check selection OpenGL version
if (rlGetVersion() == OPENGL_21)
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); // Choose OpenGL major version (just hint)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // Choose OpenGL minor version (just hint)
}
else if (rlGetVersion() == OPENGL_33)
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Choose OpenGL major version (just hint)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Choose OpenGL minor version (just hint)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Profiles Hint: Only 3.3 and above!
// Values: GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_ANY_PROFILE, GLFW_OPENGL_COMPAT_PROFILE
#if defined(__APPLE__)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); // OSX Requires fordward compatibility
#else
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_FALSE); // Fordward Compatibility Hint: Only 3.3 and above!
#endif
//glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); // Request OpenGL DEBUG context
}
else if (rlGetVersion() == OPENGL_ES_20) // Request OpenGL ES 2.0 context
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
#if defined(PLATFORM_DESKTOP)
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
#else
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
#endif
}
if (CORE.Window.fullscreen)
{
// remember center for switchinging from fullscreen to window
CORE.Window.position.x = CORE.Window.display.width/2 - CORE.Window.screen.width/2;
CORE.Window.position.y = CORE.Window.display.height/2 - CORE.Window.screen.height/2;
if (CORE.Window.position.x < 0) CORE.Window.position.x = 0;
if (CORE.Window.position.y < 0) CORE.Window.position.y = 0;
// Obtain recommended CORE.Window.display.width/CORE.Window.display.height from a valid videomode for the monitor
int count = 0;
const GLFWvidmode *modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count);
// Get closest video mode to desired CORE.Window.screen.width/CORE.Window.screen.height
for (int i = 0; i < count; i++)
{
if (modes[i].width >= CORE.Window.screen.width)
{
if (modes[i].height >= CORE.Window.screen.height)
{
CORE.Window.display.width = modes[i].width;
CORE.Window.display.height = modes[i].height;
break;
}
}
}
#if defined(PLATFORM_DESKTOP)
// If we are windowed fullscreen, ensures that window does not minimize when focus is lost
if ((CORE.Window.screen.height == CORE.Window.display.height) && (CORE.Window.screen.width == CORE.Window.display.width))
{
glfwWindowHint(GLFW_AUTO_ICONIFY, 0);
}
#endif
TRACELOG(LOG_WARNING, "SYSTEM: Closest fullscreen videomode: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
// NOTE: ISSUE: Closest videomode could not match monitor aspect-ratio, for example,
// for a desired screen size of 800x450 (16:9), closest supported videomode is 800x600 (4:3),
// framebuffer is rendered correctly but once displayed on a 16:9 monitor, it gets stretched
// by the sides to fit all monitor space...
// Try to setup the most appropiate fullscreen framebuffer for the requested screenWidth/screenHeight
// It considers device display resolution mode and setups a framebuffer with black bars if required (render size/offset)
// Modified global variables: CORE.Window.screen.width/CORE.Window.screen.height - CORE.Window.render.width/CORE.Window.render.height - CORE.Window.renderOffset.x/CORE.Window.renderOffset.y - CORE.Window.screenScale
// TODO: It is a quite cumbersome solution to display size vs requested size, it should be reviewed or removed...
// HighDPI monitors are properly considered in a following similar function: SetupViewport()
SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
CORE.Window.handle = glfwCreateWindow(CORE.Window.display.width, CORE.Window.display.height, CORE.Window.title, glfwGetPrimaryMonitor(), NULL);
// NOTE: Full-screen change, not working properly...
//glfwSetWindowMonitor(CORE.Window.handle, glfwGetPrimaryMonitor(), 0, 0, CORE.Window.screen.width, CORE.Window.screen.height, GLFW_DONT_CARE);
}
else
{
// No-fullscreen window creation
CORE.Window.handle = glfwCreateWindow(CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.title, NULL, NULL);
if (CORE.Window.handle)
{
#if defined(PLATFORM_DESKTOP)
// Center window on screen
int windowPosX = CORE.Window.display.width/2 - CORE.Window.screen.width/2;
int windowPosY = CORE.Window.display.height/2 - CORE.Window.screen.height/2;
if (windowPosX < 0) windowPosX = 0;
if (windowPosY < 0) windowPosY = 0;
glfwSetWindowPos(CORE.Window.handle, windowPosX, windowPosY);
#endif
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
}
}
if (!CORE.Window.handle)
{
glfwTerminate();
TRACELOG(LOG_WARNING, "GLFW: Failed to initialize Window");
return false;
}
else
{
TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully");
#if defined(PLATFORM_DESKTOP)
TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
#endif
TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
}
glfwSetWindowSizeCallback(CORE.Window.handle, WindowSizeCallback); // NOTE: Resizing not allowed by default!
glfwSetCursorEnterCallback(CORE.Window.handle, CursorEnterCallback);
glfwSetKeyCallback(CORE.Window.handle, KeyCallback);
glfwSetMouseButtonCallback(CORE.Window.handle, MouseButtonCallback);
glfwSetCursorPosCallback(CORE.Window.handle, MouseCursorPosCallback); // Track mouse position changes
glfwSetCharCallback(CORE.Window.handle, CharCallback);
glfwSetScrollCallback(CORE.Window.handle, ScrollCallback);
glfwSetWindowIconifyCallback(CORE.Window.handle, WindowIconifyCallback);
glfwSetDropCallback(CORE.Window.handle, WindowDropCallback);
glfwMakeContextCurrent(CORE.Window.handle);
#if !defined(PLATFORM_WEB)
glfwSwapInterval(0); // No V-Sync by default
#endif
#if defined(PLATFORM_DESKTOP)
// Load OpenGL 3.3 extensions
// NOTE: GLFW loader function is passed as parameter
rlLoadExtensions(glfwGetProcAddress);
#endif
// Try to enable GPU V-Sync, so frames are limited to screen refresh rate (60Hz -> 60 FPS)
// NOTE: V-Sync can be enabled by graphic driver configuration
if (CORE.Window.flags & FLAG_VSYNC_HINT)
{
// WARNING: It seems to hits a critical render path in Intel HD Graphics
glfwSwapInterval(1);
TRACELOG(LOG_INFO, "DISPLAY: Trying to enable VSYNC");
}
#endif // PLATFORM_DESKTOP || PLATFORM_WEB
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
CORE.Window.fullscreen = true;
// Screen size security check
if (CORE.Window.screen.width <= 0) CORE.Window.screen.width = CORE.Window.display.width;
if (CORE.Window.screen.height <= 0) CORE.Window.screen.height = CORE.Window.display.height;
#if defined(PLATFORM_RPI)
bcm_host_init();
DISPMANX_ELEMENT_HANDLE_T dispmanElement;
DISPMANX_DISPLAY_HANDLE_T dispmanDisplay;
DISPMANX_UPDATE_HANDLE_T dispmanUpdate;
VC_RECT_T dstRect;
VC_RECT_T srcRect;
#endif
EGLint samples = 0;
EGLint sampleBuffer = 0;
if (CORE.Window.flags & FLAG_MSAA_4X_HINT)
{
samples = 4;
sampleBuffer = 1;
TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4");
}
const EGLint framebufferAttribs[] =
{
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // Type of context support -> Required on RPI?
//EGL_SURFACE_TYPE, EGL_WINDOW_BIT, // Don't use it on Android!
EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5)
EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6)
EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5)
//EGL_ALPHA_SIZE, 8, // ALPHA bit depth (required for transparent framebuffer)
//EGL_TRANSPARENT_TYPE, EGL_NONE, // Request transparent framebuffer (EGL_TRANSPARENT_RGB does not work on RPI)
EGL_DEPTH_SIZE, 16, // Depth buffer size (Required to use Depth testing!)
//EGL_STENCIL_SIZE, 8, // Stencil buffer size
EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA
EGL_SAMPLES, samples, // 4x Antialiasing if activated (Free on MALI GPUs)
EGL_NONE
};
const EGLint contextAttribs[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
#if defined(PLATFORM_UWP)
const EGLint surfaceAttributes[] =
{
// EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER is part of the same optimization as EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER (see above).
// If you have compilation issues with it then please update your Visual Studio templates.
EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_NONE
};
const EGLint defaultDisplayAttributes[] =
{
// These are the default display attributes, used to request ANGLE's D3D11 renderer.
// eglInitialize will only succeed with these attributes if the hardware supports D3D11 Feature Level 10_0+.
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
// EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices.
// Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it.
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
// EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that enables ANGLE to automatically call
// the IDXGIDevice3::Trim method on behalf of the application when it gets suspended.
// Calling IDXGIDevice3::Trim when an application is suspended is a Windows Store application certification requirement.
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
const EGLint fl9_3DisplayAttributes[] =
{
// These can be used to request ANGLE's D3D11 renderer, with D3D11 Feature Level 9_3.
// These attributes are used if the call to eglInitialize fails with the default display attributes.
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3,
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
const EGLint warpDisplayAttributes[] =
{
// These attributes can be used to request D3D11 WARP.
// They are used if eglInitialize fails with both the default display attributes and the 9_3 display attributes.
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE,
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
// eglGetPlatformDisplayEXT is an alternative to eglGetDisplay. It allows us to pass in display attributes, used to configure D3D11.
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get function eglGetPlatformDisplayEXT");
return false;
}
//
// To initialize the display, we make three sets of calls to eglGetPlatformDisplayEXT and eglInitialize, with varying
// parameters passed to eglGetPlatformDisplayEXT:
// 1) The first calls uses "defaultDisplayAttributes" as a parameter. This corresponds to D3D11 Feature Level 10_0+.
// 2) If eglInitialize fails for step 1 (e.g. because 10_0+ isn't supported by the default GPU), then we try again
// using "fl9_3DisplayAttributes". This corresponds to D3D11 Feature Level 9_3.
// 3) If eglInitialize fails for step 2 (e.g. because 9_3+ isn't supported by the default GPU), then we try again
// using "warpDisplayAttributes". This corresponds to D3D11 Feature Level 11_0 on WARP, a D3D11 software rasterizer.
//
// This tries to initialize EGL to D3D11 Feature Level 10_0+. See above comment for details.
CORE.Window.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, defaultDisplayAttributes);
if (CORE.Window.device == EGL_NO_DISPLAY)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE)
{
// This tries to initialize EGL to D3D11 Feature Level 9_3, if 10_0+ is unavailable (e.g. on some mobile devices).
CORE.Window.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, fl9_3DisplayAttributes);
if (CORE.Window.device == EGL_NO_DISPLAY)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE)
{
// This initializes EGL to D3D11 Feature Level 11_0 on WARP, if 9_3+ is unavailable on the default GPU.
CORE.Window.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, warpDisplayAttributes);
if (CORE.Window.device == EGL_NO_DISPLAY)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE)
{
// If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred.
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
}
}
EGLint numConfigs = 0;
if ((eglChooseConfig(CORE.Window.device, framebufferAttribs, &CORE.Window.config, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0))
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose first EGL configuration");
return false;
}
// Create a PropertySet and initialize with the EGLNativeWindowType.
//PropertySet^ surfaceCreationProperties = ref new PropertySet();
//surfaceCreationProperties->Insert(ref new String(EGLNativeWindowTypeProperty), window); // CoreWindow^ window
// You can configure the surface to render at a lower resolution and be scaled up to
// the full window size. The scaling is often free on mobile hardware.
//
// One way to configure the SwapChainPanel is to specify precisely which resolution it should render at.
// Size customRenderSurfaceSize = Size(800, 600);
// surfaceCreationProperties->Insert(ref new String(EGLRenderSurfaceSizeProperty), PropertyValue::CreateSize(customRenderSurfaceSize));
//
// Another way is to tell the SwapChainPanel to render at a certain scale factor compared to its size.
// e.g. if the SwapChainPanel is 1920x1280 then setting a factor of 0.5f will make the app render at 960x640
// float customResolutionScale = 0.5f;
// surfaceCreationProperties->Insert(ref new String(EGLRenderResolutionScaleProperty), PropertyValue::CreateSingle(customResolutionScale));
// eglCreateWindowSurface() requires a EGLNativeWindowType parameter,
// In Windows platform: typedef HWND EGLNativeWindowType;
// Property: EGLNativeWindowTypeProperty
// Type: IInspectable
// Description: Set this property to specify the window type to use for creating a surface.
// If this property is missing, surface creation will fail.
//
//const wchar_t EGLNativeWindowTypeProperty[] = L"EGLNativeWindowTypeProperty";
//https://stackoverflow.com/questions/46550182/how-to-create-eglsurface-using-c-winrt-and-angle
//CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, reinterpret_cast<IInspectable*>(surfaceCreationProperties), surfaceAttributes);
CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, handle, surfaceAttributes);
if (CORE.Window.surface == EGL_NO_SURFACE)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL fullscreen surface");
return false;
}
CORE.Window.context = eglCreateContext(CORE.Window.device, CORE.Window.config, EGL_NO_CONTEXT, contextAttribs);
if (CORE.Window.context == EGL_NO_CONTEXT)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context");
return false;
}
// Get EGL device window size
eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_WIDTH, &CORE.Window.screen.width);
eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_HEIGHT, &CORE.Window.screen.height);
#else // PLATFORM_ANDROID, PLATFORM_RPI
EGLint numConfigs;
// Get an EGL device connection
CORE.Window.device = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (CORE.Window.device == EGL_NO_DISPLAY)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
// Initialize the EGL device connection
if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE)
{
// If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred.
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return false;
}
// Get an appropriate EGL framebuffer configuration
eglChooseConfig(CORE.Window.device, framebufferAttribs, &CORE.Window.config, 1, &numConfigs);
// Set rendering API
eglBindAPI(EGL_OPENGL_ES_API);
// Create an EGL rendering context
CORE.Window.context = eglCreateContext(CORE.Window.device, CORE.Window.config, EGL_NO_CONTEXT, contextAttribs);
if (CORE.Window.context == EGL_NO_CONTEXT)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context");
return false;
}
#endif
// Create an EGL window surface
//---------------------------------------------------------------------------------
#if defined(PLATFORM_ANDROID)
EGLint displayFormat;
// EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is guaranteed to be accepted by ANativeWindow_setBuffersGeometry()
// As soon as we picked a EGLConfig, we can safely reconfigure the ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID
eglGetConfigAttrib(CORE.Window.device, CORE.Window.config, EGL_NATIVE_VISUAL_ID, &displayFormat);
// At this point we need to manage render size vs screen size
// NOTE: This function use and modify global module variables: CORE.Window.screen.width/CORE.Window.screen.height and CORE.Window.render.width/CORE.Window.render.height and CORE.Window.screenScale
SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
ANativeWindow_setBuffersGeometry(CORE.Android.app->window, CORE.Window.render.width, CORE.Window.render.height, displayFormat);
//ANativeWindow_setBuffersGeometry(CORE.Android.app->window, 0, 0, displayFormat); // Force use of native display size
CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, CORE.Android.app->window, NULL);
#endif // PLATFORM_ANDROID
#if defined(PLATFORM_RPI)
graphics_get_display_size(0, &CORE.Window.display.width, &CORE.Window.display.height);
// At this point we need to manage render size vs screen size
// NOTE: This function use and modify global module variables: CORE.Window.screen.width/CORE.Window.screen.height and CORE.Window.render.width/CORE.Window.render.height and CORE.Window.screenScale
SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
dstRect.x = 0;
dstRect.y = 0;
dstRect.width = CORE.Window.display.width;
dstRect.height = CORE.Window.display.height;
srcRect.x = 0;
srcRect.y = 0;
srcRect.width = CORE.Window.render.width << 16;
srcRect.height = CORE.Window.render.height << 16;
// NOTE: RPI dispmanx windowing system takes care of srcRec scaling to dstRec by hardware (no cost)
// Take care that renderWidth/renderHeight fit on displayWidth/displayHeight aspect ratio
VC_DISPMANX_ALPHA_T alpha;
alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS;
//alpha.flags = DISPMANX_FLAGS_ALPHA_FROM_SOURCE; // TODO: Allow transparent framebuffer! -> FLAG_WINDOW_TRANSPARENT
alpha.opacity = 255; // Set transparency level for framebuffer, requires EGLAttrib: EGL_TRANSPARENT_TYPE
alpha.mask = 0;
dispmanDisplay = vc_dispmanx_display_open(0); // LCD
dispmanUpdate = vc_dispmanx_update_start(0);
dispmanElement = vc_dispmanx_element_add(dispmanUpdate, dispmanDisplay, 0/*layer*/, &dstRect, 0/*src*/,
&srcRect, DISPMANX_PROTECTION_NONE, &alpha, 0/*clamp*/, DISPMANX_NO_ROTATE);
CORE.Window.handle.element = dispmanElement;
CORE.Window.handle.width = CORE.Window.render.width;
CORE.Window.handle.height = CORE.Window.render.height;
vc_dispmanx_update_submit_sync(dispmanUpdate);
CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, &CORE.Window.handle, NULL);
//---------------------------------------------------------------------------------
#endif // PLATFORM_RPI
// There must be at least one frame displayed before the buffers are swapped
//eglSwapInterval(CORE.Window.device, 1);
if (eglMakeCurrent(CORE.Window.device, CORE.Window.surface, CORE.Window.surface, CORE.Window.context) == EGL_FALSE)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to attach EGL rendering context to EGL surface");
return false;
}
else
{
// Grab the width and height of the surface
//eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_WIDTH, &CORE.Window.render.width);
//eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_HEIGHT, &CORE.Window.render.height);
TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully");
TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
}
#endif // PLATFORM_ANDROID || PLATFORM_RPI
// Initialize OpenGL context (states and resources)
// NOTE: CORE.Window.screen.width and CORE.Window.screen.height not used, just stored as globals in rlgl
rlglInit(CORE.Window.screen.width, CORE.Window.screen.height);
int fbWidth = CORE.Window.render.width;
int fbHeight = CORE.Window.render.height;
#if defined(PLATFORM_DESKTOP) && defined(SUPPORT_HIGH_DPI)
glfwGetFramebufferSize(CORE.Window.handle, &fbWidth, &fbHeight);
// Screen scaling matrix is required in case desired screen area is different than display area
CORE.Window.screenScale = MatrixScale((float)fbWidth/CORE.Window.screen.width, (float)fbHeight/CORE.Window.screen.height, 1.0f);
#if !defined(__APPLE__)
SetMouseScale((float)CORE.Window.screen.width/fbWidth, (float)CORE.Window.screen.height/fbHeight);
#endif
#endif // PLATFORM_DESKTOP && SUPPORT_HIGH_DPI
// Setup default viewport
SetupViewport(fbWidth, fbHeight);
CORE.Window.currentFbo.width = CORE.Window.screen.width;
CORE.Window.currentFbo.height = CORE.Window.screen.height;
ClearBackground(RAYWHITE); // Default background color for raylib games :P
#if defined(PLATFORM_ANDROID)
CORE.Window.ready = true;
#endif
return true;
}
// Set viewport for a provided width and height
static void SetupViewport(int width, int height)
{
CORE.Window.render.width = width;
CORE.Window.render.height = height;
// Set viewport width and height
// NOTE: We consider render size and offset in case black bars are required and
// render area does not match full display area (this situation is only applicable on fullscreen mode)
rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, CORE.Window.render.width - CORE.Window.renderOffset.x, CORE.Window.render.height - CORE.Window.renderOffset.y);
rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix
rlLoadIdentity(); // Reset current matrix (PROJECTION)
// Set orthographic projection to current framebuffer size
// NOTE: Configured top-left corner as (0, 0)
rlOrtho(0, CORE.Window.render.width, CORE.Window.render.height, 0, 0.0f, 1.0f);
rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
}
// Compute framebuffer size relative to screen size and display size
// NOTE: Global variables CORE.Window.render.width/CORE.Window.render.height and CORE.Window.renderOffset.x/CORE.Window.renderOffset.y can be modified
static void SetupFramebuffer(int width, int height)
{
// Calculate CORE.Window.render.width and CORE.Window.render.height, we have the display size (input params) and the desired screen size (global var)
if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
{
TRACELOG(LOG_WARNING, "DISPLAY: Downscaling required: Screen size (%ix%i) is bigger than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
// Downscaling to fit display with border-bars
float widthRatio = (float)CORE.Window.display.width/(float)CORE.Window.screen.width;
float heightRatio = (float)CORE.Window.display.height/(float)CORE.Window.screen.height;
if (widthRatio <= heightRatio)
{
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.height*widthRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.display.height - CORE.Window.render.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.width*heightRatio);
CORE.Window.render.height = CORE.Window.display.height;
CORE.Window.renderOffset.x = (CORE.Window.display.width - CORE.Window.render.width);
CORE.Window.renderOffset.y = 0;
}
// Screen scaling required
float scaleRatio = (float)CORE.Window.render.width/(float)CORE.Window.screen.width;
CORE.Window.screenScale = MatrixScale(scaleRatio, scaleRatio, 1.0f);
// NOTE: We render to full display resolution!
// We just need to calculate above parameters for downscale matrix and offsets
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = CORE.Window.display.height;
TRACELOG(LOG_WARNING, "DISPLAY: Downscale matrix generated, content will be rendered at (%ix%i)", CORE.Window.render.width, CORE.Window.render.height);
}
else if ((CORE.Window.screen.width < CORE.Window.display.width) || (CORE.Window.screen.height < CORE.Window.display.height))
{
// Required screen size is smaller than display size
TRACELOG(LOG_INFO, "DISPLAY: Upscaling required: Screen size (%ix%i) smaller than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
// Upscaling to fit display with border-bars
float displayRatio = (float)CORE.Window.display.width/(float)CORE.Window.display.height;
float screenRatio = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
if (displayRatio <= screenRatio)
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.width/displayRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.render.height - CORE.Window.screen.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.height*displayRatio);
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = (CORE.Window.render.width - CORE.Window.screen.width);
CORE.Window.renderOffset.y = 0;
}
}
else
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = 0;
}
}
// Initialize hi-resolution timer
static void InitTimer(void)
{
srand((unsigned int)time(NULL)); // Initialize random seed
#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32)
timeBeginPeriod(1); // Setup high-resolution timer to 1ms (granularity of 1-2 ms)
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI)
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) // Success
{
CORE.Time.base = (unsigned long long int)now.tv_sec*1000000000LLU + (unsigned long long int)now.tv_nsec;
}
else TRACELOG(LOG_WARNING, "TIMER: Hi-resolution timer not available");
#endif
CORE.Time.previous = GetTime(); // Get time as double
}
// Wait for some milliseconds (stop program execution)
// NOTE: Sleep() granularity could be around 10 ms, it means, Sleep() could
// take longer than expected... for that reason we use the busy wait loop
// Ref: http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected
// Ref: http://www.geisswerks.com/ryan/FAQS/timing.html --> All about timming on Win32!
static void Wait(float ms)
{
#if defined(SUPPORT_BUSY_WAIT_LOOP) && !defined(PLATFORM_UWP)
double prevTime = GetTime();
double nextTime = 0.0;
// Busy wait loop
while ((nextTime - prevTime) < ms/1000.0f) nextTime = GetTime();
#else
#if defined(SUPPORT_HALFBUSY_WAIT_LOOP)
#define MAX_HALFBUSY_WAIT_TIME 4
double destTime = GetTime() + ms/1000;
if (ms > MAX_HALFBUSY_WAIT_TIME) ms -= MAX_HALFBUSY_WAIT_TIME;
#endif
#if defined(_WIN32)
Sleep((unsigned int)ms);
#elif defined(__linux__) || defined(PLATFORM_WEB)
struct timespec req = { 0 };
time_t sec = (int)(ms/1000.0f);
ms -= (sec*1000);
req.tv_sec = sec;
req.tv_nsec = ms*1000000L;
// NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated.
while (nanosleep(&req, &req) == -1) continue;
#elif defined(__APPLE__)
usleep(ms*1000.0f);
#endif
#if defined(SUPPORT_HALFBUSY_WAIT_LOOP)
while (GetTime() < destTime) { }
#endif
#endif
}
// Get gamepad button generic to all platforms
static int GetGamepadButton(int button)
{
int btn = GAMEPAD_BUTTON_UNKNOWN;
#if defined(PLATFORM_DESKTOP)
switch (button)
{
case GLFW_GAMEPAD_BUTTON_Y: btn = GAMEPAD_BUTTON_RIGHT_FACE_UP; break;
case GLFW_GAMEPAD_BUTTON_B: btn = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break;
case GLFW_GAMEPAD_BUTTON_A: btn = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break;
case GLFW_GAMEPAD_BUTTON_X: btn = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break;
case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break;
case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break;
case GLFW_GAMEPAD_BUTTON_BACK: btn = GAMEPAD_BUTTON_MIDDLE_LEFT; break;
case GLFW_GAMEPAD_BUTTON_GUIDE: btn = GAMEPAD_BUTTON_MIDDLE; break;
case GLFW_GAMEPAD_BUTTON_START: btn = GAMEPAD_BUTTON_MIDDLE_RIGHT; break;
case GLFW_GAMEPAD_BUTTON_DPAD_UP: btn = GAMEPAD_BUTTON_LEFT_FACE_UP; break;
case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: btn = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break;
case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: btn = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break;
case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: btn = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break;
case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: btn = GAMEPAD_BUTTON_LEFT_THUMB; break;
case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: btn = GAMEPAD_BUTTON_RIGHT_THUMB; break;
}
#endif
#if defined(PLATFORM_UWP)
btn = button; // UWP will provide the correct button
#endif
#if defined(PLATFORM_WEB)
// Gamepad Buttons reference: https://www.w3.org/TR/gamepad/#gamepad-interface
switch (button)
{
case 0: btn = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break;
case 1: btn = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break;
case 2: btn = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break;
case 3: btn = GAMEPAD_BUTTON_RIGHT_FACE_UP; break;
case 4: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break;
case 5: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break;
case 6: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break;
case 7: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break;
case 8: btn = GAMEPAD_BUTTON_MIDDLE_LEFT; break;
case 9: btn = GAMEPAD_BUTTON_MIDDLE_RIGHT; break;
case 10: btn = GAMEPAD_BUTTON_LEFT_THUMB; break;
case 11: btn = GAMEPAD_BUTTON_RIGHT_THUMB; break;
case 12: btn = GAMEPAD_BUTTON_LEFT_FACE_UP; break;
case 13: btn = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break;
case 14: btn = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break;
case 15: btn = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break;
}
#endif
return btn;
}
// Get gamepad axis generic to all platforms
static int GetGamepadAxis(int axis)
{
int axs = GAMEPAD_AXIS_UNKNOWN;
#if defined(PLATFORM_DESKTOP)
switch (axis)
{
case GLFW_GAMEPAD_AXIS_LEFT_X: axs = GAMEPAD_AXIS_LEFT_X; break;
case GLFW_GAMEPAD_AXIS_LEFT_Y: axs = GAMEPAD_AXIS_LEFT_Y; break;
case GLFW_GAMEPAD_AXIS_RIGHT_X: axs = GAMEPAD_AXIS_RIGHT_X; break;
case GLFW_GAMEPAD_AXIS_RIGHT_Y: axs = GAMEPAD_AXIS_RIGHT_Y; break;
case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: axs = GAMEPAD_AXIS_LEFT_TRIGGER; break;
case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: axs = GAMEPAD_AXIS_RIGHT_TRIGGER; break;
}
#endif
#if defined(PLATFORM_UWP)
axs = axis; // UWP will provide the correct axis
#endif
#if defined(PLATFORM_WEB)
// Gamepad axis reference:https://www.w3.org/TR/gamepad/#gamepad-interface
switch (axis)
{
case 0: axs = GAMEPAD_AXIS_LEFT_X;
case 1: axs = GAMEPAD_AXIS_LEFT_Y;
case 2: axs = GAMEPAD_AXIS_RIGHT_X;
case 3: axs = GAMEPAD_AXIS_RIGHT_X;
}
#endif
return axs;
}
// Poll (store) all input events
static void PollInputEvents(void)
{
#if defined(SUPPORT_GESTURES_SYSTEM)
// NOTE: Gestures update must be called every frame to reset gestures correctly
// because ProcessGestureEvent() is just called on an event, not every frame
UpdateGestures();
#endif
// Reset key pressed registered
CORE.Input.Keyboard.keyPressedQueueCount = 0;
#if !defined(PLATFORM_RPI)
// Reset last gamepad button/axis registered state
CORE.Input.Gamepad.lastButtonPressed = -1;
CORE.Input.Gamepad.axisCount = 0;
#endif
#if defined(PLATFORM_RPI)
// Register previous keys states
for (int i = 0; i < 512; i++) CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
// Grab a keypress from the evdev fifo if avalable
if (CORE.Input.Keyboard.lastKeyPressed.head != CORE.Input.Keyboard.lastKeyPressed.tail)
{
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = CORE.Input.Keyboard.lastKeyPressed.contents[CORE.Input.Keyboard.lastKeyPressed.tail]; // Read the key from the buffer
CORE.Input.Keyboard.keyPressedQueueCount++;
CORE.Input.Keyboard.lastKeyPressed.tail = (CORE.Input.Keyboard.lastKeyPressed.tail + 1) & 0x07; // Increment the tail pointer forwards and binary wraparound after 7 (fifo is 8 elements long)
}
// Register previous mouse states
CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
CORE.Input.Mouse.currentWheelMove = 0;
for (int i = 0; i < 3; i++)
{
CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
CORE.Input.Mouse.currentButtonState[i] = CORE.Input.Mouse.currentButtonStateEvdev[i];
}
#endif
#if defined(PLATFORM_UWP)
// Register previous keys states
for (int i = 0; i < 512; i++) CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
for (int i = 0; i < MAX_GAMEPADS; i++)
{
if (CORE.Input.Gamepad.ready[i])
{
for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousState[i][k] = CORE.Input.Gamepad.currentState[i][k];
}
}
// Register previous mouse states
CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
CORE.Input.Mouse.currentWheelMove = 0;
for (int i = 0; i < 3; i++) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
// Loop over pending messages
while (HasMessageFromUWP())
{
UWPMessage *msg = GetMessageFromUWP();
switch (msg->type)
{
case UWP_MSG_REGISTER_KEY:
{
// Convert from virtualKey
int actualKey = -1;
switch (msg->paramInt0)
{
case 0x08: actualKey = KEY_BACKSPACE; break;
case 0x20: actualKey = KEY_SPACE; break;
case 0x1B: actualKey = KEY_ESCAPE; break;
case 0x0D: actualKey = KEY_ENTER; break;
case 0x2E: actualKey = KEY_DELETE; break;
case 0x27: actualKey = KEY_RIGHT; break;
case 0x25: actualKey = KEY_LEFT; break;
case 0x28: actualKey = KEY_DOWN; break;
case 0x26: actualKey = KEY_UP; break;
case 0x70: actualKey = KEY_F1; break;
case 0x71: actualKey = KEY_F2; break;
case 0x72: actualKey = KEY_F3; break;
case 0x73: actualKey = KEY_F4; break;
case 0x74: actualKey = KEY_F5; break;
case 0x75: actualKey = KEY_F6; break;
case 0x76: actualKey = KEY_F7; break;
case 0x77: actualKey = KEY_F8; break;
case 0x78: actualKey = KEY_F9; break;
case 0x79: actualKey = KEY_F10; break;
case 0x7A: actualKey = KEY_F11; break;
case 0x7B: actualKey = KEY_F12; break;
case 0xA0: actualKey = KEY_LEFT_SHIFT; break;
case 0xA2: actualKey = KEY_LEFT_CONTROL; break;
case 0xA4: actualKey = KEY_LEFT_ALT; break;
case 0xA1: actualKey = KEY_RIGHT_SHIFT; break;
case 0xA3: actualKey = KEY_RIGHT_CONTROL; break;
case 0xA5: actualKey = KEY_RIGHT_ALT; break;
case 0x30: actualKey = KEY_ZERO; break;
case 0x31: actualKey = KEY_ONE; break;
case 0x32: actualKey = KEY_TWO; break;
case 0x33: actualKey = KEY_THREE; break;
case 0x34: actualKey = KEY_FOUR; break;
case 0x35: actualKey = KEY_FIVE; break;
case 0x36: actualKey = KEY_SIX; break;
case 0x37: actualKey = KEY_SEVEN; break;
case 0x38: actualKey = KEY_EIGHT; break;
case 0x39: actualKey = KEY_NINE; break;
case 0x41: actualKey = KEY_A; break;
case 0x42: actualKey = KEY_B; break;
case 0x43: actualKey = KEY_C; break;
case 0x44: actualKey = KEY_D; break;
case 0x45: actualKey = KEY_E; break;
case 0x46: actualKey = KEY_F; break;
case 0x47: actualKey = KEY_G; break;
case 0x48: actualKey = KEY_H; break;
case 0x49: actualKey = KEY_I; break;
case 0x4A: actualKey = KEY_J; break;
case 0x4B: actualKey = KEY_K; break;
case 0x4C: actualKey = KEY_L; break;
case 0x4D: actualKey = KEY_M; break;
case 0x4E: actualKey = KEY_N; break;
case 0x4F: actualKey = KEY_O; break;
case 0x50: actualKey = KEY_P; break;
case 0x51: actualKey = KEY_Q; break;
case 0x52: actualKey = KEY_R; break;
case 0x53: actualKey = KEY_S; break;
case 0x54: actualKey = KEY_T; break;
case 0x55: actualKey = KEY_U; break;
case 0x56: actualKey = KEY_V; break;
case 0x57: actualKey = KEY_W; break;
case 0x58: actualKey = KEY_X; break;
case 0x59: actualKey = KEY_Y; break;
case 0x5A: actualKey = KEY_Z; break;
default: break;
}
if (actualKey > -1) CORE.Input.Keyboard.currentKeyState[actualKey] = msg->paramChar0;
} break;
case UWP_MSG_REGISTER_CLICK: CORE.Input.Mouse.currentButtonState[msg->paramInt0] = msg->paramChar0; break;
case UWP_MSG_SCROLL_WHEEL_UPDATE: CORE.Input.Mouse.currentWheelMove += msg->paramInt0; break;
case UWP_MSG_UPDATE_MOUSE_LOCATION: CORE.Input.Mouse.position = msg->paramVector0; break;
case UWP_MSG_SET_GAMEPAD_ACTIVE: if (msg->paramInt0 < MAX_GAMEPADS) CORE.Input.Gamepad.ready[msg->paramInt0] = msg->paramBool0; break;
case UWP_MSG_SET_GAMEPAD_BUTTON:
{
if ((msg->paramInt0 < MAX_GAMEPADS) && (msg->paramInt1 < MAX_GAMEPAD_BUTTONS)) CORE.Input.Gamepad.currentState[msg->paramInt0][msg->paramInt1] = msg->paramChar0;
} break;
case UWP_MSG_SET_GAMEPAD_AXIS:
{
if ((msg->paramInt0 < MAX_GAMEPADS) && (msg->paramInt1 < MAX_GAMEPAD_AXIS)) CORE.Input.Gamepad.axisState[msg->paramInt0][msg->paramInt1] = msg->paramFloat0;
// Register buttons for 2nd triggers
CORE.Input.Gamepad.currentState[msg->paramInt0][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[msg->paramInt0][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1);
CORE.Input.Gamepad.currentState[msg->paramInt0][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[msg->paramInt0][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1);
} break;
case UWP_MSG_SET_DISPLAY_DIMS:
{
CORE.Window.display.width = msg->paramVector0.x;
CORE.Window.display.height = msg->paramVector0.y;
} break;
case UWP_MSG_HANDLE_RESIZE:
{
eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_WIDTH, &CORE.Window.screen.width);
eglQuerySurface(CORE.Window.device, CORE.Window.surface, EGL_HEIGHT, &CORE.Window.screen.height);
// If window is resized, viewport and projection matrix needs to be re-calculated
rlViewport(0, 0, CORE.Window.screen.width, CORE.Window.screen.height); // Set viewport width and height
rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix
rlLoadIdentity(); // Reset current matrix (PROJECTION)
rlOrtho(0, CORE.Window.screen.width, CORE.Window.screen.height, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0)
rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlClearScreenBuffers(); // Clear screen buffers (color and depth)
// Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D())
// NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor,
// for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported)
CORE.Window.currentFbo.width = CORE.Window.screen.width;
CORE.Window.currentFbo.height = CORE.Window.screen.height;
// NOTE: Postprocessing texture is not scaled to new size
CORE.Window.resized = true;
} break;
case UWP_MSG_SET_GAME_TIME: CORE.Time.current = msg->paramDouble0; break;
default: break;
}
DeleteUWPMessage(msg); //Delete, we are done
}
#endif // PLATFORM_UWP
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
// Keyboard/Mouse input polling (automatically managed by GLFW3 through callback)
// Register previous keys states
for (int i = 0; i < 512; i++) CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
// Register previous mouse states
for (int i = 0; i < 3; i++) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
// Register previous mouse wheel state
CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
CORE.Input.Mouse.currentWheelMove = 0;
#endif
// Register previous touch states
for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
#if defined(PLATFORM_DESKTOP)
// Check if gamepads are ready
// NOTE: We do it here in case of disconnection
for (int i = 0; i < MAX_GAMEPADS; i++)
{
if (glfwJoystickPresent(i)) CORE.Input.Gamepad.ready[i] = true;
else CORE.Input.Gamepad.ready[i] = false;
}
// Register gamepads buttons events
for (int i = 0; i < MAX_GAMEPADS; i++)
{
if (CORE.Input.Gamepad.ready[i]) // Check if gamepad is available
{
// Register previous gamepad states
for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousState[i][k] = CORE.Input.Gamepad.currentState[i][k];
// Get current gamepad state
// NOTE: There is no callback available, so we get it manually
// Get remapped buttons
GLFWgamepadstate state;
glfwGetGamepadState(i, &state); // This remapps all gamepads so they have their buttons mapped like an xbox controller
const unsigned char *buttons = state.buttons;
for (int k = 0; (buttons != NULL) && (k < GLFW_GAMEPAD_BUTTON_DPAD_LEFT + 1) && (k < MAX_GAMEPAD_BUTTONS); k++)
{
const GamepadButton button = GetGamepadButton(k);
if (buttons[k] == GLFW_PRESS)
{
CORE.Input.Gamepad.currentState[i][button] = 1;
CORE.Input.Gamepad.lastButtonPressed = button;
}
else CORE.Input.Gamepad.currentState[i][button] = 0;
}
// Get current axis state
const float *axes = state.axes;
for (int k = 0; (axes != NULL) && (k < GLFW_GAMEPAD_AXIS_LAST + 1) && (k < MAX_GAMEPAD_AXIS); k++)
{
const int axis = GetGamepadAxis(k);
CORE.Input.Gamepad.axisState[i][axis] = axes[k];
}
// Register buttons for 2nd triggers (because GLFW doesn't count these as buttons but rather axis)
CORE.Input.Gamepad.currentState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1);
CORE.Input.Gamepad.currentState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1);
CORE.Input.Gamepad.axisCount = GLFW_GAMEPAD_AXIS_LAST;
}
}
CORE.Window.resized = false;
#if defined(SUPPORT_EVENTS_WAITING)
glfwWaitEvents();
#else
glfwPollEvents(); // Register keyboard/mouse events (callbacks)... and window events!
#endif
#endif //defined(PLATFORM_DESKTOP)
// Gamepad support using emscripten API
// NOTE: GLFW3 joystick functionality not available in web
#if defined(PLATFORM_WEB)
// Get number of gamepads connected
int numGamepads = 0;
if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS) numGamepads = emscripten_get_num_gamepads();
for (int i = 0; (i < numGamepads) && (i < MAX_GAMEPADS); i++)
{
// Register previous gamepad button states
for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousState[i][k] = CORE.Input.Gamepad.currentState[i][k];
EmscriptenGamepadEvent gamepadState;
int result = emscripten_get_gamepad_status(i, &gamepadState);
if (result == EMSCRIPTEN_RESULT_SUCCESS)
{
// Register buttons data for every connected gamepad
for (int j = 0; (j < gamepadState.numButtons) && (j < MAX_GAMEPAD_BUTTONS); j++)
{
const GamepadButton button = GetGamepadButton(j);
if (gamepadState.digitalButton[j] == 1)
{
CORE.Input.Gamepad.currentState[i][button] = 1;
CORE.Input.Gamepad.lastButtonPressed = button;
}
else CORE.Input.Gamepad.currentState[i][button] = 0;
//TRACELOGD("INPUT: Gamepad %d, button %d: Digital: %d, Analog: %g", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]);
}
// Register axis data for every connected gamepad
for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++)
{
const int axis = GetGamepadAxis(j);
CORE.Input.Gamepad.axisState[i][axis] = gamepadState.axis[j];
}
CORE.Input.Gamepad.axisCount = gamepadState.numAxes;
}
}
#endif
#if defined(PLATFORM_ANDROID)
// Register previous keys states
// NOTE: Android supports up to 260 keys
for (int i = 0; i < 260; i++) CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
// Android ALooper_pollAll() variables
int pollResult = 0;
int pollEvents = 0;
// Poll Events (registered events)
// NOTE: Activity is paused if not enabled (CORE.Android.appEnabled)
while ((pollResult = ALooper_pollAll(CORE.Android.appEnabled? 0 : -1, NULL, &pollEvents, (void**)&CORE.Android.source)) >= 0)
{
// Process this event
if (CORE.Android.source != NULL) CORE.Android.source->process(CORE.Android.app, CORE.Android.source);
// NOTE: Never close window, native activity is controlled by the system!
if (CORE.Android.app->destroyRequested != 0)
{
//CORE.Window.shouldClose = true;
//ANativeActivity_finish(CORE.Android.app->activity);
}
}
#endif
#if defined(PLATFORM_RPI) && defined(SUPPORT_SSH_KEYBOARD_RPI)
// NOTE: Keyboard reading could be done using input_event(s) reading or just read from stdin,
// we now use both methods inside here. 2nd method is still used for legacy purposes (Allows for input trough SSH console)
ProcessKeyboard();
// NOTE: Mouse input events polling is done asynchronously in another pthread - EventThread()
// NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread()
#endif
}
// Copy back buffer to front buffers
static void SwapBuffers(void)
{
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
glfwSwapBuffers(CORE.Window.handle);
#endif
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP)
eglSwapBuffers(CORE.Window.device, CORE.Window.surface);
#endif
}
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
// GLFW3 Error Callback, runs on GLFW3 error
static void ErrorCallback(int error, const char *description)
{
TRACELOG(LOG_WARNING, "GLFW: Error: %i Description: %s", error, description);
}
// GLFW3 Srolling Callback, runs on mouse wheel
static void ScrollCallback(GLFWwindow *window, double xoffset, double yoffset)
{
CORE.Input.Mouse.currentWheelMove = (int)yoffset;
}
// GLFW3 Keyboard Callback, runs on key pressed
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (key == CORE.Input.Keyboard.exitKey && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(CORE.Window.handle, GLFW_TRUE);
// NOTE: Before closing window, while loop must be left!
}
else if (key == GLFW_KEY_F12 && action == GLFW_PRESS)
{
#if defined(SUPPORT_GIF_RECORDING)
if (mods == GLFW_MOD_CONTROL)
{
if (gifRecording)
{
GifEnd();
gifRecording = false;
#if defined(PLATFORM_WEB)
// Download file from MEMFS (emscripten memory filesystem)
// saveFileFromMEMFSToDisk() function is defined in raylib/templates/web_shel/shell.html
emscripten_run_script(TextFormat("saveFileFromMEMFSToDisk('%s','%s')", TextFormat("screenrec%03i.gif", screenshotCounter - 1), TextFormat("screenrec%03i.gif", screenshotCounter - 1)));
#endif
TRACELOG(LOG_INFO, "SYSTEM: Finish animated GIF recording");
}
else
{
gifRecording = true;
gifFramesCounter = 0;
char path[512] = { 0 };
#if defined(PLATFORM_ANDROID)
strcpy(path, CORE.Android.internalDataPath);
strcat(path, TextFormat("./screenrec%03i.gif", screenshotCounter));
#else
strcpy(path, TextFormat("./screenrec%03i.gif", screenshotCounter));
#endif
// NOTE: delay represents the time between frames in the gif, if we capture a gif frame every
// 10 game frames and each frame trakes 16.6ms (60fps), delay between gif frames should be ~16.6*10.
GifBegin(path, CORE.Window.screen.width, CORE.Window.screen.height, (int)(GetFrameTime()*10.0f), 8, false);
screenshotCounter++;
TRACELOG(LOG_INFO, "SYSTEM: Start animated GIF recording: %s", TextFormat("screenrec%03i.gif", screenshotCounter));
}
}
else
#endif // SUPPORT_GIF_RECORDING
#if defined(SUPPORT_SCREEN_CAPTURE)
{
TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter));
screenshotCounter++;
}
#endif // SUPPORT_SCREEN_CAPTURE
}
else
{
// WARNING: GLFW could return GLFW_REPEAT, we need to consider it as 1
// to work properly with our implementation (IsKeyDown/IsKeyUp checks)
if (action == GLFW_RELEASE) CORE.Input.Keyboard.currentKeyState[key] = 0;
else CORE.Input.Keyboard.currentKeyState[key] = 1;
}
}
// GLFW3 Mouse Button Callback, runs on mouse button pressed
static void MouseButtonCallback(GLFWwindow *window, int button, int action, int mods)
{
// WARNING: GLFW could only return GLFW_PRESS (1) or GLFW_RELEASE (0) for now,
// but future releases may add more actions (i.e. GLFW_REPEAT)
CORE.Input.Mouse.currentButtonState[button] = action;
#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES)
// Process mouse events as touches to be able to use mouse-gestures
GestureEvent gestureEvent = { 0 };
// Register touch actions
if ((CORE.Input.Mouse.currentButtonState[button] == 1) && (CORE.Input.Mouse.previousButtonState[button] == 0)) gestureEvent.touchAction = TOUCH_DOWN;
else if ((CORE.Input.Mouse.currentButtonState[button] == 0) && (CORE.Input.Mouse.previousButtonState[button] == 1)) gestureEvent.touchAction = TOUCH_UP;
// NOTE: TOUCH_MOVE event is registered in MouseCursorPosCallback()
// Assign a pointer ID
gestureEvent.pointerId[0] = 0;
// Register touch points count
gestureEvent.pointCount = 1;
// Register touch points position, only one point registered
gestureEvent.position[0] = GetMousePosition();
// Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height
gestureEvent.position[0].x /= (float)GetScreenWidth();
gestureEvent.position[0].y /= (float)GetScreenHeight();
// Gesture data is sent to gestures system for processing
ProcessGestureEvent(gestureEvent);
#endif
}
// GLFW3 Cursor Position Callback, runs on mouse move
static void MouseCursorPosCallback(GLFWwindow *window, double x, double y)
{
CORE.Input.Mouse.position.x = (float)x;
CORE.Input.Mouse.position.y = (float)y;
CORE.Input.Touch.position[0] = CORE.Input.Mouse.position;
#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES)
// Process mouse events as touches to be able to use mouse-gestures
GestureEvent gestureEvent = { 0 };
gestureEvent.touchAction = TOUCH_MOVE;
// Assign a pointer ID
gestureEvent.pointerId[0] = 0;
// Register touch points count
gestureEvent.pointCount = 1;
// Register touch points position, only one point registered
gestureEvent.position[0] = CORE.Input.Touch.position[0];
// Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height
gestureEvent.position[0].x /= (float)GetScreenWidth();
gestureEvent.position[0].y /= (float)GetScreenHeight();
// Gesture data is sent to gestures system for processing
ProcessGestureEvent(gestureEvent);
#endif
}
// GLFW3 Char Key Callback, runs on key down (get unicode char value)
static void CharCallback(GLFWwindow *window, unsigned int key)
{
// NOTE: Registers any key down considering OS keyboard layout but
// do not detects action events, those should be managed by user...
// Ref: https://github.com/glfw/glfw/issues/668#issuecomment-166794907
// Ref: https://www.glfw.org/docs/latest/input_guide.html#input_char
// Check if there is space available in the queue
if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_CHARS_QUEUE)
{
// Add character to the queue
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = key;
CORE.Input.Keyboard.keyPressedQueueCount++;
}
}
// GLFW3 CursorEnter Callback, when cursor enters the window
static void CursorEnterCallback(GLFWwindow *window, int enter)
{
if (enter == true) CORE.Input.Mouse.cursorOnScreen = true;
else CORE.Input.Mouse.cursorOnScreen = false;
}
// GLFW3 WindowSize Callback, runs when window is resized
// NOTE: Window resizing not allowed by default
static void WindowSizeCallback(GLFWwindow *window, int width, int height)
{
SetupViewport(width, height); // Reset viewport and projection matrix for new size
// Set current screen size
CORE.Window.screen.width = width;
CORE.Window.screen.height = height;
CORE.Window.currentFbo.width = width;
CORE.Window.currentFbo.height = height;
// NOTE: Postprocessing texture is not scaled to new size
CORE.Window.resized = true;
}
// GLFW3 WindowIconify Callback, runs when window is minimized/restored
static void WindowIconifyCallback(GLFWwindow *window, int iconified)
{
if (iconified) CORE.Window.minimized = true; // The window was iconified
else CORE.Window.minimized = false; // The window was restored
}
// GLFW3 Window Drop Callback, runs when drop files into window
// NOTE: Paths are stored in dynamic memory for further retrieval
// Everytime new files are dropped, old ones are discarded
static void WindowDropCallback(GLFWwindow *window, int count, const char **paths)
{
ClearDroppedFiles();
CORE.Window.dropFilesPath = (char **)RL_MALLOC(sizeof(char *)*count);
for (int i = 0; i < count; i++)
{
CORE.Window.dropFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
strcpy(CORE.Window.dropFilesPath[i], paths[i]);
}
CORE.Window.dropFilesCount = count;
}
#endif
#if defined(PLATFORM_ANDROID)
// ANDROID: Process activity lifecycle commands
static void AndroidCommandCallback(struct android_app *app, int32_t cmd)
{
switch (cmd)
{
case APP_CMD_START:
{
//rendering = true;
} break;
case APP_CMD_RESUME: break;
case APP_CMD_INIT_WINDOW:
{
if (app->window != NULL)
{
if (CORE.Android.contextRebindRequired)
{
// Reset screen scaling to full display size
EGLint displayFormat;
eglGetConfigAttrib(CORE.Window.device, CORE.Window.config, EGL_NATIVE_VISUAL_ID, &displayFormat);
ANativeWindow_setBuffersGeometry(app->window, CORE.Window.render.width, CORE.Window.render.height, displayFormat);
// Recreate display surface and re-attach OpenGL context
CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, app->window, NULL);
eglMakeCurrent(CORE.Window.device, CORE.Window.surface, CORE.Window.surface, CORE.Window.context);
CORE.Android.contextRebindRequired = false;
}
else
{
CORE.Window.display.width = ANativeWindow_getWidth(CORE.Android.app->window);
CORE.Window.display.height = ANativeWindow_getHeight(CORE.Android.app->window);
// Init graphics device (display device and OpenGL context)
InitGraphicsDevice(CORE.Window.screen.width, CORE.Window.screen.height);
// Init hi-res timer
InitTimer();
#if defined(SUPPORT_DEFAULT_FONT)
// Load default font
// NOTE: External function (defined in module: text)
LoadFontDefault();
Rectangle rec = GetFontDefault().recs[95];
// NOTE: We setup a 1px padding on char rectangle to avoid pixel bleeding on MSAA filtering
SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 1, rec.y + 1, rec.width - 2, rec.height - 2 });
#endif
// TODO: GPU assets reload in case of lost focus (lost context)
// NOTE: This problem has been solved just unbinding and rebinding context from display
/*
if (assetsReloadRequired)
{
for (int i = 0; i < assetsCount; i++)
{
// TODO: Unload old asset if required
// Load texture again to pointed texture
(*textureAsset + i) = LoadTexture(assetPath[i]);
}
}
*/
}
}
} break;
case APP_CMD_GAINED_FOCUS:
{
CORE.Android.appEnabled = true;
//ResumeMusicStream();
} break;
case APP_CMD_PAUSE: break;
case APP_CMD_LOST_FOCUS:
{
CORE.Android.appEnabled = false;
//PauseMusicStream();
} break;
case APP_CMD_TERM_WINDOW:
{
// Dettach OpenGL context and destroy display surface
// NOTE 1: Detaching context before destroying display surface avoids losing our resources (textures, shaders, VBOs...)
// NOTE 2: In some cases (too many context loaded), OS could unload context automatically... :(
eglMakeCurrent(CORE.Window.device, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroySurface(CORE.Window.device, CORE.Window.surface);
CORE.Android.contextRebindRequired = true;
} break;
case APP_CMD_SAVE_STATE: break;
case APP_CMD_STOP: break;
case APP_CMD_DESTROY:
{
// TODO: Finish activity?
//ANativeActivity_finish(CORE.Android.app->activity);
} break;
case APP_CMD_CONFIG_CHANGED:
{
//AConfiguration_fromAssetManager(CORE.Android.app->config, CORE.Android.app->activity->assetManager);
//print_cur_config(CORE.Android.app);
// Check screen orientation here!
} break;
default: break;
}
}
// ANDROID: Get input events
static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event)
{
// If additional inputs are required check:
// https://developer.android.com/ndk/reference/group/input
// https://developer.android.com/training/game-controllers/controller-input
int type = AInputEvent_getType(event);
int source = AInputEvent_getSource(event);
if (type == AINPUT_EVENT_TYPE_MOTION)
{
if ((source & AINPUT_SOURCE_JOYSTICK) == AINPUT_SOURCE_JOYSTICK || (source & AINPUT_SOURCE_GAMEPAD) == AINPUT_SOURCE_GAMEPAD)
{
// Get first touch position
CORE.Input.Touch.position[0].x = AMotionEvent_getX(event, 0);
CORE.Input.Touch.position[0].y = AMotionEvent_getY(event, 0);
// Get second touch position
CORE.Input.Touch.position[1].x = AMotionEvent_getX(event, 1);
CORE.Input.Touch.position[1].y = AMotionEvent_getY(event, 1);
int32_t keycode = AKeyEvent_getKeyCode(event);
if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN)
{
CORE.Input.Keyboard.currentKeyState[keycode] = 1; // Key down
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode;
CORE.Input.Keyboard.keyPressedQueueCount++;
}
else CORE.Input.Keyboard.currentKeyState[keycode] = 0; // Key up
// Stop processing gamepad buttons
return 1;
}
}
else if (type == AINPUT_EVENT_TYPE_KEY)
{
int32_t keycode = AKeyEvent_getKeyCode(event);
//int32_t AKeyEvent_getMetaState(event);
// Save current button and its state
// NOTE: Android key action is 0 for down and 1 for up
if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN)
{
CORE.Input.Keyboard.currentKeyState[keycode] = 1; // Key down
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode;
CORE.Input.Keyboard.keyPressedQueueCount++;
}
else CORE.Input.Keyboard.currentKeyState[keycode] = 0; // Key up
if (keycode == AKEYCODE_POWER)
{
// Let the OS handle input to avoid app stuck. Behaviour: CMD_PAUSE -> CMD_SAVE_STATE -> CMD_STOP -> CMD_CONFIG_CHANGED -> CMD_LOST_FOCUS
// Resuming Behaviour: CMD_START -> CMD_RESUME -> CMD_CONFIG_CHANGED -> CMD_CONFIG_CHANGED -> CMD_GAINED_FOCUS
// It seems like locking mobile, screen size (CMD_CONFIG_CHANGED) is affected.
// NOTE: AndroidManifest.xml must have <activity android:configChanges="orientation|keyboardHidden|screenSize" >
// Before that change, activity was calling CMD_TERM_WINDOW and CMD_DESTROY when locking mobile, so that was not a normal behaviour
return 0;
}
else if ((keycode == AKEYCODE_BACK) || (keycode == AKEYCODE_MENU))
{
// Eat BACK_BUTTON and AKEYCODE_MENU, just do nothing... and don't let to be handled by OS!
return 1;
}
else if ((keycode == AKEYCODE_VOLUME_UP) || (keycode == AKEYCODE_VOLUME_DOWN))
{
// Set default OS behaviour
return 0;
}
return 0;
}
CORE.Input.Touch.position[0].x = AMotionEvent_getX(event, 0);
CORE.Input.Touch.position[0].y = AMotionEvent_getY(event, 0);
int32_t action = AMotionEvent_getAction(event);
unsigned int flags = action & AMOTION_EVENT_ACTION_MASK;
if (flags == AMOTION_EVENT_ACTION_DOWN || flags == AMOTION_EVENT_ACTION_MOVE)
{
CORE.Input.Touch.currentTouchState[MOUSE_LEFT_BUTTON] = 1;
}
else if (flags == AMOTION_EVENT_ACTION_UP)
{
CORE.Input.Touch.currentTouchState[MOUSE_LEFT_BUTTON] = 0;
}
#if defined(SUPPORT_GESTURES_SYSTEM)
GestureEvent gestureEvent;
// Register touch actions
if (flags == AMOTION_EVENT_ACTION_DOWN) gestureEvent.touchAction = TOUCH_DOWN;
else if (flags == AMOTION_EVENT_ACTION_UP) gestureEvent.touchAction = TOUCH_UP;
else if (flags == AMOTION_EVENT_ACTION_MOVE) gestureEvent.touchAction = TOUCH_MOVE;
// Register touch points count
// NOTE: Documentation says pointerCount is Always >= 1,
// but in practice it can be 0 or over a million
gestureEvent.pointCount = AMotionEvent_getPointerCount(event);
// Only enable gestures for 1-3 touch points
if ((gestureEvent.pointCount > 0) && (gestureEvent.pointCount < 4))
{
// Register touch points id
// NOTE: Only two points registered
gestureEvent.pointerId[0] = AMotionEvent_getPointerId(event, 0);
gestureEvent.pointerId[1] = AMotionEvent_getPointerId(event, 1);
// Register touch points position
gestureEvent.position[0] = (Vector2){ AMotionEvent_getX(event, 0), AMotionEvent_getY(event, 0) };
gestureEvent.position[1] = (Vector2){ AMotionEvent_getX(event, 1), AMotionEvent_getY(event, 1) };
// Normalize gestureEvent.position[x] for screenWidth and screenHeight
gestureEvent.position[0].x /= (float)GetScreenWidth();
gestureEvent.position[0].y /= (float)GetScreenHeight();
gestureEvent.position[1].x /= (float)GetScreenWidth();
gestureEvent.position[1].y /= (float)GetScreenHeight();
// Gesture data is sent to gestures system for processing
ProcessGestureEvent(gestureEvent);
}
#endif
return 0;
}
#endif
#if defined(PLATFORM_WEB)
// Register fullscreen change events
static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *event, void *userData)
{
//isFullscreen: int event->isFullscreen
//fullscreenEnabled: int event->fullscreenEnabled
//fs element nodeName: (char *) event->nodeName
//fs element id: (char *) event->id
//Current element size: (int) event->elementWidth, (int) event->elementHeight
//Screen size:(int) event->screenWidth, (int) event->screenHeight
if (event->isFullscreen)
{
CORE.Window.fullscreen = true;
TRACELOG(LOG_INFO, "WEB: Canvas scaled to fullscreen. ElementSize: (%ix%i), ScreenSize(%ix%i)", event->elementWidth, event->elementHeight, event->screenWidth, event->screenHeight);
}
else
{
CORE.Window.fullscreen = false;
TRACELOG(LOG_INFO, "WEB: Canvas scaled to windowed. ElementSize: (%ix%i), ScreenSize(%ix%i)", event->elementWidth, event->elementHeight, event->screenWidth, event->screenHeight);
}
// TODO: Depending on scaling factor (screen vs element), calculate factor to scale mouse/touch input
return 0;
}
// Register keyboard input events
static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
{
if ((eventType == EMSCRIPTEN_EVENT_KEYPRESS) && (strcmp(keyEvent->code, "Escape") == 0))
{
emscripten_exit_pointerlock();
}
return 0;
}
// Register mouse input events
static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
{
// Lock mouse pointer when click on screen
if ((eventType == EMSCRIPTEN_EVENT_CLICK) && CORE.Input.Mouse.cursorLockRequired)
{
EmscriptenPointerlockChangeEvent plce;
emscripten_get_pointerlock_status(&plce);
if (!plce.isActive) emscripten_request_pointerlock(0, 1);
else
{
emscripten_exit_pointerlock();
emscripten_get_pointerlock_status(&plce);
//if (plce.isActive) TRACELOG(LOG_WARNING, "Pointer lock exit did not work!");
}
CORE.Input.Mouse.cursorLockRequired = false;
}
return 0;
}
// Register touch input events
static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData)
{
for (int i = 0; i < touchEvent->numTouches; i++)
{
if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) CORE.Input.Touch.currentTouchState[i] = 1;
else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) CORE.Input.Touch.currentTouchState[i] = 0;
}
#if defined(SUPPORT_GESTURES_SYSTEM)
GestureEvent gestureEvent = { 0 };
// Register touch actions
if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) gestureEvent.touchAction = TOUCH_DOWN;
else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) gestureEvent.touchAction = TOUCH_UP;
else if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) gestureEvent.touchAction = TOUCH_MOVE;
// Register touch points count
gestureEvent.pointCount = touchEvent->numTouches;
// Register touch points id
gestureEvent.pointerId[0] = touchEvent->touches[0].identifier;
gestureEvent.pointerId[1] = touchEvent->touches[1].identifier;
// Register touch points position
// NOTE: Only two points registered
gestureEvent.position[0] = (Vector2){ touchEvent->touches[0].targetX, touchEvent->touches[0].targetY };
gestureEvent.position[1] = (Vector2){ touchEvent->touches[1].targetX, touchEvent->touches[1].targetY };
double canvasWidth, canvasHeight;
// NOTE: emscripten_get_canvas_element_size() returns canvas.width and canvas.height but
// we are looking for actual CSS size: canvas.style.width and canvas.style.height
//EMSCRIPTEN_RESULT res = emscripten_get_canvas_element_size("#canvas", &canvasWidth, &canvasHeight);
emscripten_get_element_css_size("#canvas", &canvasWidth, &canvasHeight);
// Normalize gestureEvent.position[x] for CORE.Window.screen.width and CORE.Window.screen.height
gestureEvent.position[0].x *= ((float)GetScreenWidth()/(float)canvasWidth);
gestureEvent.position[0].y *= ((float)GetScreenHeight()/(float)canvasHeight);
gestureEvent.position[1].x *= ((float)GetScreenWidth()/(float)canvasWidth);
gestureEvent.position[1].y *= ((float)GetScreenHeight()/(float)canvasHeight);
CORE.Input.Touch.position[0] = gestureEvent.position[0];
CORE.Input.Touch.position[1] = gestureEvent.position[1];
// Gesture data is sent to gestures system for processing
ProcessGestureEvent(gestureEvent);
#else
// Support only simple touch position
if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART)
{
// Get first touch position
CORE.Input.Touch.position[0] = (Vector2){ touchEvent->touches[0].targetX, touchEvent->touches[0].targetY };
double canvasWidth, canvasHeight;
//EMSCRIPTEN_RESULT res = emscripten_get_canvas_element_size("#canvas", &canvasWidth, &canvasHeight);
emscripten_get_element_css_size("#canvas", &canvasWidth, &canvasHeight);
// Normalize gestureEvent.position[x] for screenWidth and screenHeight
CORE.Input.Touch.position[0].x *= ((float)GetScreenWidth()/(float)canvasWidth);
CORE.Input.Touch.position[0].y *= ((float)GetScreenHeight()/(float)canvasHeight);
}
#endif
return 1;
}
// Register connected/disconnected gamepads events
static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData)
{
/*
TRACELOGD("%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"",
eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state",
gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping);
for (int i = 0; i < gamepadEvent->numAxes; ++i) TRACELOGD("Axis %d: %g", i, gamepadEvent->axis[i]);
for (int i = 0; i < gamepadEvent->numButtons; ++i) TRACELOGD("Button %d: Digital: %d, Analog: %g", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]);
*/
if ((gamepadEvent->connected) && (gamepadEvent->index < MAX_GAMEPADS)) CORE.Input.Gamepad.ready[gamepadEvent->index] = true;
else CORE.Input.Gamepad.ready[gamepadEvent->index] = false;
// TODO: Test gamepadEvent->index
return 0;
}
#endif
#if defined(PLATFORM_RPI)
#if defined(SUPPORT_SSH_KEYBOARD_RPI)
// Initialize Keyboard system (using standard input)
static void InitKeyboard(void)
{
// NOTE: We read directly from Standard Input (stdin) - STDIN_FILENO file descriptor
// Make stdin non-blocking (not enough, need to configure to non-canonical mode)
int flags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified
// Save terminal keyboard settings and reconfigure terminal with new settings
struct termios keyboardNewSettings;
tcgetattr(STDIN_FILENO, &CORE.Input.Keyboard.defaultSettings); // Get current keyboard settings
keyboardNewSettings = CORE.Input.Keyboard.defaultSettings;
// New terminal settings for keyboard: turn off buffering (non-canonical mode), echo and key processing
// NOTE: ISIG controls if ^C and ^Z generate break signals or not
keyboardNewSettings.c_lflag &= ~(ICANON | ECHO | ISIG);
//keyboardNewSettings.c_iflag &= ~(ISTRIP | INLCR | ICRNL | IGNCR | IXON | IXOFF);
keyboardNewSettings.c_cc[VMIN] = 1;
keyboardNewSettings.c_cc[VTIME] = 0;
// Set new keyboard settings (change occurs immediately)
tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings);
// NOTE: Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE
// Save old keyboard mode to restore it at the end
if (ioctl(STDIN_FILENO, KDGKBMODE, &CORE.Input.Keyboard.defaultMode) < 0)
{
// NOTE: It could mean we are using a remote keyboard through ssh!
TRACELOG(LOG_WARNING, "RPI: Failed to change keyboard mode (SSH keyboard?)");
}
else
{
// We reconfigure keyboard mode to get:
// - scancodes (K_RAW)
// - keycodes (K_MEDIUMRAW)
// - ASCII chars (K_XLATE)
// - UNICODE chars (K_UNICODE)
ioctl(STDIN_FILENO, KDSKBMODE, K_XLATE);
}
// Register keyboard restore when program finishes
atexit(RestoreKeyboard);
}
// Process keyboard inputs
// TODO: Most probably input reading and processing should be in a separate thread
static void ProcessKeyboard(void)
{
#define MAX_KEYBUFFER_SIZE 32 // Max size in bytes to read
// Keyboard input polling (fill keys[256] array with status)
int bufferByteCount = 0; // Bytes available on the buffer
char keysBuffer[MAX_KEYBUFFER_SIZE]; // Max keys to be read at a time
// Read availables keycodes from stdin
bufferByteCount = read(STDIN_FILENO, keysBuffer, MAX_KEYBUFFER_SIZE); // POSIX system call
// Reset pressed keys array (it will be filled below)
for (int i = 0; i < 512; i++) CORE.Input.Keyboard.currentKeyState[i] = 0;
// Check keys from event input workers (This is the new keyboard reading method)
//for (int i = 0; i < 512; i++) CORE.Input.Keyboard.currentKeyState[i] = CORE.Input.Keyboard.currentKeyStateEvdev[i];
// Fill all read bytes (looking for keys)
for (int i = 0; i < bufferByteCount; i++)
{
// NOTE: If (key == 0x1b), depending on next key, it could be a special keymap code!
// Up -> 1b 5b 41 / Left -> 1b 5b 44 / Right -> 1b 5b 43 / Down -> 1b 5b 42
if (keysBuffer[i] == 0x1b)
{
// Detect ESC to stop program
if (bufferByteCount == 1) CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] = 1;
else
{
if (keysBuffer[i + 1] == 0x5b) // Special function key
{
if ((keysBuffer[i + 2] == 0x5b) || (keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32))
{
// Process special function keys (F1 - F12)
switch (keysBuffer[i + 3])
{
case 0x41: CORE.Input.Keyboard.currentKeyState[290] = 1; break; // raylib KEY_F1
case 0x42: CORE.Input.Keyboard.currentKeyState[291] = 1; break; // raylib KEY_F2
case 0x43: CORE.Input.Keyboard.currentKeyState[292] = 1; break; // raylib KEY_F3
case 0x44: CORE.Input.Keyboard.currentKeyState[293] = 1; break; // raylib KEY_F4
case 0x45: CORE.Input.Keyboard.currentKeyState[294] = 1; break; // raylib KEY_F5
case 0x37: CORE.Input.Keyboard.currentKeyState[295] = 1; break; // raylib KEY_F6
case 0x38: CORE.Input.Keyboard.currentKeyState[296] = 1; break; // raylib KEY_F7
case 0x39: CORE.Input.Keyboard.currentKeyState[297] = 1; break; // raylib KEY_F8
case 0x30: CORE.Input.Keyboard.currentKeyState[298] = 1; break; // raylib KEY_F9
case 0x31: CORE.Input.Keyboard.currentKeyState[299] = 1; break; // raylib KEY_F10
case 0x33: CORE.Input.Keyboard.currentKeyState[300] = 1; break; // raylib KEY_F11
case 0x34: CORE.Input.Keyboard.currentKeyState[301] = 1; break; // raylib KEY_F12
default: break;
}
if (keysBuffer[i + 2] == 0x5b) i += 4;
else if ((keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32)) i += 5;
}
else
{
switch (keysBuffer[i + 2])
{
case 0x41: CORE.Input.Keyboard.currentKeyState[265] = 1; break; // raylib KEY_UP
case 0x42: CORE.Input.Keyboard.currentKeyState[264] = 1; break; // raylib KEY_DOWN
case 0x43: CORE.Input.Keyboard.currentKeyState[262] = 1; break; // raylib KEY_RIGHT
case 0x44: CORE.Input.Keyboard.currentKeyState[263] = 1; break; // raylib KEY_LEFT
default: break;
}
i += 3; // Jump to next key
}
// NOTE: Some keys are not directly keymapped (CTRL, ALT, SHIFT)
}
}
}
else if (keysBuffer[i] == 0x0a) // raylib KEY_ENTER (don't mix with <linux/input.h> KEY_*)
{
CORE.Input.Keyboard.currentKeyState[257] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 257; // Add keys pressed into queue
CORE.Input.Keyboard.keyPressedQueueCount++;
}
else if (keysBuffer[i] == 0x7f) // raylib KEY_BACKSPACE
{
CORE.Input.Keyboard.currentKeyState[259] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 257; // Add keys pressed into queue
CORE.Input.Keyboard.keyPressedQueueCount++;
}
else
{
// Translate lowercase a-z letters to A-Z
if ((keysBuffer[i] >= 97) && (keysBuffer[i] <= 122))
{
CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i] - 32] = 1;
}
else CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i]] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keysBuffer[i]; // Add keys pressed into queue
CORE.Input.Keyboard.keyPressedQueueCount++;
}
}
// Check exit key (same functionality as GLFW3 KeyCallback())
if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true;
#if defined(SUPPORT_SCREEN_CAPTURE)
// Check screen capture key (raylib key: KEY_F12)
if (CORE.Input.Keyboard.currentKeyState[301] == 1)
{
TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter));
screenshotCounter++;
}
#endif
}
// Restore default keyboard input
static void RestoreKeyboard(void)
{
// Reset to default keyboard settings
tcsetattr(STDIN_FILENO, TCSANOW, &CORE.Input.Keyboard.defaultSettings);
// Reconfigure keyboard to default mode
ioctl(STDIN_FILENO, KDSKBMODE, CORE.Input.Keyboard.defaultMode);
}
#endif //SUPPORT_SSH_KEYBOARD_RPI
// Initialise user input from evdev(/dev/input/event<N>) this means mouse, keyboard or gamepad devices
static void InitEvdevInput(void)
{
char path[MAX_FILEPATH_LENGTH];
DIR *directory;
struct dirent *entity;
// Reset variables
for (int i = 0; i < MAX_TOUCH_POINTS; ++i)
{
CORE.Input.Touch.position[i].x = -1;
CORE.Input.Touch.position[i].y = -1;
}
// Reset keypress buffer
CORE.Input.Keyboard.lastKeyPressed.head = 0;
CORE.Input.Keyboard.lastKeyPressed.tail = 0;
// Reset keyboard key state
for (int i = 0; i < 512; i++) CORE.Input.Keyboard.currentKeyState[i] = 0;
// Open the linux directory of "/dev/input"
directory = opendir(DEFAULT_EVDEV_PATH);
if (directory)
{
while ((entity = readdir(directory)) != NULL)
{
if (strncmp("event", entity->d_name, strlen("event")) == 0) // Search for devices named "event*"
{
sprintf(path, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name);
EventThreadSpawn(path); // Identify the device and spawn a thread for it
}
}
closedir(directory);
}
else TRACELOG(LOG_WARNING, "RPI: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH);
}
// Identifies a input device and spawns a thread to handle it if needed
static void EventThreadSpawn(char *device)
{
#define BITS_PER_LONG (sizeof(long)*8)
#define NBITS(x) ((((x) - 1)/BITS_PER_LONG) + 1)
#define OFF(x) ((x)%BITS_PER_LONG)
#define BIT(x) (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define TEST_BIT(array, bit) ((array[LONG(bit)] >> OFF(bit)) & 1)
struct input_absinfo absinfo;
unsigned long evBits[NBITS(EV_MAX)];
unsigned long absBits[NBITS(ABS_MAX)];
unsigned long relBits[NBITS(REL_MAX)];
unsigned long keyBits[NBITS(KEY_MAX)];
bool hasAbs = false;
bool hasRel = false;
bool hasAbsMulti = false;
int freeWorkerId = -1;
int fd = -1;
InputEventWorker *worker;
// Open the device and allocate worker
//-------------------------------------------------------------------------------------------------------
// Find a free spot in the workers array
for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i)
{
if (CORE.Input.eventWorker[i].threadId == 0)
{
freeWorkerId = i;
break;
}
}
// Select the free worker from array
if (freeWorkerId >= 0)
{
worker = &(CORE.Input.eventWorker[freeWorkerId]); // Grab a pointer to the worker
memset(worker, 0, sizeof(InputEventWorker)); // Clear the worker
}
else
{
TRACELOG(LOG_WARNING, "RPI: Failed to create input device thread for %s, out of worker slots", device);
return;
}
// Open the device
fd = open(device, O_RDONLY | O_NONBLOCK);
if (fd < 0)
{
TRACELOG(LOG_WARNING, "RPI: Failed to open input device (error: %d)", device, worker->fd);
return;
}
worker->fd = fd;
// Grab number on the end of the devices name "event<N>"
int devNum = 0;
char *ptrDevName = strrchr(device, 't');
worker->eventNum = -1;
if (ptrDevName != NULL)
{
if (sscanf(ptrDevName, "t%d", &devNum) == 1)
worker->eventNum = devNum;
}
// At this point we have a connection to the device, but we don't yet know what the device is.
// It could be many things, even as simple as a power button...
//-------------------------------------------------------------------------------------------------------
// Identify the device
//-------------------------------------------------------------------------------------------------------
ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits); // Read a bitfield of the avalable device properties
// Check for absolute input devices
if (TEST_BIT(evBits, EV_ABS))
{
ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits);
// Check for absolute movement support (usualy touchscreens, but also joysticks)
if (TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y))
{
hasAbs = true;
// Get the scaling values
ioctl(fd, EVIOCGABS(ABS_X), &absinfo);
worker->absRange.x = absinfo.minimum;
worker->absRange.width = absinfo.maximum - absinfo.minimum;
ioctl(fd, EVIOCGABS(ABS_Y), &absinfo);
worker->absRange.y = absinfo.minimum;
worker->absRange.height = absinfo.maximum - absinfo.minimum;
}
// Check for multiple absolute movement support (usualy multitouch touchscreens)
if (TEST_BIT(absBits, ABS_MT_POSITION_X) && TEST_BIT(absBits, ABS_MT_POSITION_Y))
{
hasAbsMulti = true;
// Get the scaling values
ioctl(fd, EVIOCGABS(ABS_X), &absinfo);
worker->absRange.x = absinfo.minimum;
worker->absRange.width = absinfo.maximum - absinfo.minimum;
ioctl(fd, EVIOCGABS(ABS_Y), &absinfo);
worker->absRange.y = absinfo.minimum;
worker->absRange.height = absinfo.maximum - absinfo.minimum;
}
}
// Check for relative movement support (usualy mouse)
if (TEST_BIT(evBits, EV_REL))
{
ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits);
if (TEST_BIT(relBits, REL_X) && TEST_BIT(relBits, REL_Y)) hasRel = true;
}
// Check for button support to determine the device type(usualy on all input devices)
if (TEST_BIT(evBits, EV_KEY))
{
ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits);
if (hasAbs || hasAbsMulti)
{
if (TEST_BIT(keyBits, BTN_TOUCH)) worker->isTouch = true; // This is a touchscreen
if (TEST_BIT(keyBits, BTN_TOOL_FINGER)) worker->isTouch = true; // This is a drawing tablet
if (TEST_BIT(keyBits, BTN_TOOL_PEN)) worker->isTouch = true; // This is a drawing tablet
if (TEST_BIT(keyBits, BTN_STYLUS)) worker->isTouch = true; // This is a drawing tablet
if (worker->isTouch || hasAbsMulti) worker->isMultitouch = true; // This is a multitouch capable device
}
if (hasRel)
{
if (TEST_BIT(keyBits, BTN_LEFT)) worker->isMouse = true; // This is a mouse
if (TEST_BIT(keyBits, BTN_RIGHT)) worker->isMouse = true; // This is a mouse
}
if (TEST_BIT(keyBits, BTN_A)) worker->isGamepad = true; // This is a gamepad
if (TEST_BIT(keyBits, BTN_TRIGGER)) worker->isGamepad = true; // This is a gamepad
if (TEST_BIT(keyBits, BTN_START)) worker->isGamepad = true; // This is a gamepad
if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad
if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad
if (TEST_BIT(keyBits, KEY_SPACE)) worker->isKeyboard = true; // This is a keyboard
}
//-------------------------------------------------------------------------------------------------------
// Decide what to do with the device
//-------------------------------------------------------------------------------------------------------
if (worker->isTouch || worker->isMouse || worker->isKeyboard)
{
// Looks like an interesting device
TRACELOG(LOG_INFO, "RPI: Opening input device: %s (%s%s%s%s%s)", device,
worker->isMouse? "mouse " : "",
worker->isMultitouch? "multitouch " : "",
worker->isTouch? "touchscreen " : "",
worker->isGamepad? "gamepad " : "",
worker->isKeyboard? "keyboard " : "");
// Create a thread for this device
int error = pthread_create(&worker->threadId, NULL, &EventThread, (void *)worker);
if (error != 0)
{
TRACELOG(LOG_WARNING, "RPI: Failed to create input device thread: %s (error: %d)", device, error);
worker->threadId = 0;
close(fd);
}
#if defined(USE_LAST_TOUCH_DEVICE)
// Find touchscreen with the highest index
int maxTouchNumber = -1;
for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i)
{
if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = CORE.Input.eventWorker[i].eventNum;
}
// Find toucnscreens with lower indexes
for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i)
{
if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum < maxTouchNumber))
{
if (CORE.Input.eventWorker[i].threadId != 0)
{
TRACELOG(LOG_WARNING, "RPI: Found duplicate touchscreen, killing touchscreen on event: %d", i);
pthread_cancel(CORE.Input.eventWorker[i].threadId);
close(CORE.Input.eventWorker[i].fd);
}
}
}
#endif
}
else close(fd); // We are not interested in this device
//-------------------------------------------------------------------------------------------------------
}
// Input device events reading thread
static void *EventThread(void *arg)
{
// Scancode to keycode mapping for US keyboards
// TODO: Probably replace this with a keymap from the X11 to get the correct regional map for the keyboard:
// Currently non US keyboards will have the wrong mapping for some keys
static const int keymap_US[] =
{ 0,256,49,50,51,52,53,54,55,56,57,48,45,61,259,258,81,87,69,82,84,
89,85,73,79,80,91,93,257,341,65,83,68,70,71,72,74,75,76,59,39,96,
340,92,90,88,67,86,66,78,77,44,46,47,344,332,342,32,280,290,291,
292,293,294,295,296,297,298,299,282,281,327,328,329,333,324,325,
326,334,321,322,323,320,330,0,85,86,300,301,89,90,91,92,93,94,95,
335,345,331,283,346,101,268,265,266,263,262,269,264,267,260,261,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,347,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,0,0,0,0,0,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,0,0,0,0,0,0,0, };
struct input_event event;
InputEventWorker *worker = (InputEventWorker *)arg;
int touchAction = -1;
bool gestureUpdate = false;
int keycode;
while (!CORE.Window.shouldClose)
{
// Try to read data from the device and only continue if successful
if (read(worker->fd, &event, sizeof(event)) == (int)sizeof(event))
{
// Relative movement parsing
if (event.type == EV_REL)
{
if (event.code == REL_X)
{
CORE.Input.Mouse.position.x += event.value;
CORE.Input.Touch.position[0].x = CORE.Input.Mouse.position.x;
#if defined(SUPPORT_GESTURES_SYSTEM)
touchAction = TOUCH_MOVE;
gestureUpdate = true;
#endif
}
if (event.code == REL_Y)
{
CORE.Input.Mouse.position.y += event.value;
CORE.Input.Touch.position[0].y = CORE.Input.Mouse.position.y;
#if defined(SUPPORT_GESTURES_SYSTEM)
touchAction = TOUCH_MOVE;
gestureUpdate = true;
#endif
}
if (event.code == REL_WHEEL) CORE.Input.Mouse.currentWheelMove += event.value;
}
// Absolute movement parsing
if (event.type == EV_ABS)
{
// Basic movement
if (event.code == ABS_X)
{
CORE.Input.Mouse.position.x = (event.value - worker->absRange.x)*CORE.Window.screen.width/worker->absRange.width; // Scale acording to absRange
#if defined(SUPPORT_GESTURES_SYSTEM)
touchAction = TOUCH_MOVE;
gestureUpdate = true;
#endif
}
if (event.code == ABS_Y)
{
CORE.Input.Mouse.position.y = (event.value - worker->absRange.y)*CORE.Window.screen.height/worker->absRange.height; // Scale acording to absRange
#if defined(SUPPORT_GESTURES_SYSTEM)
touchAction = TOUCH_MOVE;
gestureUpdate = true;
#endif
}
// Multitouch movement
if (event.code == ABS_MT_SLOT) worker->touchSlot = event.value; // Remeber the slot number for the folowing events
if (event.code == ABS_MT_POSITION_X)
{
if (worker->touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[worker->touchSlot].x = (event.value - worker->absRange.x)*CORE.Window.screen.width/worker->absRange.width; // Scale acording to absRange
}
if (event.code == ABS_MT_POSITION_Y)
{
if (worker->touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[worker->touchSlot].y = (event.value - worker->absRange.y)*CORE.Window.screen.height/worker->absRange.height; // Scale acording to absRange
}
if (event.code == ABS_MT_TRACKING_ID)
{
if ((event.value < 0) && (worker->touchSlot < MAX_TOUCH_POINTS))
{
// Touch has ended for this point
CORE.Input.Touch.position[worker->touchSlot].x = -1;
CORE.Input.Touch.position[worker->touchSlot].y = -1;
}
}
}
// Button parsing
if (event.type == EV_KEY)
{
// Mouse button parsing
if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT))
{
CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_LEFT_BUTTON] = event.value;
#if defined(SUPPORT_GESTURES_SYSTEM)
if (event.value > 0) touchAction = TOUCH_DOWN;
else touchAction = TOUCH_UP;
gestureUpdate = true;
#endif
}
if (event.code == BTN_RIGHT) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_RIGHT_BUTTON] = event.value;
if (event.code == BTN_MIDDLE) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_MIDDLE_BUTTON] = event.value;
// Keyboard button parsing
if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255
{
keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode
// Make sure we got a valid keycode
if ((keycode > 0) && (keycode < sizeof(CORE.Input.Keyboard.currentKeyState)))
{
/* Disabled buffer !!
// Store the key information for raylib to later use
CORE.Input.Keyboard.currentKeyState[keycode] = event.value;
if (event.value > 0)
{
// Add the key int the fifo
CORE.Input.Keyboard.lastKeyPressed.contents[CORE.Input.Keyboard.lastKeyPressed.head] = keycode; // Put the data at the front of the fifo snake
CORE.Input.Keyboard.lastKeyPressed.head = (CORE.Input.Keyboard.lastKeyPressed.head + 1) & 0x07; // Increment the head pointer forwards and binary wraparound after 7 (fifo is 8 elements long)
// TODO: This fifo is not fully threadsafe with multiple writers, so multiple keyboards hitting a key at the exact same time could miss a key (double write to head before it was incremented)
}
*/
CORE.Input.Keyboard.currentKeyState[keycode] = event.value;
if (event.value == 1)
{
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode; // Register last key pressed
CORE.Input.Keyboard.keyPressedQueueCount++;
}
#if defined(SUPPORT_SCREEN_CAPTURE)
// Check screen capture key (raylib key: KEY_F12)
if (CORE.Input.Keyboard.currentKeyState[301] == 1)
{
TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter));
screenshotCounter++;
}
#endif
if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true;
TRACELOGD("RPI: KEY_%s ScanCode: %4i KeyCode: %4i", event.value == 0 ? "UP":"DOWN", event.code, keycode);
}
}
}
// Screen confinement
if (CORE.Input.Mouse.position.x < 0) CORE.Input.Mouse.position.x = 0;
if (CORE.Input.Mouse.position.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x) CORE.Input.Mouse.position.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x;
if (CORE.Input.Mouse.position.y < 0) CORE.Input.Mouse.position.y = 0;
if (CORE.Input.Mouse.position.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y) CORE.Input.Mouse.position.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y;
// Gesture update
if (gestureUpdate)
{
#if defined(SUPPORT_GESTURES_SYSTEM)
GestureEvent gestureEvent = { 0 };
gestureEvent.pointCount = 0;
gestureEvent.touchAction = touchAction;
if (CORE.Input.Touch.position[0].x >= 0) gestureEvent.pointCount++;
if (CORE.Input.Touch.position[1].x >= 0) gestureEvent.pointCount++;
if (CORE.Input.Touch.position[2].x >= 0) gestureEvent.pointCount++;
if (CORE.Input.Touch.position[3].x >= 0) gestureEvent.pointCount++;
gestureEvent.pointerId[0] = 0;
gestureEvent.pointerId[1] = 1;
gestureEvent.pointerId[2] = 2;
gestureEvent.pointerId[3] = 3;
gestureEvent.position[0] = CORE.Input.Touch.position[0];
gestureEvent.position[1] = CORE.Input.Touch.position[1];
gestureEvent.position[2] = CORE.Input.Touch.position[2];
gestureEvent.position[3] = CORE.Input.Touch.position[3];
ProcessGestureEvent(gestureEvent);
#endif
}
}
else
{
usleep(5000); // Sleep for 5ms to avoid hogging CPU time
}
}
close(worker->fd);
return NULL;
}
// Init gamepad system
static void InitGamepad(void)
{
char gamepadDev[128] = "";
for (int i = 0; i < MAX_GAMEPADS; i++)
{
sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i);
if ((CORE.Input.Gamepad.streamId[i] = open(gamepadDev, O_RDONLY|O_NONBLOCK)) < 0)
{
// NOTE: Only show message for first gamepad
if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available");
}
else
{
CORE.Input.Gamepad.ready[i] = true;
// NOTE: Only create one thread
if (i == 0)
{
int error = pthread_create(&CORE.Input.Gamepad.threadId, NULL, &GamepadThread, NULL);
if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread");
else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully");
}
}
}
}
// Process Gamepad (/dev/input/js0)
static void *GamepadThread(void *arg)
{
#define JS_EVENT_BUTTON 0x01 // Button pressed/released
#define JS_EVENT_AXIS 0x02 // Joystick axis moved
#define JS_EVENT_INIT 0x80 // Initial state of device
struct js_event {
unsigned int time; // event timestamp in milliseconds
short value; // event value
unsigned char type; // event type
unsigned char number; // event axis/button number
};
// Read gamepad event
struct js_event gamepadEvent;
while (!CORE.Window.shouldClose)
{
for (int i = 0; i < MAX_GAMEPADS; i++)
{
if (read(CORE.Input.Gamepad.streamId[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event))
{
gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events
// Process gamepad events by type
if (gamepadEvent.type == JS_EVENT_BUTTON)
{
TRACELOGD("RPI: Gamepad button: %i, value: %i", gamepadEvent.number, gamepadEvent.value);
if (gamepadEvent.number < MAX_GAMEPAD_BUTTONS)
{
// 1 - button pressed, 0 - button released
CORE.Input.Gamepad.currentState[i][gamepadEvent.number] = (int)gamepadEvent.value;
if ((int)gamepadEvent.value == 1) CORE.Input.Gamepad.lastButtonPressed = gamepadEvent.number;
else CORE.Input.Gamepad.lastButtonPressed = -1;
}
}
else if (gamepadEvent.type == JS_EVENT_AXIS)
{
TRACELOGD("RPI: Gamepad axis: %i, value: %i", gamepadEvent.number, gamepadEvent.value);
if (gamepadEvent.number < MAX_GAMEPAD_AXIS)
{
// NOTE: Scaling of gamepadEvent.value to get values between -1..1
CORE.Input.Gamepad.axisState[i][gamepadEvent.number] = (float)gamepadEvent.value/32768;
}
}
}
else
{
usleep(1000); //Sleep for 1ms to avoid hogging CPU time
}
}
}
return NULL;
}
#endif // PLATFORM_RPI
|