sola-raylib-sys 6.1.0

Raw FFI bindings for raylib. sola-raylib-sys N.x tracks raylib N.x (e.g. 5.x → raylib 5.5; 6.x → raylib 6.0).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
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
/**********************************************************************************************
*
*   rcore_drm - Functions to manage window, graphics device and inputs
*
*   PLATFORM: DRM
*       - Raspberry Pi 0-5 (DRM/KMS)
*       - Linux DRM subsystem (KMS mode)
*
*   LIMITATIONS:
*       - Most of the window/monitor functions are not implemented (not required)
*
*   POSSIBLE IMPROVEMENTS:
*       - Improvement 01
*       - Improvement 02
*
*   CONFIGURATION:
*       #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 orblocking the device if not restored properly. Use with care
*
*   DEPENDENCIES:
*       - DRM and GLM: System libraries for display initialization and configuration
*       - gestures: Gestures system for touch-ready devices (or simulated from mouse inputs)
*
*
*   LICENSE: zlib/libpng
*
*   Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
*
*   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 <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 <limits.h>         // INT_MAX

#include <sys/ioctl.h>      // Required for: ioctl() - UNIX System call for device-specific input/output operations
#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

// WARNING: Both 'linux/input.h' and 'raylib.h' define KEY_F12
// To avoid conflict with the capturing code in rcore.c, undefine the macro KEY_F12,
// so the enum KEY_F12 from raylib is used
#undef KEY_F12

#include <xf86drm.h>        // Direct Rendering Manager user-level library interface
#include <xf86drmMode.h>    // Direct Rendering Manager mode setting (KMS) interface

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    #include <gbm.h>            // Generic Buffer Management (native platform for EGL on DRM)
    #include "EGL/egl.h"        // Native platform windowing system interface
    #include "EGL/eglext.h"     // EGL extensions
#else
    #include <sys/mman.h>       // For mmap when copying to the dumb buffer
    #include <errno.h>          // For the conversion of certain error messages
#endif

// NOTE: DRM cache enables triple buffered DRM caching
#if defined(SUPPORT_DRM_CACHE)
    #include <poll.h>       // Required for: drmHandleEvent() poll
    #include <errno.h>      // Required for: EBUSY, EAGAIN

    #define MAX_DRM_CACHED_BUFFERS  3
#endif

#ifndef EGL_OPENGL_ES3_BIT
    #define EGL_OPENGL_ES3_BIT  0x40
#endif

#ifndef EGL_PLATFORM_GBM_KHR
    #define EGL_PLATFORM_GBM_KHR  0x31D7
#endif

//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#define USE_LAST_TOUCH_DEVICE           // When multiple touchscreens are connected, only use the one with the highest event<N> number

#define DEFAULT_EVDEV_PATH "/dev/input/"    // Path to the linux input events

// Actually biggest key is KEY_CNT but only mapping keys up to KEY_ALS_TOGGLE
#define KEYMAP_SIZE KEY_ALS_TOGGLE

//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
typedef struct {
    // Display data
    int fd;                             // File descriptor for /dev/dri/...
    drmModeConnector *connector;        // Direct Rendering Manager (DRM) mode connector
    drmModeCrtc *crtc;                  // CRT Controller
    int modeIndex;                      // Index of the used mode of connector->modes
    uint32_t prevFB;                    // Previous DRM framebufer (during frame swapping)

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    struct gbm_device *gbmDevice;       // GBM device
    struct gbm_surface *gbmSurface;     // GBM surface
    struct gbm_bo *prevBO;              // Previous GBM buffer object (during frame swapping)
    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
#else
    uint32_t prevDumbHandle;            // Handle to the previous dumb buffer (during frame swapping)
#endif

    // Keyboard data
    int defaultKeyboardMode;            // Default keyboard mode
    bool eventKeyboardMode;             // Keyboard in event mode
    int defaultFileFlags;               // Default IO file flags
    struct termios defaultSettings;     // Default keyboard settings
    int keyboardFd;                     // File descriptor for the evdev keyboard

    // Mouse data
    Vector2 eventWheelMove;             // Registers the event mouse wheel variation
    // NOTE: currentButtonState[] can't be written directly due to multithreading, app could miss the update
    char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; // Holds the new mouse state for the next polling event to grab
    bool cursorRelative;                // Relative cursor mode
    int mouseFd;                        // File descriptor for the evdev mouse/touch/gestures
    bool mouseIsTouch;                  // Check if the current mouse device is actually a touchscreen
    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 touchActive[MAX_TOUCH_POINTS]; // Track which touch points are currently active
    Vector2 touchPosition[MAX_TOUCH_POINTS]; // Track touch positions for each slot
    int touchId[MAX_TOUCH_POINTS];      // Track touch IDs for each slot

    // Gamepad data
    int gamepadStreamFd[MAX_GAMEPADS];  // Gamepad device file descriptor
    int gamepadAbsAxisRange[MAX_GAMEPADS][MAX_GAMEPAD_AXES][2]; // [0] = min, [1] = range value of the axes
    int gamepadAbsAxisMap[MAX_GAMEPADS][ABS_CNT]; // Maps the axes gamepads from the evdev api to a sequential one
    int gamepadCount;                   // The number of gamepads registered
} PlatformData;

#if defined(SUPPORT_DRM_CACHE)
typedef struct {
    struct gbm_bo *bo;      // Graphics buffer object
    uint32_t fbId;          // DRM framebuffer ID
} FramebufferCache;

static FramebufferCache fbCache[MAX_DRM_CACHED_BUFFERS] = { 0 };
static volatile int fbCacheCount = 0;
static volatile bool pendingFlip = false;
static bool crtcSet = false;
#endif

//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
extern CoreData CORE;                   // Global CORE state context

static PlatformData platform = { 0 };   // Platform specific data

//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------

// NOTE: The complete evdev EV_KEY list can be found at /usr/include/linux/input-event-codes.h
// TODO: Complete the LUT with all unicode decimal values
// TODO: 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
// NOTE: Replacing this with the keymap from X11 would probably be useless, as people use the drm
// backend to *avoid* X11
static const int evkeyToUnicodeLUT[] = {
    0, 27, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 8, 0, 113, 119, 101, 114,
    116, 121, 117, 105, 111, 112, 0, 0, 13, 0, 97, 115, 100, 102, 103, 104, 106, 107, 108, 59,
    39, 96, 0, 92, 122, 120, 99, 118, 98, 110, 109, 44, 46, 47, 0, 0, 0, 32
    // LUT currently incomplete, only mapped the most essential keys
};

// This is the map used to map any keycode returned from linux to a raylib code from 'raylib.h'
// NOTE: Use short here to save a little memory
static const short linuxToRaylibMap[KEYMAP_SIZE] = {
    // Don't map with designated initialization,
    // it will geenrate many naming conflicts
    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,

    // Gamepads are mapped according to:
    // REF: https://www.kernel.org/doc/html/next/input/gamepad.html
    // Those mappings are standardized, but that doesn't mean people follow
    // the standards, so this is more of an approximation
    [BTN_DPAD_UP] = GAMEPAD_BUTTON_LEFT_FACE_UP,
    [BTN_DPAD_RIGHT] = GAMEPAD_BUTTON_LEFT_FACE_RIGHT,
    [BTN_DPAD_DOWN] = GAMEPAD_BUTTON_LEFT_FACE_DOWN,
    [BTN_DPAD_LEFT] = GAMEPAD_BUTTON_LEFT_FACE_LEFT,
    [BTN_Y] = GAMEPAD_BUTTON_RIGHT_FACE_UP,
    [BTN_B] = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT,
    [BTN_A] = GAMEPAD_BUTTON_RIGHT_FACE_DOWN,
    [BTN_X] = GAMEPAD_BUTTON_RIGHT_FACE_LEFT,
    [BTN_TL] = GAMEPAD_BUTTON_LEFT_TRIGGER_1,
    [BTN_TL2] = GAMEPAD_BUTTON_LEFT_TRIGGER_2,
    [BTN_TR] = GAMEPAD_BUTTON_RIGHT_TRIGGER_1,
    [BTN_TR2] = GAMEPAD_BUTTON_RIGHT_TRIGGER_2,
    [BTN_SELECT] = GAMEPAD_BUTTON_MIDDLE_LEFT,
    [BTN_MODE] = GAMEPAD_BUTTON_MIDDLE,
    [BTN_START] = GAMEPAD_BUTTON_MIDDLE_RIGHT,
    [BTN_THUMBL] = GAMEPAD_BUTTON_LEFT_THUMB,
    [BTN_THUMBR] = GAMEPAD_BUTTON_RIGHT_THUMB,
};

//----------------------------------------------------------------------------------
// Module Internal Functions Declaration
//----------------------------------------------------------------------------------
int InitPlatform(void);          // Initialize platform (graphics, inputs and more)
void ClosePlatform(void);        // Close platform

#if SUPPORT_SSH_KEYBOARD_RPI
static void InitKeyboard(void);                 // Initialize raw keyboard system
static void RestoreKeyboard(void);              // Restore keyboard system
static void ProcessKeyboard(void);              // Process keyboard events
#endif

// Input management functions
static void InitEvdevInput(void);               // Initialize evdev inputs
static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate
static void PollKeyboardEvents(void);           // Process evdev keyboard events
static void PollGamepadEvents(void);            // Process evdev gamepad events
static void PollMouseEvents(void);              // Process evdev mouse events

static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode);                               // Search matching DRM mode in connector's mode list
static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced);      // Search exactly matching DRM connector mode in connector's list
static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced);    // Search the nearest matching DRM connector mode in connector's list

static void SetupFramebuffer(int width, int height); // Setup main framebuffer (required by InitPlatform())

//----------------------------------------------------------------------------------
// Module Functions Declaration
//----------------------------------------------------------------------------------
// NOTE: Functions declaration is provided by raylib.h

//----------------------------------------------------------------------------------
// Module Functions Definition: Window and Graphics Device
//----------------------------------------------------------------------------------

// Check if application should close
// NOTE: By default, if KEY_ESCAPE pressed
bool WindowShouldClose(void)
{
    if (CORE.Window.ready) return CORE.Window.shouldClose;
    else return true;
}

// Toggle fullscreen mode
void ToggleFullscreen(void)
{
    TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform");
}

// Toggle borderless windowed mode
void ToggleBorderlessWindowed(void)
{
    TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform");
}

// Set window state: maximized, if resizable
void MaximizeWindow(void)
{
    TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform");
}

// Set window state: minimized
void MinimizeWindow(void)
{
    TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform");
}

// Restore window from being minimized/maximized
void RestoreWindow(void)
{
    TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform");
}

// Set window configuration state using flags
void SetWindowState(unsigned int flags)
{
    TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform");
}

// Clear window configuration state flags
void ClearWindowState(unsigned int flags)
{
    TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform");
}

// Set icon for window
void SetWindowIcon(Image image)
{
    TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform");
}

// Set icon for window
void SetWindowIcons(Image *images, int count)
{
    TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
}

// Set title for window
void SetWindowTitle(const char *title)
{
    CORE.Window.title = title;
}

// Set window position on screen (windowed mode)
void SetWindowPosition(int x, int y)
{
    TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform");
}

// Set monitor for the current window
void SetWindowMonitor(int monitor)
{
    TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform");
}

// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
void SetWindowMinSize(int width, int height)
{
    CORE.Window.screenMin.width = width;
    CORE.Window.screenMin.height = height;
}

// Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
void SetWindowMaxSize(int width, int height)
{
    CORE.Window.screenMax.width = width;
    CORE.Window.screenMax.height = height;
}

// Set window dimensions
void SetWindowSize(int width, int height)
{
    TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform");
}

// Set window opacity, value opacity is between 0.0 and 1.0
void SetWindowOpacity(float opacity)
{
    TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform");
}

// Set window focused
void SetWindowFocused(void)
{
    TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform");
}

// Get native window handle
void *GetWindowHandle(void)
{
    TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform");
    return NULL;
}

// Get number of monitors
int GetMonitorCount(void)
{
    TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform");
    return 1;
}

// Get current monitor where window is placed
int GetCurrentMonitor(void)
{
    TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform");
    return 0;
}

// Get selected monitor position
Vector2 GetMonitorPosition(int monitor)
{
    TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform");
    return (Vector2){ 0, 0 };
}

// Get selected monitor width (currently used by monitor)
int GetMonitorWidth(int monitor)
{
    int width = 0;

    if (monitor != 0)
    {
        TRACELOG(LOG_WARNING, "GetMonitorWidth() implemented for first monitor only");
    }
    else if ((platform.connector) && (platform.modeIndex >= 0))
    {
        width = platform.connector->modes[platform.modeIndex].hdisplay;
    }

    return width;
}

// Get selected monitor height (currently used by monitor)
int GetMonitorHeight(int monitor)
{
    int height = 0;

    if (monitor != 0)
    {
        TRACELOG(LOG_WARNING, "GetMonitorHeight() implemented for first monitor only");
    }
    else if ((platform.connector) && (platform.modeIndex >= 0))
    {
        height = platform.connector->modes[platform.modeIndex].vdisplay;
    }

    return height;
}

// Get selected monitor physical width in millimetres
int GetMonitorPhysicalWidth(int monitor)
{
    int physicalWidth = 0;

    if (monitor != 0)
    {
        TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() implemented for first monitor only");
    }
    else if ((platform.connector) && (platform.modeIndex >= 0))
    {
        physicalWidth = platform.connector->mmWidth;
    }

    return physicalWidth;
}

// Get selected monitor physical height in millimetres
int GetMonitorPhysicalHeight(int monitor)
{
    int physicalHeight = 0;

    if (monitor != 0)
    {
        TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() implemented for first monitor only");
    }
    else if ((platform.connector) && (platform.modeIndex >= 0))
    {
        physicalHeight = platform.connector->mmHeight;
    }

    return physicalHeight;
}

// Get selected monitor refresh rate
int GetMonitorRefreshRate(int monitor)
{
    int refresh = 0;

    if ((platform.connector) && (platform.modeIndex >= 0))
    {
        refresh = platform.connector->modes[platform.modeIndex].vrefresh;
    }

    return refresh;
}

// Get the human-readable, UTF-8 encoded name of the selected monitor
const char *GetMonitorName(int monitor)
{
    const char *name = "";

    if (monitor != 0)
    {
        TRACELOG(LOG_WARNING, "GetMonitorName() implemented for first monitor only");
    }
    else if ((platform.connector) && (platform.modeIndex >= 0))
    {
        name = platform.connector->modes[platform.modeIndex].name;
    }

    return name;
}

// Get window position XY on monitor
Vector2 GetWindowPosition(void)
{
    return (Vector2){ 0, 0 };
}

// Get window scale DPI factor for current monitor
Vector2 GetWindowScaleDPI(void)
{
    return (Vector2){ 1.0f, 1.0f };
}

// Set clipboard text content
void SetClipboardText(const char *text)
{
    TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform");
}

// Get clipboard text content
// NOTE: returned string is allocated and freed by GLFW
const char *GetClipboardText(void)
{
    TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform");
    return NULL;
}

// Get clipboard image
Image GetClipboardImage(void)
{
    Image image = { 0 };

    TRACELOG(LOG_WARNING, "GetClipboardImage() not implemented on target platform");

    return image;
}

// Show mouse cursor
void ShowCursor(void)
{
    CORE.Input.Mouse.cursorHidden = false;
}

// Hides mouse cursor
void HideCursor(void)
{
    CORE.Input.Mouse.cursorHidden = true;
}

// Enables cursor (unlock cursor)
void EnableCursor(void)
{
    // Set cursor position in the middle
    SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);

    platform.cursorRelative = false;
    CORE.Input.Mouse.cursorLocked = false;
}

// Disables cursor (lock cursor)
void DisableCursor(void)
{
    // Set cursor position in the middle
    SetMousePosition(0, 0);

    platform.cursorRelative = true;
    CORE.Input.Mouse.cursorLocked = true;
}

#if defined(SUPPORT_DRM_CACHE)

// Destroy cached framebuffer callback, set by gbm_bo_set_user_data()
static void DestroyFrameBufferCallback(struct gbm_bo *bo, void *data)
{
    uint32_t fbId = (uintptr_t)data;

    // Remove from cache
    for (int i = 0; i < fbCacheCount; i++)
    {
        if (fbCache[i].bo == bo)
        {
            TRACELOG(LOG_INFO, "DISPLAY: DRM: Framebuffer removed [%u]", (uintptr_t)fbId);
            drmModeRmFB(platform.fd, fbCache[i].fbId); // Release DRM FB

            // Shift remaining entries
            for (int j = i; j < fbCacheCount - 1; j++) fbCache[j] = fbCache[j + 1];

            fbCacheCount--;
            break;
        }
    }
}

// Create or retrieve cached DRM FB for BO
static uint32_t GetOrCreateFbForBo(struct gbm_bo *bo)
{
    // Try to find existing cache entry
    for (int i = 0; i < fbCacheCount; i++)
    {
        if (fbCache[i].bo == bo) return fbCache[i].fbId;
    }

    // Create new entry if cache not full
    if (fbCacheCount >= MAX_DRM_CACHED_BUFFERS) return 0; // FB cache full

    uint32_t handle = gbm_bo_get_handle(bo).u32;
    uint32_t stride = gbm_bo_get_stride(bo);
    uint32_t width = gbm_bo_get_width(bo);
    uint32_t height = gbm_bo_get_height(bo);

    uint32_t fbId = 0;
    if (drmModeAddFB(platform.fd, width, height, 24, 32, stride, handle, &fbId)) return 0;

    // Store in cache
    fbCache[fbCacheCount] = (FramebufferCache){ .bo = bo, .fbId = fbId };
    fbCacheCount++;

    // Set destroy callback to auto-cleanup
    gbm_bo_set_user_data(bo, (void *)(uintptr_t)fbId, DestroyFrameBufferCallback);

    TRACELOG(LOG_INFO, "DISPLAY: DRM: Added new buffer object [%u]" , (uintptr_t)fbId);

    return fbId;
}

// Renders a blank frame to allocate initial buffers
// TODO: WARNING: Platform backend should not include OpenGL code
void RenderBlankFrame()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    eglSwapBuffers(platform.device, platform.surface);
    glFinish(); // Ensure the buffer is processed
}

// Initialize with first buffer only
int InitSwapScreenBuffer()
{
    if (!platform.gbmSurface || (platform.fd < 0))
    {
        TRACELOG(LOG_ERROR, "DISPLAY: DRM: Swap buffers can not be initialized");
        return -1;
    }

    // Render a blank frame to allocate buffers
    RenderBlankFrame();

    // Get first buffer
    struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface);
    if (!bo)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to lock initial swap buffer");
        return -1;
    }

    // Create FB for first buffer
    uint32_t fbId = GetOrCreateFbForBo(bo);
    if (!fbId)
    {
        gbm_surface_release_buffer(platform.gbmSurface, bo);
        return -1;
    }

    // Initial CRTC setup
    if (drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fbId, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]))
    {
        TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to initialize CRTC setup. ERROR: %s", strerror(errno));
        gbm_surface_release_buffer(platform.gbmSurface, bo);
        return -1;
    }

    // Keep first buffer locked until flipped
    platform.prevBO = bo;
    crtcSet = true;

    return 0;
}

// Static page flip handler
// NOTE: Called once the drmModePageFlip() finished from the drmHandleEvent() context
static void PageFlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
{
    // Unused inputs
    (void)fd;
    (void)frame;
    (void)sec;
    (void)usec;

    pendingFlip = false;
    struct gbm_bo *boToRelease = (struct gbm_bo *)data;

    // Buffers are released after the flip completes (via page_flip_handler), ensuring they're no longer in use
    // Prevents the GPU from writing to a buffer being scanned out
    if (boToRelease) gbm_surface_release_buffer(platform.gbmSurface, boToRelease);
}

// Swap implementation with proper caching
void SwapScreenBuffer()
{
    if (!crtcSet || !platform.gbmSurface) return;

    static int loopCnt = 0;
    static int errCnt[5] = { 0 };
    loopCnt++;

    // Call this only, if pendingFlip is not set
    eglSwapBuffers(platform.device, platform.surface);

    // Process pending events non-blocking
    drmEventContext evctx = {
        .version = DRM_EVENT_CONTEXT_VERSION,
        .page_flip_handler = PageFlipHandler
    };

    struct pollfd pfd = { .fd = platform.fd, .events = POLLIN };

    // Polling for event for 0ms
    while (poll(&pfd, 1, 0) > 0) drmHandleEvent(platform.fd, &evctx);

    // Skip if previous flip pending
    if (pendingFlip)
    {
        errCnt[0]++; // Skip frame: flip pending
        return;
    }

    // Get new front buffer
    struct gbm_bo *nextBO = gbm_surface_lock_front_buffer(platform.gbmSurface);
    if (!nextBO) // Failed to lock front buffer
    {
        errCnt[1]++;
        return;
    }

    // Get FB ID (creates new one if needed)
    uint32_t fbId = GetOrCreateFbForBo(nextBO);
    if (!fbId)
    {
        gbm_surface_release_buffer(platform.gbmSurface, nextBO);
        errCnt[2]++;
        return;
    }

    // Attempt page flip
    // NOTE: rmModePageFlip() schedules a buffer-flip for the next vblank and then notifies us about it
    // It takes a CRTC-id, fb-id and an arbitrary data-pointer and then schedules the page-flip
    // This is fully asynchronous and when the page-flip happens, the DRM-fd will become readable and drmHandleEvent() can be called
    // This will read all vblank/page-flip events and call our modeset_page_flip_event() callback with the data-pointer passed to drmModePageFlip()
    // Simply call modeset_draw_dev() then so the next frame is rendered... returns immediately
    if (drmModePageFlip(platform.fd, platform.crtc->crtc_id, fbId, DRM_MODE_PAGE_FLIP_EVENT, platform.prevBO))
    {
        if (errno == EBUSY) errCnt[3]++; // Display busy - skip flip
        else errCnt[4]++; // Page flip failed

        gbm_surface_release_buffer(platform.gbmSurface, nextBO);
        return;
    }

    // Success: update state
    pendingFlip = true;
    platform.prevBO = nextBO;

/*
    // Some benchmarking code
    if (loopCnt >= 600)
    {
        TRACELOG(LOG_INFO, "DRM: Error counters: %d, %d, %d, %d, %d, %d", errCnt[0], errCnt[1], errCnt[2], errCnt[3], errCnt[4], loopCnt);
        for (int i = 0; i < 5; i++) errCnt[i] = 0;
        loopCnt = 0;
    }
*/
}

#else // !SUPPORT_DRM_CACHE

// Swap back buffer with front buffer (screen drawing)
void SwapScreenBuffer(void)
{
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    // Hardware rendering buffer swap with EGL
    eglSwapBuffers(platform.device, platform.surface);

    if (!platform.gbmSurface || (-1 == platform.fd) || !platform.connector || !platform.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap");

    struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface);
    if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer");

    uint32_t fb = 0;
    int result = drmModeAddFB(platform.fd, platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay, 24, 32, gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, &fb);
    if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result);

    result = drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fb, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]);
    if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result);

    if (platform.prevFB)
    {
        result = drmModeRmFB(platform.fd, platform.prevFB);
        if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result);
    }

    platform.prevFB = fb;

    if (platform.prevBO) gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO);

    platform.prevBO = bo;
#else
    // Software rendering buffer swap
    if ((platform.fd == -1) || !platform.connector || (platform.modeIndex < 0))
    {
        TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap");
        return;
    }

    // Retrieving the dimensions of the display mode used
    drmModeModeInfo *mode = &platform.connector->modes[platform.modeIndex];
    uint32_t width = mode->hdisplay;
    uint32_t height = mode->vdisplay;

    // Dumb buffers use a fixed format based on bpp
    const uint32_t bpp = 32;    // 32 bits per pixel (XRGB8888 format)
    const uint32_t depth = 24;  // Color depth, here only 24 bits, alpha is not used

    // Create a dumb buffer for software rendering
    struct drm_mode_create_dumb creq = { 0 };
    creq.width = width;
    creq.height = height;
    creq.bpp = bpp;

    int result = drmIoctl(platform.fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq);
    if (result < 0)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: Failed to create dumb buffer: %s", strerror(errno));
        return;
    }

    // Create framebuffer with the correct format
    uint32_t fb = 0;
    result = drmModeAddFB(platform.fd, width, height, depth, bpp, creq.pitch, creq.handle, &fb);
    if (result != 0)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d (%s)", result, strerror(errno));
        struct drm_mode_destroy_dumb dreq = { 0 };
        dreq.handle = creq.handle;
        drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
        return;
    }

    // Map the dumb buffer to copy our software rendered buffer
    struct drm_mode_map_dumb mreq = { 0 };
    mreq.handle = creq.handle;
    result = drmIoctl(platform.fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq);
    if (result != 0)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: Failed to map dumb buffer: %s", strerror(errno));
        drmModeRmFB(platform.fd, fb);
        struct drm_mode_destroy_dumb dreq = { 0 };
        dreq.handle = creq.handle;
        drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
        return;
    }

    // Map the buffer into userspace
    void *dumbBuffer = mmap(0, creq.size, PROT_READ | PROT_WRITE, MAP_SHARED, platform.fd, mreq.offset);
    if (dumbBuffer == MAP_FAILED)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: Failed to mmap dumb buffer: %s", strerror(errno));
        drmModeRmFB(platform.fd, fb);
        struct drm_mode_destroy_dumb dreq = { 0 };
        dreq.handle = creq.handle;
        drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
        return;
    }

    // Copy the software rendered buffer to the dumb buffer with scaling if needed
    // NOTE: RLSW will make a simple copy if the dimensions match
    swBlitPixels(0, 0, width, height, 0, 0, width, height, SW_RGBA, SW_UNSIGNED_BYTE, dumbBuffer);

    // Unmap the buffer
    munmap(dumbBuffer, creq.size);

    // Find a CRTC compatible with the connector
    uint32_t crtcId = 0;
    if (platform.crtc) crtcId = platform.crtc->crtc_id;
    else
    {
        // Find a CRTC that's compatible with this connector
        drmModeRes *res = drmModeGetResources(platform.fd);
        if (!res)
        {
            TRACELOG(LOG_ERROR, "DISPLAY: Failed to get DRM resources");
            drmModeRmFB(platform.fd, fb);
            struct drm_mode_destroy_dumb dreq = { 0 };
            dreq.handle = creq.handle;
            drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
            return;
        }

        // Check which CRTCs are compatible with this connector
        drmModeEncoder *encoder = NULL;
        if (platform.connector->encoder_id) encoder = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);

        if (encoder && encoder->crtc_id)
        {
            crtcId = encoder->crtc_id;
            platform.crtc = drmModeGetCrtc(platform.fd, crtcId);
        }
        else
        {
            // Find a free CRTC
            for (int i = 0; i < res->count_crtcs; i++)
            {
                drmModeCrtc *crtc = drmModeGetCrtc(platform.fd, res->crtcs[i]);
                if (crtc && !crtc->buffer_id) // CRTC is free
                {
                    crtcId = res->crtcs[i];
                    if (platform.crtc) drmModeFreeCrtc(platform.crtc);
                    platform.crtc = crtc;
                    break;
                }

                if (crtc) drmModeFreeCrtc(crtc);
            }
        }

        if (encoder) drmModeFreeEncoder(encoder);
        drmModeFreeResources(res);

        if (!crtcId)
        {
            TRACELOG(LOG_ERROR, "DISPLAY: No compatible CRTC found");
            drmModeRmFB(platform.fd, fb);
            struct drm_mode_destroy_dumb dreq = { 0 };
            dreq.handle = creq.handle;
            drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
            return;
        }
    }

    // Set CRTC with better error handling
    result = drmModeSetCrtc(platform.fd, crtcId, fb, 0, 0, &platform.connector->connector_id, 1, mode);
    if (result != 0)
    {
        TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d (%s)", result, strerror(errno));
        TRACELOG(LOG_ERROR, "DISPLAY: CRTC ID: %u, FB ID: %u, Connector ID: %u", crtcId, fb, platform.connector->connector_id);
        TRACELOG(LOG_ERROR, "DISPLAY: Mode: %dx%d@%d", mode->hdisplay, mode->vdisplay, mode->vrefresh);

        drmModeRmFB(platform.fd, fb);
        struct drm_mode_destroy_dumb dreq = { 0 };
        dreq.handle = creq.handle;
        drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
        return;
    }

    // Clean up previous framebuffer
    if (platform.prevFB)
    {
        result = drmModeRmFB(platform.fd, platform.prevFB);
        if (result != 0) TRACELOG(LOG_WARNING, "DISPLAY: drmModeRmFB() failed with result: %d", result);
    }

    platform.prevFB = fb;

    // Clean up previous dumb buffer
    if (platform.prevDumbHandle)
    {
        struct drm_mode_destroy_dumb dreq = { 0 };
        dreq.handle = platform.prevDumbHandle;
        drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
    }

    platform.prevDumbHandle = creq.handle;
#endif
}
#endif // SUPPORT_DRM_CACHE

//----------------------------------------------------------------------------------
// Module Functions Definition: Misc
//----------------------------------------------------------------------------------

// Get elapsed time measure in seconds since InitTimer()
double GetTime(void)
{
    double time = 0.0;
    struct timespec ts = { 0 };
    clock_gettime(CLOCK_MONOTONIC, &ts);
    unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;

    time = (double)(nanoSeconds - CORE.Time.base)*1e-9;  // Elapsed time since InitTimer()

    return time;
}

// Open URL with default system browser (if available)
// NOTE: This function is only safe to use if the provided URL is safe
// A user could craft a malicious string performing another action
// Avoid calling this function with user input non-validated strings
void OpenURL(const char *url)
{
    TRACELOG(LOG_WARNING, "OpenURL() not implemented on target platform");
}

//----------------------------------------------------------------------------------
// Module Functions Definition: Inputs
//----------------------------------------------------------------------------------

// Set internal gamepad mappings
int SetGamepadMappings(const char *mappings)
{
    TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform");
    return 0;
}

// Set gamepad vibration
void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
{
    TRACELOG(LOG_WARNING, "SetGamepadVibration() not implemented on target platform");
}

// Set mouse position XY
void SetMousePosition(int x, int y)
{
    CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
    CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
}

// Set mouse cursor
void SetMouseCursor(int cursor)
{
    TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform");
}

// Get physical key name
const char *GetKeyName(int key)
{
    TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform");
    return "";
}

// Register all input events
void PollInputEvents(void)
{
#if SUPPORT_GESTURES_SYSTEM
    // NOTE: Gestures update must be called every frame to reset gestures correctly
    // because ProcessGestureEvent() is called on an event, not every frame
    UpdateGestures();
#endif

    // Reset keys/chars pressed registered
    CORE.Input.Keyboard.keyPressedQueueCount = 0;
    CORE.Input.Keyboard.charPressedQueueCount = 0;

    // Reset last gamepad button/axis registered state
    CORE.Input.Gamepad.lastButtonPressed = 0;       // GAMEPAD_BUTTON_UNKNOWN
    //CORE.Input.Gamepad.axisCount = 0;

    // Register previous keys states
    for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
    {
        CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
        CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
    }

    PollKeyboardEvents();

#if SUPPORT_SSH_KEYBOARD_RPI
    // NOTE: Keyboard reading could be done using input_event(s) or read from stdin, both methods are used here
    // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console
    if (!platform.eventKeyboardMode) ProcessKeyboard();
#endif

    // Check exit key
    if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true;

    // Register previous mouse position
    if (platform.cursorRelative) CORE.Input.Mouse.currentPosition = (Vector2){ 0.0f, 0.0f };
    else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;

    // Register previous mouse states
    CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
    CORE.Input.Mouse.currentWheelMove = platform.eventWheelMove;
    platform.eventWheelMove = (Vector2){ 0.0f, 0.0f };

    for (int i = 0; i < MAX_MOUSE_BUTTONS; i++)
    {
        CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
        CORE.Input.Mouse.currentButtonState[i] = platform.currentButtonStateEvdev[i];
        CORE.Input.Touch.currentTouchState[i] = platform.currentButtonStateEvdev[i];
    }

    // Register gamepads buttons events
    PollGamepadEvents();

    // Register previous touch states
    for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];

    // Map touch position to mouse position for convenience
    // NOTE: For DRM touchscreen devices, this mapping is disabled to avoid false touch detection
    // CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;

    // Handle the mouse/touch/gestures events:
    PollMouseEvents();
}

//----------------------------------------------------------------------------------
// Module Internal Functions Definition
//----------------------------------------------------------------------------------

// Initialize platform: graphics, inputs and more
int InitPlatform(void)
{
    platform.fd = -1;
    platform.connector = NULL;
    platform.modeIndex = -1;
    platform.crtc = NULL;
    platform.prevFB = 0;

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    platform.gbmDevice = NULL;
    platform.gbmSurface = NULL;
    platform.prevBO = NULL;
#else
    platform.prevDumbHandle = 0;
#endif

    // Initialize graphic device: display/window and graphic context
    //----------------------------------------------------------------------------
    FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);

#if defined(DEFAULT_GRAPHIC_DEVICE_DRM)
    platform.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR);
    if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: Default graphic device DRM opened successfully");
#else
    TRACELOG(LOG_WARNING, "DISPLAY: No graphic card set, trying platform-gpu-card");
    platform.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4)
    if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: platform-gpu-card opened successfully");

    drmModeRes *res = NULL;
    if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
    {
        if (platform.fd != -1) close(platform.fd);
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to open platform-gpu-card, trying card1");
        platform.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded
        if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card1 opened successfully");
    }

    if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
    {
        if (platform.fd != -1) close(platform.fd);
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card1, trying card0");
        platform.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3)
        if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card0 opened successfully");
    }

    if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
    {
        if (platform.fd != -1) close(platform.fd);
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card0, trying card2");
        platform.fd = open("/dev/dri/card2", O_RDWR);
        if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card2 opened successfully");
    }
#endif

    if (platform.fd == -1)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card");
        return -1;
    }

    if (!res)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed get DRM resources");
        close(platform.fd);
        return -1;
    }

    TRACELOG(LOG_TRACE, "DISPLAY: Connectors found: %i", res->count_connectors);

    // Connector detection
    for (size_t i = 0; i < res->count_connectors; i++)
    {
        TRACELOG(LOG_TRACE, "DISPLAY: Connector index %i", i);

        drmModeConnector *con = drmModeGetConnector(platform.fd, res->connectors[i]);
        if (!con)
        {
            TRACELOG(LOG_WARNING, "DISPLAY: Failed to get connector %i", i);
            continue;
        }

        TRACELOG(LOG_TRACE, "DISPLAY: Connector %i modes detected: %i", i, con->count_modes);
        TRACELOG(LOG_TRACE, "DISPLAY: Connector %i status: %s", i,
                 (con->connection == DRM_MODE_CONNECTED)? "CONNECTED" :
                 (con->connection == DRM_MODE_DISCONNECTED)? "DISCONNECTED" :
                 (con->connection == DRM_MODE_UNKNOWNCONNECTION)? "UNKNOWN" : "OTHER");

        // In certain cases the status of the conneciton is reported as UKNOWN, but it is still connected
        // This might be a hardware or software limitation like on Raspberry Pi Zero with composite output
        // WARNING: Accept CONNECTED, UNKNOWN and even those without encoder_id connectors for software mode
        if (((con->connection == DRM_MODE_CONNECTED) || (con->connection == DRM_MODE_UNKNOWNCONNECTION)) && (con->count_modes > 0))
        {
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
            // For hardware rendering, an encoder_id is needed
            if (con->encoder_id)
            {
                TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected with encoder", i);
                platform.connector = con;
                break;
            }
            else TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected but no encoder", i);
#else
            // For software rendering, accept even without encoder_id
            TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i suitable for software rendering", i);
            platform.connector = con;
            break;
#endif
        }

        if (!platform.connector)
        {
            TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i NOT suitable (deleting)", i);
            drmModeFreeConnector(con);
        }
    }

    if (!platform.connector)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: No suitable DRM connector found");
        drmModeFreeResources(res);
        close(platform.fd);
        return -1;
    }

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    drmModeEncoder *enc = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);
    if (!enc)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode encoder");
        drmModeFreeConnector(platform.connector);
        drmModeFreeResources(res);
        close(platform.fd);
        return -1;
    }

    platform.crtc = drmModeGetCrtc(platform.fd, enc->crtc_id);
    if (!platform.crtc)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode crtc");
        drmModeFreeEncoder(enc);
        drmModeFreeConnector(platform.connector);
        drmModeFreeResources(res);
        close(platform.fd);
        return -1;
    }

    // If InitWindow should use the current mode find it in the connector's mode list
    if ((CORE.Window.screen.width <= 0) || (CORE.Window.screen.height <= 0))
    {
        TRACELOG(LOG_TRACE, "DISPLAY: Selecting DRM connector mode for current used mode...");

        platform.modeIndex = FindMatchingConnectorMode(platform.connector, &platform.crtc->mode);

        if (platform.modeIndex < 0)
        {
            TRACELOG(LOG_WARNING, "DISPLAY: No matching DRM connector mode found");
            drmModeFreeEncoder(enc);
            drmModeFreeConnector(platform.connector);
            drmModeFreeResources(res);
            close(platform.fd);
            return -1;
        }

        CORE.Window.screen.width = CORE.Window.display.width;
        CORE.Window.screen.height = CORE.Window.display.height;
    }

    const bool allowInterlaced = FLAG_IS_SET(CORE.Window.flags, FLAG_INTERLACED_HINT);
    const int fps = (CORE.Time.target > 0)? (1.0/CORE.Time.target) : 60;

    // Try to find an exact matching mode
    platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced);

    // If nothing found, try to find a nearly matching mode
    if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced);

    // If nothing found, try to find an exactly matching mode including interlaced
    if (platform.modeIndex < 0) platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true);

    // If nothing found, try to find a nearly matching mode including interlaced
    if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true);

    // If nothing found, there is no suitable mode
    if (platform.modeIndex < 0)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable DRM connector mode");
        drmModeFreeEncoder(enc);
        drmModeFreeConnector(platform.connector);
        drmModeFreeResources(res);
        close(platform.fd);
        return -1;
    }

    CORE.Window.display.width = platform.connector->modes[platform.modeIndex].hdisplay;
    CORE.Window.display.height = platform.connector->modes[platform.modeIndex].vdisplay;

    TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", platform.connector->modes[platform.modeIndex].name,
        platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay,
        FLAG_IS_SET(platform.connector->modes[platform.modeIndex].flags, DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
        platform.connector->modes[platform.modeIndex].vrefresh);

    drmModeFreeEncoder(enc);
    enc = NULL;
#else
    // For software rendering, the first available mode can be used
    if (platform.connector->count_modes > 0)
    {
        platform.modeIndex = 0;
        CORE.Window.display.width = platform.connector->modes[0].hdisplay;
        CORE.Window.display.height = platform.connector->modes[0].vdisplay;

        TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u) for software rendering",
                 platform.connector->modes[0].name,
                 platform.connector->modes[0].hdisplay,
                 platform.connector->modes[0].vdisplay,
                 (platform.connector->modes[0].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
                 platform.connector->modes[0].vrefresh);
    }
    else
    {
        TRACELOG(LOG_WARNING, "DISPLAY: No modes available for connector");
        drmModeFreeConnector(platform.connector);
        drmModeFreeResources(res);
        close(platform.fd);
        return -1;
    }
#endif

    // Use the width and height of the surface for render
    CORE.Window.render.width = CORE.Window.screen.width;
    CORE.Window.render.height = CORE.Window.screen.height;

    drmModeFreeResources(res);
    res = NULL;

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    // Hardware rendering initialization with EGL
    platform.gbmDevice = gbm_create_device(platform.fd);
    if (!platform.gbmDevice)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM device");
        return -1;
    }

    platform.gbmSurface = gbm_surface_create(platform.gbmDevice, platform.connector->modes[platform.modeIndex].hdisplay,
        platform.connector->modes[platform.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
    if (!platform.gbmSurface)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM surface");
        return -1;
    }

    EGLint samples = 0;
    EGLint sampleBuffer = 0;
    if (FLAG_IS_SET(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, (rlGetVersion() == RL_OPENGL_ES_30)? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT, // Type of context support
        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, 24,         // 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
    };

    EGLint numConfigs = 0;
    const char *eglClientExtensions = NULL;

    // Get an EGL device connection
    // NOTE: eglGetPlatformDisplay() is preferred over eglGetDisplay() legacy call
    platform.device = EGL_NO_DISPLAY;
#if defined(EGL_VERSION_1_5)
    platform.device = eglGetPlatformDisplay(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
#else
    // Check if extension is available for eglGetPlatformDisplayEXT()
    // NOTE: Better compatibility with some drivers (e.g. Mali Midgard)
    eglClientExtensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
    if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
    {
        PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");

        if (eglGetPlatformDisplayEXT != NULL) platform.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
    }

    // In case extension not found or display could not be retrieved, try using legacy version
    if (platform.device == EGL_NO_DISPLAY) platform.device = eglGetDisplay((EGLNativeDisplayType)platform.gbmDevice);
#endif
    if (platform.device == EGL_NO_DISPLAY)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
        return -1;
    }

    // Initialize the EGL device connection
    if (eglInitialize(platform.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 -1;
    }

    if (!eglChooseConfig(platform.device, NULL, NULL, 0, &numConfigs))
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config count: 0x%x", eglGetError());
        return -1;
    }

    TRACELOG(LOG_TRACE, "DISPLAY: EGL configs available: %d", numConfigs);

    EGLConfig *configs = (EGLConfig *)RL_CALLOC(numConfigs, sizeof(*configs));
    if (!configs)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to get memory for EGL configs");
        return -1;
    }

    EGLint matchingNumConfigs = 0;
    if (!eglChooseConfig(platform.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs))
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose EGL config: 0x%x", eglGetError());
        RL_FREE(configs);
        return -1;
    }

    TRACELOG(LOG_TRACE, "DISPLAY: EGL matching configs available: %d", matchingNumConfigs);

    // find the EGL config that matches the previously setup GBM format
    int found = 0;
    for (EGLint i = 0; i < matchingNumConfigs; i++)
    {
        EGLint id = 0;
        if (!eglGetConfigAttrib(platform.device, configs[i], EGL_NATIVE_VISUAL_ID, &id))
        {
            TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config attribute: 0x%x", eglGetError());
            continue;
        }

        if (GBM_FORMAT_ARGB8888 == id)
        {
            TRACELOG(LOG_TRACE, "DISPLAY: Using EGL config: %d", i);
            platform.config = configs[i];
            found = 1;
            break;
        }
    }

    RL_FREE(configs);

    if (!found)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable EGL config");
        return -1;
    }

    // Set rendering API
    eglBindAPI(EGL_OPENGL_ES_API);

    // Create an EGL rendering context
    platform.context = eglCreateContext(platform.device, platform.config, EGL_NO_CONTEXT, contextAttribs);
    if (platform.context == EGL_NO_CONTEXT)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context");
        return -1;
    }

    // Create an EGL window surface
    platform.surface = EGL_NO_SURFACE;

    if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
    {
        PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");

        if (eglCreatePlatformWindowSurfaceEXT != NULL) platform.surface = eglCreatePlatformWindowSurfaceEXT(platform.device, platform.config, platform.gbmSurface, NULL);
    }

    if (platform.surface == EGL_NO_SURFACE)
    {
        platform.surface = eglCreateWindowSurface(platform.device, platform.config, (EGLNativeWindowType)platform.gbmSurface, NULL);
    }

    if (platform.surface == EGL_NO_SURFACE)
    {
        TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL window surface: 0x%04x", eglGetError());
        return -1;
    }

    // At this point, manage render size vs screen size
    // NOTE: This function use and modify global module variables:
    //  -> CORE.Window.screen.width/CORE.Window.screen.height
    //  -> CORE.Window.render.width/CORE.Window.render.height
    //  -> CORE.Window.screenScale
    SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);

    // There must be at least one frame displayed before the buffers are swapped
    //eglSwapInterval(platform.device, 1);

    EGLBoolean result = eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context);

    // Check surface and context activation
    if (result != EGL_FALSE)
    {
        CORE.Window.ready = true;

        CORE.Window.render.width = CORE.Window.screen.width;
        CORE.Window.render.height = CORE.Window.screen.height;
        CORE.Window.currentFbo.width = CORE.Window.render.width;
        CORE.Window.currentFbo.height = CORE.Window.render.height;
    }
    else
    {
        TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphics device");
        return -1;
    }

    // Load OpenGL extensions
    // NOTE: GL procedures address loader is required to load extensions
    rlLoadExtensions(eglGetProcAddress);
#else
    // At this point, manage render size vs screen size
    // NOTE: This function use and modify global module variables:
    //  -> CORE.Window.screen.width/CORE.Window.screen.height
    //  -> CORE.Window.render.width/CORE.Window.render.height
    //  -> CORE.Window.screenScale
    SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);

    // Setup window ready state for software rendering
    CORE.Window.ready = true;

    CORE.Window.render.width = CORE.Window.screen.width;
    CORE.Window.render.height = CORE.Window.screen.height;
    CORE.Window.currentFbo.width = CORE.Window.render.width;
    CORE.Window.currentFbo.height = CORE.Window.render.height;
#endif

    TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
        FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
    TRACELOG(LOG_INFO, "    > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
    TRACELOG(LOG_INFO, "    > Screen size:  %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
    TRACELOG(LOG_INFO, "    > Render size:  %i x %i", CORE.Window.render.width, CORE.Window.render.height);
    TRACELOG(LOG_INFO, "    > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);

    if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) MinimizeWindow();

    // If graphic device is no properly initialized, end program
    if (!CORE.Window.ready)
    {
        TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device");
        return -1;
    }
    else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor())/2 - CORE.Window.screen.width/2, GetMonitorHeight(GetCurrentMonitor())/2 - CORE.Window.screen.height/2);

    // Set some default window flags
    FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN);       // false
    FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);    // false
    FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);      // true
    FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);    // false

    //----------------------------------------------------------------------------
    // Initialize timing system
    //----------------------------------------------------------------------------
    // NOTE: timing system must be initialized before the input events system
    InitTimer();
    //----------------------------------------------------------------------------

    // Initialize input events system
    //----------------------------------------------------------------------------
    InitEvdevInput();   // Evdev inputs initialization

#if SUPPORT_SSH_KEYBOARD_RPI
    InitKeyboard();     // Keyboard init (stdin)
#endif
    //----------------------------------------------------------------------------

    // Initialize storage system
    //----------------------------------------------------------------------------
    CORE.Storage.basePath = GetWorkingDirectory();
    //----------------------------------------------------------------------------

#if defined(SUPPORT_DRM_CACHE)
    if (InitSwapScreenBuffer() == 0)
    {
        TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
        return 0;
    }
    else
    {
        TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized failed");
        return -1;
    }
#else // !SUPPORT_DRM_CACHE
    TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
    return 0;
#endif
}

// Close platform
void ClosePlatform(void)
{
    if (platform.prevFB)
    {
        drmModeRmFB(platform.fd, platform.prevFB);
        platform.prevFB = 0;
    }

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    if (platform.prevBO)
    {
        gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO);
        platform.prevBO = NULL;
    }

    if (platform.gbmSurface)
    {
        gbm_surface_destroy(platform.gbmSurface);
        platform.gbmSurface = NULL;
    }

    if (platform.gbmDevice)
    {
        gbm_device_destroy(platform.gbmDevice);
        platform.gbmDevice = NULL;
    }
#endif

    if (platform.crtc)
    {
        if (platform.connector)
        {
            drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, platform.crtc->buffer_id,
                platform.crtc->x, platform.crtc->y, &platform.connector->connector_id, 1, &platform.crtc->mode);
            drmModeFreeConnector(platform.connector);
            platform.connector = NULL;
        }

        drmModeFreeCrtc(platform.crtc);
        platform.crtc = NULL;
    }

    if (platform.fd != -1)
    {
        close(platform.fd);
        platform.fd = -1;
    }

#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
    // Close surface, context and display
    if (platform.device != EGL_NO_DISPLAY)
    {
        if (platform.surface != EGL_NO_SURFACE)
        {
            eglDestroySurface(platform.device, platform.surface);
            platform.surface = EGL_NO_SURFACE;
        }

        if (platform.context != EGL_NO_CONTEXT)
        {
            eglDestroyContext(platform.device, platform.context);
            platform.context = EGL_NO_CONTEXT;
        }

        eglTerminate(platform.device);
        platform.device = EGL_NO_DISPLAY;
    }
#endif

    CORE.Window.shouldClose = true;   // Added to force threads to exit when the close window is called

    // Close the evdev devices

    if (platform.mouseFd != -1)
    {
        close(platform.mouseFd);
        platform.mouseFd = -1;
    }

    for (int i = 0; i < platform.gamepadCount; i++)
    {
        close(platform.gamepadStreamFd[i]);
        platform.gamepadStreamFd[i] = -1;
    }

    if (platform.keyboardFd != -1)
    {
        close(platform.keyboardFd);
        platform.keyboardFd = -1;
    }
}

#if SUPPORT_SSH_KEYBOARD_RPI
// Initialize Keyboard system (using standard input)
static void InitKeyboard(void)
{
    // NOTE: Read directly from Standard Input (stdin) - STDIN_FILENO file descriptor,
    // Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE

    // Save terminal keyboard settings
    tcgetattr(STDIN_FILENO, &platform.defaultSettings);

    // Reconfigure terminal with new settings
    struct termios keyboardNewSettings = { 0 };
    keyboardNewSettings = platform.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
    FLAG_CLEAR(keyboardNewSettings.c_lflag, ICANON | ECHO | ISIG);
    //FLAG_CLEAR(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);

    // Save old keyboard mode to restore it at the end
    platform.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0);          // F_GETFL: Get the file access mode and the file status flags
    fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified

    // NOTE: If ioctl() returns -1, it means the call failed for some reason (error code set in errno)
    int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode);

    // In case of failure, it could mean a remote keyboard is used (SSH)
    if (result < 0) TRACELOG(LOG_WARNING, "DRM: Failed to change keyboard mode, an SSH keyboard is probably used");
    else
    {
        // 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);  // ASCII chars
    }

    // Register keyboard restore when program finishes
    atexit(RestoreKeyboard);
}

// Restore default keyboard input
static void RestoreKeyboard(void)
{
    // Reset to default keyboard settings
    tcsetattr(STDIN_FILENO, TCSANOW, &platform.defaultSettings);

    // Reconfigure keyboard to default mode
    fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags);
    ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode);
}

// Process keyboard inputs
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] = { 0 };    // 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 < MAX_KEYBOARD_KEYS; i++)
    {
        CORE.Input.Keyboard.currentKeyState[i] = 0;
        CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
    }

    // 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)
        {
            // Check if ESCAPE key has been pressed 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] = 259;     // 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++;
        }
    }
}
#endif // SUPPORT_SSH_KEYBOARD_RPI

// Initialize user input from evdev(/dev/input/event<N>)
// this means mouse, keyboard or gamepad devices
static void InitEvdevInput(void)
{
    char path[MAX_FILEPATH_LENGTH] = { 0 };
    DIR *directory = NULL;
    struct dirent *entity = NULL;

    // Initialize keyboard file descriptor
    platform.keyboardFd = -1;
    platform.mouseFd = -1;

    // 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;
        platform.touchActive[i] = false;
        platform.touchPosition[i].x = -1;
        platform.touchPosition[i].y = -1;
        platform.touchId[i] = -1;
    }

    // Initialize touch slot
    platform.touchSlot = 0;

    // Reset keyboard key state
    for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
    {
        CORE.Input.Keyboard.currentKeyState[i] = 0;
        CORE.Input.Keyboard.keyRepeatInFrame[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*"
                (strncmp("mouse", entity->d_name, strlen("mouse")) == 0))       // Search for devices named "mouse*"
            {
                snprintf(path, MAX_FILEPATH_LENGTH, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name);
                ConfigureEvdevDevice(path);                                     // Configure the device if appropriate
            }
        }

        closedir(directory);
    }
    else TRACELOG(LOG_WARNING, "INPUT: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH);
}

// Identifies a input device and configures it for use if appropriate
static void ConfigureEvdevDevice(char *device)
{
    #define BITS_PER_LONG   (8*sizeof(long))
    #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)

    unsigned long evBits[NBITS(EV_MAX)] = { 0 };
    unsigned long absBits[NBITS(ABS_MAX)] = { 0 };
    unsigned long relBits[NBITS(REL_MAX)] = { 0 };
    unsigned long keyBits[NBITS(KEY_MAX)] = { 0 };

    // Open the device
    int fd = open(device, O_RDONLY | O_NONBLOCK);
    if (fd < 0)
    {
        TRACELOG(LOG_WARNING, "SYSTEM: Failed to open input device: %s", device);
        return;
    }

    // At this point, a connection to the device has been stablished, but still left to know what the device is,
    // it could be many things, even as simple as a power button...
    //-------------------------------------------------------------------------------------------------------

    // Identify the device
    //-------------------------------------------------------------------------------------------------------
    struct {
        bool exist;
        struct input_absinfo info;
    } absinfo[ABS_CNT] = { 0 };

    // These flags aren't really a one of
    // Some devices could have properties associated with keyboards
    // as well as properties associated with mice
    bool isKeyboard = false;
    bool isMouse = false;
    bool isTouch = false;
    bool isGamepad = false;

    int absAxisCount = 0;

    ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits);
    ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits);

    if (TEST_BIT(evBits, EV_ABS))
    {
        ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits);

        // If the device has an X an Y axis it's either a touch device, a special mouse or a gamepad
        bool hasAbsXY = TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y);

        if (hasAbsXY)
        {
            absAxisCount += 2;

            absinfo[ABS_X].exist = true;
            absinfo[ABS_Y].exist = true;

            ioctl(fd, EVIOCGABS(ABS_X), &absinfo[ABS_X].info);
            ioctl(fd, EVIOCGABS(ABS_Y), &absinfo[ABS_Y].info);
        }

        // If it has any of these buttons it's a touch device
        if (hasAbsXY &&
           (TEST_BIT(keyBits, BTN_STYLUS) ||
            TEST_BIT(keyBits, BTN_TOOL_PEN) ||
            TEST_BIT(keyBits, BTN_TOOL_FINGER) ||
            TEST_BIT(keyBits, BTN_TOUCH))) isTouch = true;

        // Absolute mice should really only exist with VMWare
        else if (hasAbsXY && TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;

        // If any of the common joystick axes are present, assume it's a gamepad
        else
        {
            for (int axis = (hasAbsXY? ABS_Z : ABS_X); axis < ABS_PRESSURE; axis++)
            {
                if (TEST_BIT(absBits, axis))
                {
                    absinfo[axis].exist = true;
                    isGamepad = true;
                    absAxisCount++;

                    ioctl(fd, EVIOCGABS(axis), &absinfo[axis].info);
                }
            }
        }

        // If the device has multitouch axes, it's a touch device
        if (TEST_BIT(absBits, ABS_MT_POSITION_X) &&
            TEST_BIT(absBits, ABS_MT_POSITION_Y)) isTouch = true;
    }

    if (TEST_BIT(evBits, EV_REL))
    {
        ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits);

        // If it has any of the gamepad or touch features tested so far, it's not a mouse
        if (!isTouch &&
            !isGamepad &&
            TEST_BIT(relBits, REL_X) &&
            TEST_BIT(relBits, REL_Y) &&
            TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;
    }

    if (TEST_BIT(evBits, EV_KEY))
    {
        // The first 32 keys as defined in input-event-codes.h are pretty much
        // exclusive to keyboards, so they can be tested using a mask
        // Leave out the first bit to not test KEY_RESERVED
        const unsigned long mask = 0xFFFFFFFE;
        if ((keyBits[0] & mask) == mask) isKeyboard = true;

        // If any of the common gamepad buttons is found, assume it's a gamepad
        else
        {
            for (int button = BTN_JOYSTICK; button < BTN_DIGI; ++button)
            {
                if (TEST_BIT(keyBits, button)) isGamepad = true;
            }

            for (int button = BTN_TRIGGER_HAPPY1; button <= BTN_TRIGGER_HAPPY40; button++)
            {
                if (TEST_BIT(keyBits, button)) isGamepad = true;
            }
        }
    }

    const char *deviceKindStr = "unknown";
    if (isMouse || isTouch)
    {
        bool prioritize = false;

        // Priority logic: touchscreens override Mice
        // 1. No device set yet? Take it
        if (platform.mouseFd == -1) prioritize = true;
        // 2. Current is mouse, new is touch? Upgrade to touch
        else if (isTouch && !platform.mouseIsTouch) prioritize = true;
        // 3. Current is touch, new is touch? Use the new one (last one found wins, standard behavior)
        else if (isTouch && platform.mouseIsTouch) prioritize = true;
        // 4. Current is mouse, new is mouse? Use the new one
        else if (!isTouch && !platform.mouseIsTouch) prioritize = true;
        // 5. Current is touch, new is mouse? Ignore the mouse, keep the touchscreen
        else prioritize = false;

        if (prioritize)
        {
            deviceKindStr = isTouch? "touchscreen" : "mouse";

            if (platform.mouseFd != -1)
            {
                TRACELOG(LOG_INFO, "INPUT: Overwriting previous input device with new %s", deviceKindStr);
                close(platform.mouseFd);
            }

            platform.mouseFd = fd;
            platform.mouseIsTouch = isTouch;

            if (absAxisCount > 0)
            {
                platform.absRange.x = absinfo[ABS_X].info.minimum;
                platform.absRange.width = absinfo[ABS_X].info.maximum - absinfo[ABS_X].info.minimum;

                platform.absRange.y = absinfo[ABS_Y].info.minimum;
                platform.absRange.height = absinfo[ABS_Y].info.maximum - absinfo[ABS_Y].info.minimum;
            }

            TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
        }
        else
        {
            TRACELOG(LOG_INFO, "INPUT: Ignoring device %s (keeping higher priority %s device)", device, platform.mouseIsTouch ? "touchscreen" : "mouse");
            close(fd);
            return;
        }
    }
    else if (isGamepad && !isMouse && !isKeyboard && (platform.gamepadCount < MAX_GAMEPADS))
    {
        deviceKindStr = "gamepad";
        int index = platform.gamepadCount++;

        platform.gamepadStreamFd[index] = fd;
        CORE.Input.Gamepad.ready[index] = true;

        ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]);
        CORE.Input.Gamepad.axisCount[index] = absAxisCount;

        if (absAxisCount > 0)
        {
            // TODO: Review GamepadAxis enum matching
            // So gamepad axes (as in the actual linux joydev.c) are simply enumerated
            // and (at least for some input drivers like xpat) it's convention to use
            // ABS_X, ABX_Y for one joystick ABS_RX, ABS_RY for the other and the Z axes for the shoulder buttons
            // If these are now enumerated, it results to LJOY_X, LJOY_Y, LEFT_SHOULDERB, RJOY_X, ...
            int axisIndex = 0;
            for (int axis = ABS_X; axis < ABS_PRESSURE; axis++)
            {
                if (absinfo[axis].exist)
                {
                    platform.gamepadAbsAxisRange[index][axisIndex][0] = absinfo[axisIndex].info.minimum;
                    platform.gamepadAbsAxisRange[index][axisIndex][1] = absinfo[axisIndex].info.maximum - absinfo[axisIndex].info.minimum;

                    platform.gamepadAbsAxisMap[index][axis] = axisIndex;
                    axisIndex++;
                }
            }
        }
    }
    else if (isKeyboard && (platform.keyboardFd == -1))
    {
        deviceKindStr = "keyboard";
        platform.keyboardFd = fd;
    }
    else
    {
        close(fd);
        return;
    }

    TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
}

// Poll and process evdev keyboard events
static void PollKeyboardEvents(void)
{
    int fd = platform.keyboardFd;
    if (fd == -1) return;

    struct input_event event = { 0 };
    int keycode = -1;

    // Try to read data from the keyboard and only continue if successful
    while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
    {
        // Check if the event is a key event
        if (event.type != EV_KEY) continue;

#if SUPPORT_SSH_KEYBOARD_RPI
        // If the event was a key, assume a working keyboard is connected, so disable the SSH keyboard
        platform.eventKeyboardMode = true;
#endif
        // Keyboard keys appear for codes 1 to 255, ignore everthing else
        if ((event.code >= 1) && (event.code <= 255))
        {
            // Lookup the scancode in the keymap to get a keycode
            keycode = linuxToRaylibMap[event.code];

            // Make sure a valid keycode is obtained
            if ((keycode > 0) && (keycode < MAX_KEYBOARD_KEYS))
            {
                // WARNING: https://www.kernel.org/doc/Documentation/input/input.txt
                // Event interface: 'value' is the value the event carries. Either a relative change for EV_REL,
                // absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat
                CORE.Input.Keyboard.currentKeyState[keycode] = (event.value >= 1);
                CORE.Input.Keyboard.keyRepeatInFrame[keycode] = (event.value == 2);

                // If the key is pressed add it to the queues
                if (event.value == 1)
                {
                    if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
                    {
                        CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode;
                        CORE.Input.Keyboard.keyPressedQueueCount++;
                    }

                    if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
                    {
                        // TODO/FIXME: This is not actually converting to unicode properly because it's not taking things like shift into account
                        CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = evkeyToUnicodeLUT[event.code];
                        CORE.Input.Keyboard.charPressedQueueCount++;
                    }
                }

                TRACELOG(LOG_DEBUG, "INPUT: KEY_%s Keycode(linux): %4i KeyCode(raylib): %4i", (event.value == 0)? "UP  " : "DOWN", event.code, keycode);
            }
        }
    }
}

// Poll gamepad input events
static void PollGamepadEvents(void)
{
    // Read gamepad event
    struct input_event event = { 0 };

    for (int i = 0; i < platform.gamepadCount; i++)
    {
        if (!CORE.Input.Gamepad.ready[i]) continue;

        // Register previous gamepad states
        for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];

        while (read(platform.gamepadStreamFd[i], &event, sizeof(event)) == (int)sizeof(event))
        {
            if (event.type == EV_KEY)
            {
                if (event.code < KEYMAP_SIZE)
                {
                    short keycode = linuxToRaylibMap[event.code]; // raylib keycode

                    TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: KEY_%s Keycode(linux): %4i Keycode(raylib): %4i", i, (event.value == 0)? "UP" : "DOWN", event.code, keycode);

                    if ((keycode != 0) && (keycode < MAX_GAMEPAD_BUTTONS))
                    {
                        // 1 - button pressed, 0 - button released
                        CORE.Input.Gamepad.currentButtonState[i][keycode] = event.value;
                        CORE.Input.Gamepad.lastButtonPressed = (event.value == 1)? keycode : GAMEPAD_BUTTON_UNKNOWN;
                    }
                }
            }
            else if (event.type == EV_ABS)
            {
                if (event.code < ABS_CNT)
                {
                    int axisRaylib = platform.gamepadAbsAxisMap[i][event.code];

                    TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: Axis: %2i Value: %i", i, axisRaylib, event.value);

                    if (axisRaylib < MAX_GAMEPAD_AXES)
                    {
                        int min = platform.gamepadAbsAxisRange[i][event.code][0];
                        int range = platform.gamepadAbsAxisRange[i][event.code][1];

                        // NOTE: Scaling of event.value to get values between -1..1
                        CORE.Input.Gamepad.axisState[i][axisRaylib] = (2*(float)(event.value - min)/range) - 1;
                    }
                }
            }
        }
    }
}

// Poll mouse input events
static void PollMouseEvents(void)
{
    int fd = platform.mouseFd;
    if (fd == -1) return;

    struct input_event event = { 0 };
    int touchAction = -1;           // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE
    static bool isMultitouch = false; // Detect if device supports MT events

    // Try to read data from the mouse/touch/gesture and only continue if successful
    while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
    {
        // Relative movement parsing
        if (event.type == EV_REL)
        {
            if (event.code == REL_X)
            {
                if (platform.cursorRelative)
                {
                    CORE.Input.Mouse.currentPosition.x = event.value;
                    CORE.Input.Mouse.previousPosition.x = 0.0f;
                }
                else CORE.Input.Mouse.currentPosition.x += event.value;

                // NOTE: For DRM touchscreen, do not simulate touch from mouse movement
                // CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x;
                touchAction = 2;    // TOUCH_ACTION_MOVE
            }

            if (event.code == REL_Y)
            {
                if (platform.cursorRelative)
                {
                    CORE.Input.Mouse.currentPosition.y = event.value;
                    CORE.Input.Mouse.previousPosition.y = 0.0f;
                }
                else CORE.Input.Mouse.currentPosition.y += event.value;

                // NOTE: For DRM touchscreen, do not simulate touch from mouse movement
                // CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y;
                touchAction = 2;    // TOUCH_ACTION_MOVE
            }

            if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value;
        }

        // Absolute movement parsing
        if (event.type == EV_ABS)
        {
            // Basic movement
            if (event.code == ABS_X)
            {
                CORE.Input.Mouse.currentPosition.x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;    // Scale according to absRange

                // Update single touch position only if it's active and no MT events are being used
                if (platform.touchActive[0] && !isMultitouch)
                {
                    platform.touchPosition[0].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
                    if (touchAction == -1) touchAction = 2;    // TOUCH_ACTION_MOVE
                }
            }

            if (event.code == ABS_Y)
            {
                CORE.Input.Mouse.currentPosition.y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;  // Scale according to absRange

                // Update single touch position only if it's active and no MT events are being used
                if (platform.touchActive[0] && !isMultitouch)
                {
                    platform.touchPosition[0].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
                    if (touchAction == -1) touchAction = 2;    // TOUCH_ACTION_MOVE
                }
            }

            // Multitouch movement
            if (event.code == ABS_MT_SLOT)
            {
                platform.touchSlot = event.value;
                isMultitouch = true;
            }

            if (event.code == ABS_MT_POSITION_X)
            {
                isMultitouch = true;
                if (platform.touchSlot < MAX_TOUCH_POINTS)
                {
                    platform.touchPosition[platform.touchSlot].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;

                    // If this slot is active, it's a move; If not, update the buffer for when it becomes active
                    // Only set to MOVE if a DOWN or UP event has not been detected this frame
                    if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2;    // TOUCH_ACTION_MOVE
                }
            }

            if (event.code == ABS_MT_POSITION_Y)
            {
                if (platform.touchSlot < MAX_TOUCH_POINTS)
                {
                    platform.touchPosition[platform.touchSlot].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;

                    // If this slot is active, it's a move; If not, update the buffer for when it becomes active
                    // Only set to MOVE if a DOWN or UP event have not been detected this frame
                    if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2;    // TOUCH_ACTION_MOVE
                }
            }

            if (event.code == ABS_MT_TRACKING_ID)
            {
                if (platform.touchSlot < MAX_TOUCH_POINTS)
                {
                    if (event.value >= 0)
                    {

                        platform.touchActive[platform.touchSlot] = true;
                        platform.touchId[platform.touchSlot] = event.value; // Use Tracking ID for unique IDs

                        touchAction = 1; // TOUCH_ACTION_DOWN
                    }
                    else
                    {
                        // Touch has ended for this point
                        platform.touchActive[platform.touchSlot] = false;
                        platform.touchPosition[platform.touchSlot].x = -1;
                        platform.touchPosition[platform.touchSlot].y = -1;
                        platform.touchId[platform.touchSlot] = -1;

                        // Force UP action if DOWN action has not already been set
                        // (DOWN takes priority over UP if both happen in one frame, though rare)
                        if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
                    }
                }
            }

            // Handle ABS_MT_PRESSURE (0x3a) if available, as some devices use it for lift-off
            #ifndef ABS_MT_PRESSURE
                #define ABS_MT_PRESSURE 0x3a
            #endif
            if (event.code == ABS_MT_PRESSURE)
            {
                if (platform.touchSlot < MAX_TOUCH_POINTS)
                {
                    if (event.value <= 0) // Pressure 0 means lift
                    {
                        platform.touchActive[platform.touchSlot] = false;
                        platform.touchPosition[platform.touchSlot].x = -1;
                        platform.touchPosition[platform.touchSlot].y = -1;
                        platform.touchId[platform.touchSlot] = -1;
                        if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
                    }
                }
            }

            // Touchscreen tap
            if (event.code == ABS_PRESSURE)
            {
                int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT];

                if (!event.value && previousMouseLeftButtonState)
                {
                    platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0;
                    if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
                }

                if (event.value && !previousMouseLeftButtonState)
                {
                    platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1;
                    touchAction = 1; // TOUCH_ACTION_DOWN
                }
            }
        }

        // Button parsing
        if (event.type == EV_KEY)
        {
            // Mouse button parsing
            if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT))
            {
                platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value;

                if (event.value > 0)
                {
                    bool activateSlot0 = false;

                    if (event.code == BTN_LEFT) activateSlot0 = true; // Mouse click always activates
                    else if (event.code == BTN_TOUCH)
                    {
                        bool anyActive = false;
                        for (int i = 0; i < MAX_TOUCH_POINTS; i++)
                        {
                            if (platform.touchActive[i]) { anyActive = true; break; }
                        }

                        if (!anyActive) activateSlot0 = true;
                    }

                    if (activateSlot0)
                    {
                        platform.touchActive[0] = true;
                        platform.touchId[0] = 0;
                    }

                    touchAction = 1; // TOUCH_ACTION_DOWN
                }
                else
                {
                    // Only clear touch 0 for actual mouse clicks (BTN_LEFT)
                    if (event.code == BTN_LEFT)
                    {
                        platform.touchActive[0] = false;
                        platform.touchPosition[0].x = -1;
                        platform.touchPosition[0].y = -1;
                    }
                    else if (event.code == BTN_TOUCH) platform.touchSlot = 0;            // Reset slot index to 0

                    touchAction = 0;       // TOUCH_ACTION_UP
                }
            }

            if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value;
            if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value;
            if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value;
            if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value;
            if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value;
            if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value;
        }

        // Screen confinement
        if (!CORE.Input.Mouse.cursorLocked)
        {
            if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0;
            if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x)
                CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x;

            if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0;
            if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y)
                CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y;
        }

        // Repack active touches into CORE.Input.Touch
        int k = 0;
        for (int i = 0; i < MAX_TOUCH_POINTS; i++)
        {
            if (platform.touchActive[i])
            {
                CORE.Input.Touch.position[k] = platform.touchPosition[i];
                CORE.Input.Touch.pointId[k] = platform.touchId[i];
                k++;
            }
        }

        CORE.Input.Touch.pointCount = k;

        // Clear remaining slots
        for (int i = k; i < MAX_TOUCH_POINTS; i++)
        {
            CORE.Input.Touch.position[i].x = -1;
            CORE.Input.Touch.position[i].y = -1;
            CORE.Input.Touch.pointId[i] = -1;
        }

#if SUPPORT_GESTURES_SYSTEM
        if (touchAction > -1)
        {
            GestureEvent gestureEvent = { 0 };
            gestureEvent.touchAction = touchAction;
            gestureEvent.pointCount = CORE.Input.Touch.pointCount;

            for (int i = 0; i < MAX_TOUCH_POINTS; i++)
            {
                gestureEvent.pointId[i] = i;
                gestureEvent.position[i] = CORE.Input.Touch.position[i];
            }

            ProcessGestureEvent(gestureEvent);
            touchAction = -1;
        }
#endif
    }
}

// Search matching DRM mode in connector's mode list
static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode)
{
    if (NULL == connector) return -1;
    if (NULL == mode) return -1;

    // safe bitwise comparison of two modes
    #define BINCMP(a, b) memcmp((a), (b), (sizeof(a) < sizeof(b))? sizeof(a) : sizeof(b))

    for (size_t i = 0; i < connector->count_modes; i++)
    {
        TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, connector->modes[i].hdisplay, connector->modes[i].vdisplay,
            connector->modes[i].vrefresh, (FLAG_IS_SET(connector->modes[i].flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");

        if (0 == BINCMP(&platform.crtc->mode, &platform.connector->modes[i])) return i;
    }

    return -1;

    #undef BINCMP
}

// Search exactly matching DRM connector mode in connector's list
static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
{
    TRACELOG(LOG_TRACE, "DISPLAY: Searching exact connector mode for %ux%u@%u, selecting an interlaced mode is allowed: %s", width, height, fps, allowInterlaced? "yes" : "no");

    if (NULL == connector) return -1;

    for (int i = 0; i < platform.connector->count_modes; i++)
    {
        const drmModeModeInfo *const mode = &platform.connector->modes[i];

        TRACELOG(LOG_TRACE, "DISPLAY: DRM Mode %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh, (FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");

        if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced) continue;

        if ((mode->hdisplay == width) && (mode->vdisplay == height) && (mode->vrefresh == fps)) return i;
    }

    TRACELOG(LOG_TRACE, "DISPLAY: No DRM exact matching mode found");
    return -1;
}

// Search the nearest matching DRM connector mode in connector's list
static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
{
    TRACELOG(LOG_TRACE, "DISPLAY: Searching nearest connector mode for %ux%u@%u, selecting an interlaced mode is allowed: %s", width, height, fps, allowInterlaced? "yes" : "no");

    if (NULL == connector) return -1;

    int nearestIndex = -1;
    int minUnusedPixels = INT_MAX;
    int minFpsDiff = INT_MAX;
    for (int i = 0; i < platform.connector->count_modes; i++)
    {
        const drmModeModeInfo *const mode = &platform.connector->modes[i];

        TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh,
            (FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");

        if ((mode->hdisplay < width) || (mode->vdisplay < height))
        {
            TRACELOG(LOG_TRACE, "DISPLAY: DRM mode is too small");
            continue;
        }

        if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced)
        {
            TRACELOG(LOG_TRACE, "DISPLAY: DRM shouldn't choose an interlaced mode");
            continue;
        }

        const int unusedPixels = (mode->hdisplay - width)*(mode->vdisplay - height);
        const int fpsDiff = mode->vrefresh - fps;

        if ((unusedPixels < minUnusedPixels) ||
            ((unusedPixels == minUnusedPixels) && (abs(fpsDiff) < abs(minFpsDiff))) ||
            ((unusedPixels == minUnusedPixels) && (abs(fpsDiff) == abs(minFpsDiff)) && (fpsDiff > 0)))
        {
            nearestIndex = i;
            minUnusedPixels = unusedPixels;
            minFpsDiff = fpsDiff;
        }
    }

    return nearestIndex;
}

// 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, using 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: Rendering to full display resolution,
        // 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);

        if ((CORE.Window.screen.width == 0) || (CORE.Window.screen.height == 0))
        {
            CORE.Window.screen.width = CORE.Window.display.width;
            CORE.Window.screen.height = 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;
    }
}

// EOF