fyrox-impl 1.0.1

Feature-rich, easy-to-use, 2D/3D game engine with a scene editor. Like Godot, but in Rust.
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
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! Engine is container for all subsystems (renderer, ui, sound, resource manager). It also
//! creates a window and an OpenGL context.

#![warn(missing_docs)]

pub mod error;
pub mod executor;
pub mod input;
pub mod task;

mod hotreload;
mod wasm_utils;

use crate::plugin::error::{GameError, GameResult};
use crate::{
    asset::{
        event::ResourceEvent,
        manager::{ResourceManager, ResourceWaitContext},
        state::ResourceState,
        untyped::ResourceKind,
    },
    core::{
        algebra::Vector2,
        err,
        futures::{executor::block_on, future::join_all},
        instant,
        log::Log,
        pool::Handle,
        reflect::Reflect,
        task::TaskPool,
        warn, SafeLock,
    },
    engine::{error::EngineError, input::InputState, task::TaskPoolHandler},
    event::Event,
    graph::SceneGraph,
    graphics::error::FrameworkError,
    gui::{
        constructor::WidgetConstructorContainer,
        font::{
            loader::FontLoader, Font, BOLD_ITALIC, BUILT_IN_BOLD, BUILT_IN_FONT, BUILT_IN_ITALIC,
        },
        loader::UserInterfaceLoader,
        style::{self, resource::StyleLoader, Style},
        RenderMode, UiContainer, UiUpdateSwitches, UserInterface,
    },
    material::{
        self,
        loader::MaterialLoader,
        shader::{loader::ShaderLoader, Shader, ShaderResource, ShaderResourceExtension},
        Material,
    },
    plugin::{
        dylib::DyLibDynamicPlugin, DynamicPlugin, Plugin, PluginContainer, PluginContext,
        PluginRegistrationContext,
    },
    renderer::{ui_renderer::UiRenderInfo, Renderer},
    resource::{
        curve::{loader::CurveLoader, CurveResourceState},
        gltf::material::GLTF_SHADER,
        model::{loader::ModelLoader, Model, ModelResource},
        texture::{
            self, loader::TextureLoader, CompressionOptions, Texture, TextureImportOptions,
            TextureKind, TextureMinificationFilter, TextureResource, TextureResourceExtension,
        },
    },
    scene::{
        base::NodeScriptMessage,
        graph::GraphUpdateSwitches,
        mesh::surface::{self, SurfaceData, SurfaceDataLoader},
        node::{
            constructor::{new_node_constructor_container, NodeConstructorContainer},
            Node,
        },
        skybox::SkyBoxKind,
        sound::SoundEngine,
        tilemap::{
            brush::{TileMapBrush, TileMapBrushLoader},
            tileset::{TileSet, TileSetLoader},
            CustomTileCollider, TileMapData,
        },
        Scene, SceneContainer,
    },
    script::{
        constructor::ScriptConstructorContainer, DynamicTypeId, PluginsRefMut, RoutingStrategy,
        Script, ScriptContext, ScriptDeinitContext, ScriptMessage, ScriptMessageContext,
        ScriptMessageKind, ScriptMessageSender, UniversalScriptContext,
    },
    window::Window,
};
use fxhash::{FxHashMap, FxHashSet};
use fyrox_animation::AnimationTracksData;
use fyrox_core::dyntype::DynTypeConstructorContainer;
use fyrox_core::NameProvider;
use fyrox_graphics::server::SharedGraphicsServer;
use fyrox_graphics_gl::server::GlGraphicsServer;
use fyrox_sound::{
    buffer::{loader::SoundBufferLoader, SoundBuffer},
    renderer::hrtf::{HrirSphereLoader, HrirSphereResourceData},
};
use std::{
    any::TypeId,
    cell::Cell,
    collections::{HashSet, VecDeque},
    fmt::{Display, Formatter},
    io::Cursor,
    ops::{Deref, DerefMut},
    path::Path,
    rc::Rc,
    sync::{
        mpsc::{channel, Receiver},
        Arc,
    },
    time::Duration,
};
use uuid::Uuid;
use winit::event::{DeviceEvent, ElementState, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::{
    dpi::{Position, Size},
    window::Icon,
    window::WindowAttributes,
};

/// Serialization context holds runtime type information that allows to create unknown types using
/// their UUIDs and a respective constructors.
pub struct SerializationContext {
    /// A node constructor container.
    pub node_constructors: NodeConstructorContainer,
    /// A script constructor container.
    pub script_constructors: ScriptConstructorContainer,
}

impl Default for SerializationContext {
    fn default() -> Self {
        Self::new()
    }
}

impl SerializationContext {
    /// Creates default serialization context.
    pub fn new() -> Self {
        Self {
            node_constructors: new_node_constructor_container(),
            script_constructors: ScriptConstructorContainer::new(),
        }
    }
}

/// Performance statistics.
#[derive(Debug, Default)]
pub struct PerformanceStatistics {
    /// Amount of time spent in the UI system.
    pub ui_time: Duration,

    /// Amount of time spent in updating/initializing/destructing scripts of all scenes.
    pub scripts_time: Duration,

    /// Amount of time spent in plugins updating.
    pub plugins_time: Duration,
}

impl Display for PerformanceStatistics {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "Performance Statistics:\n\tUI: {:?}\n\tScripts: {:?}\n\tPlugins: {:?}",
            self.ui_time, self.scripts_time, self.plugins_time
        )
    }
}

/// An initialized graphics context. It contains the main application window and the renderer instance.
pub struct InitializedGraphicsContext {
    /// Main application window.
    pub window: Window,

    /// Current renderer.
    pub renderer: Renderer,

    params: GraphicsContextParams,
}

impl InitializedGraphicsContext {
    /// Tries to set a new icon for the window from the given data source. The data source must contain
    /// some of the supported texture types data (png, bmp, jpg images). You can call this method
    /// with [`include_bytes`] macro to pass file's data directly.
    pub fn set_window_icon_from_memory(&mut self, data: &[u8]) {
        if let Ok(texture) = TextureResource::load_from_memory(
            Uuid::new_v4(),
            ResourceKind::Embedded,
            data,
            TextureImportOptions::default()
                .with_compression(CompressionOptions::NoCompression)
                .with_minification_filter(TextureMinificationFilter::Linear),
        ) {
            self.set_window_icon_from_texture(&texture);
        }
    }

    /// Tries to set a new icon for the window using the given texture.
    pub fn set_window_icon_from_texture(&mut self, texture: &TextureResource) {
        let data = texture.data_ref();
        if let TextureKind::Rectangle { width, height } = data.kind() {
            if let Ok(img) = Icon::from_rgba(data.data().to_vec(), width, height) {
                self.window.set_window_icon(Some(img));
            }
        }
    }
}

/// Graphics context of the engine, it could be in two main states:
///
/// - [`GraphicsContext::Initialized`] - active graphics context, that is fully initialized and ready for use.
/// - [`GraphicsContext::Uninitialized`] - suspended graphics context, that contains a set of params that could
/// be used for further initialization.
///
/// By default, when you creating an engine, there's no graphics context initialized. It must be initialized
/// manually (if you need it) on [`Event::Resumed`]. On most operating systems, it is possible to initialize
/// graphics context right after the engine was created. However Android won't allow you to do this, also on
/// some versions of macOS immediate initialization could lead to panic.
///
/// You can switch between these states whenever you need, for example if your application does not need a
/// window and a renderer at all you can just not create graphics context. This could be useful for game
/// servers or background applications. When you destroy a graphics context, the engine will remember the options
/// with which it was created and some of the main window parameters (position, size, etc.) and will re-use these
/// parameters on a next initialization attempt.
#[allow(clippy::large_enum_variant)]
pub enum GraphicsContext {
    /// Fully initialized graphics context. See [`InitializedGraphicsContext`] docs for more info.
    Initialized(InitializedGraphicsContext),

    /// Uninitialized (suspended) graphics context. See [`GraphicsContextParams`] docs for more info.
    Uninitialized(GraphicsContextParams),
}

impl GraphicsContext {
    /// Attempts to cast a graphics context to its initialized version. The method will panic if the context
    /// is not initialized.
    pub fn as_initialized_ref(&self) -> &InitializedGraphicsContext {
        if let GraphicsContext::Initialized(ctx) = self {
            ctx
        } else {
            panic!("Graphics context is uninitialized!")
        }
    }

    /// Attempts to cast a graphics context to its initialized version. The method will panic if the context
    /// is not initialized.
    pub fn as_initialized_mut(&mut self) -> &mut InitializedGraphicsContext {
        if let GraphicsContext::Initialized(ctx) = self {
            ctx
        } else {
            panic!("Graphics context is uninitialized!")
        }
    }
}

pub(crate) enum GameErrorSource {
    PluginMethod(&'static str),
    ScriptMethod {
        scene_handle: Handle<Scene>,
        node_handle: Handle<Node>,
        method_name: &'static str,
    },
}

pub(crate) struct GameErrorContainer {
    source: GameErrorSource,
    error: GameError,
}

type ErrorQueue = VecDeque<GameErrorContainer>;

/// See module docs.
pub struct Engine {
    /// Graphics context of the engine. See [`GraphicsContext`] docs for more info.
    pub graphics_context: GraphicsContext,

    /// Current resource manager. Resource manager can be cloned (it does clone only ref) to be able to
    /// use resource manager from any thread, this is useful to load resources from multiple
    /// threads to decrease loading times of your game by utilizing all available power of
    /// your CPU.
    pub resource_manager: ResourceManager,

    /// All available user interfaces in the engine.
    pub user_interfaces: UiContainer,

    /// All available scenes in the engine.
    pub scenes: SceneContainer,

    /// Task pool for asynchronous task management.
    pub task_pool: TaskPoolHandler,

    performance_statistics: PerformanceStatistics,

    model_events_receiver: Receiver<ResourceEvent>,

    #[allow(dead_code)] // Keep engine instance alive.
    sound_engine: SoundEngine,

    // A set of plugins used by the engine.
    plugins: Vec<PluginContainer>,

    plugins_enabled: bool,

    // Amount of time (in seconds) that passed from creation of the engine.
    elapsed_time: f32,

    input_state: InputState,

    /// A special container that is able to create nodes by their type UUID. Use a copy of this
    /// value whenever you need it as a parameter in other parts of the engine.
    pub serialization_context: Arc<SerializationContext>,

    /// A container with widget constructors.
    pub widget_constructors: Arc<WidgetConstructorContainer>,

    /// A container with constructors for dynamic types. See [`DynTypeConstructorContainer`] for more
    /// info.
    pub dyn_type_constructors: Arc<DynTypeConstructorContainer>,

    /// Script processor is used to run script methods in a strict order.
    pub script_processor: ScriptProcessor,

    error_queue: ErrorQueue,
}

#[derive(Debug, Hash, PartialEq, Eq)]
enum MessageTypeId {
    Static(TypeId),
    Dynamic(DynamicTypeId),
}

/// Performs dispatch of script messages.
pub struct ScriptMessageDispatcher {
    type_groups: FxHashMap<MessageTypeId, FxHashSet<Handle<Node>>>,
    message_receiver: Receiver<ScriptMessage>,
}

fn try_enqueue_plugin_error(method_name: &'static str, result: GameResult, queue: &mut ErrorQueue) {
    if let Err(error) = result {
        queue.push_back(GameErrorContainer {
            source: GameErrorSource::PluginMethod(method_name),
            error,
        });
    }
}

impl ScriptMessageDispatcher {
    fn new(message_receiver: Receiver<ScriptMessage>) -> Self {
        Self {
            type_groups: Default::default(),
            message_receiver,
        }
    }

    /// Subscribes a node to receive any message of the given type `T`. Subscription is automatically removed
    /// if the node dies.
    pub fn subscribe_to<T: 'static>(&mut self, receiver: Handle<Node>) {
        self.subscribe_internal_to(receiver, MessageTypeId::Static(TypeId::of::<T>()));
    }

    /// Subscribes a node to receive any message of the given type `type_id`. Subscription is automatically removed
    /// if the node dies.
    pub fn subscribe_dynamic_to(&mut self, receiver: Handle<Node>, type_id: DynamicTypeId) {
        self.subscribe_internal_to(receiver, MessageTypeId::Dynamic(type_id));
    }

    #[inline]
    fn subscribe_internal_to(&mut self, receiver: Handle<Node>, type_id: MessageTypeId) {
        self.type_groups
            .entry(type_id)
            .and_modify(|v| {
                v.insert(receiver);
            })
            .or_insert_with(|| FxHashSet::from_iter([receiver]));
    }

    /// Unsubscribes a node from receiving any messages of the given type `T`.
    pub fn unsubscribe_from<T: 'static>(&mut self, receiver: Handle<Node>) {
        self.unsubscribe_internal_from(receiver, &MessageTypeId::Static(TypeId::of::<T>()));
    }

    /// Unsubscribes a node from receiving any messages of the given type `type_id`.
    pub fn unsubscribe_dynamic_from(&mut self, receiver: Handle<Node>, type_id: DynamicTypeId) {
        self.unsubscribe_internal_from(receiver, &MessageTypeId::Dynamic(type_id));
    }

    #[inline]
    fn unsubscribe_internal_from(&mut self, receiver: Handle<Node>, type_id: &MessageTypeId) {
        if let Some(group) = self.type_groups.get_mut(type_id) {
            group.remove(&receiver);
        }
    }

    /// Unsubscribes a node from receiving any messages.
    pub fn unsubscribe(&mut self, receiver: Handle<Node>) {
        for group in self.type_groups.values_mut() {
            group.remove(&receiver);
        }
    }

    fn dispatch_messages(
        &self,
        scene: &mut Scene,
        scene_handle: Handle<Scene>,
        plugins: &mut [PluginContainer],
        resource_manager: &ResourceManager,
        dt: f32,
        elapsed_time: f32,
        message_sender: &ScriptMessageSender,
        user_interfaces: &mut UiContainer,
        graphics_context: &mut GraphicsContext,
        task_pool: &mut TaskPoolHandler,
        input_state: &InputState,
        error_queue: &mut ErrorQueue,
    ) {
        while let Ok(message) = self.message_receiver.try_recv() {
            let type_id = match message.payload.get_dynamic_type_id() {
                Some(it) => MessageTypeId::Dynamic(it),
                None => MessageTypeId::Static(message.payload.deref().type_id()),
            };
            let receivers = self.type_groups.get(&type_id);

            if receivers.is_none_or(|r| r.is_empty()) {
                Log::warn(format!(
                    "Script message {message:?} was sent, but there's no receivers. \
                    Did you forgot to subscribe your script to the message?"
                ));
            }

            if let Some(receivers) = receivers {
                let mut payload = message.payload;

                match message.kind {
                    ScriptMessageKind::Targeted(target) => {
                        if receivers.contains(&target) {
                            let mut context = ScriptMessageContext {
                                dt,
                                elapsed_time,
                                plugins: PluginsRefMut(plugins),
                                handle: target,
                                scene,
                                scene_handle,
                                resource_manager,
                                message_sender,
                                task_pool,
                                graphics_context,
                                user_interfaces,
                                script_index: 0,
                                input_state,
                            };

                            process_node_scripts(
                                "on_message",
                                &mut context,
                                scene_handle,
                                error_queue,
                                &mut |s, ctx| s.on_message(&mut *payload, ctx),
                            )
                        }
                    }
                    ScriptMessageKind::Hierarchical { root, routing } => match routing {
                        RoutingStrategy::Up => {
                            let mut node = root;
                            while let Ok(node_ref) = scene.graph.try_get_node(node) {
                                let parent = node_ref.parent();

                                let mut context = ScriptMessageContext {
                                    dt,
                                    elapsed_time,
                                    plugins: PluginsRefMut(plugins),
                                    handle: node,
                                    scene,
                                    scene_handle,
                                    resource_manager,
                                    message_sender,
                                    task_pool,
                                    graphics_context,
                                    user_interfaces,
                                    script_index: 0,
                                    input_state,
                                };

                                if receivers.contains(&node) {
                                    process_node_scripts(
                                        "on_message",
                                        &mut context,
                                        scene_handle,
                                        error_queue,
                                        &mut |s, ctx| s.on_message(&mut *payload, ctx),
                                    );
                                }

                                node = parent;
                            }
                        }
                        RoutingStrategy::Down => {
                            for node in scene.graph.traverse_handle_iter(root).collect::<Vec<_>>() {
                                let mut context = ScriptMessageContext {
                                    dt,
                                    elapsed_time,
                                    plugins: PluginsRefMut(plugins),
                                    handle: node,
                                    scene,
                                    scene_handle,
                                    resource_manager,
                                    message_sender,
                                    task_pool,
                                    graphics_context,
                                    user_interfaces,
                                    script_index: 0,
                                    input_state,
                                };

                                if receivers.contains(&node) {
                                    process_node_scripts(
                                        "on_message",
                                        &mut context,
                                        scene_handle,
                                        error_queue,
                                        &mut |s, ctx| s.on_message(&mut *payload, ctx),
                                    );
                                }
                            }
                        }
                    },
                    ScriptMessageKind::Global => {
                        for &node in receivers {
                            let mut context = ScriptMessageContext {
                                dt,
                                elapsed_time,
                                plugins: PluginsRefMut(plugins),
                                handle: node,
                                scene,
                                scene_handle,
                                resource_manager,
                                message_sender,
                                task_pool,
                                graphics_context,
                                user_interfaces,
                                script_index: 0,
                                input_state,
                            };

                            process_node_scripts(
                                "on_message",
                                &mut context,
                                scene_handle,
                                error_queue,
                                &mut |s, ctx| s.on_message(&mut *payload, ctx),
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Scripted scene is a handle to scene with some additional data associated with it.
pub struct ScriptedScene {
    /// Handle of a scene.
    pub handle: Handle<Scene>,
    /// Script message sender.
    pub message_sender: ScriptMessageSender,
    message_dispatcher: ScriptMessageDispatcher,
}

/// Script processor is used to run script methods in a strict order.
#[derive(Default)]
pub struct ScriptProcessor {
    wait_list: Vec<ResourceWaitContext>,
    /// A list of scenes.
    pub scripted_scenes: Vec<ScriptedScene>,
}

impl ScriptProcessor {
    fn has_scripted_scene(&self, scene: Handle<Scene>) -> bool {
        self.scripted_scenes.iter().any(|s| s.handle == scene)
    }

    fn register_scripted_scene(
        &mut self,
        scene: Handle<Scene>,
        resource_manager: &ResourceManager,
    ) {
        // Ensure that the scene wasn't registered previously.
        assert!(!self.has_scripted_scene(scene));

        let (tx, rx) = channel();
        self.scripted_scenes.push(ScriptedScene {
            handle: scene,
            message_sender: ScriptMessageSender { sender: tx },
            message_dispatcher: ScriptMessageDispatcher::new(rx),
        });

        self.wait_list
            .push(resource_manager.state().get_wait_context());
    }

    fn handle_scripts(
        &mut self,
        scenes: &mut SceneContainer,
        plugins: &mut [PluginContainer],
        resource_manager: &ResourceManager,
        task_pool: &mut TaskPoolHandler,
        graphics_context: &mut GraphicsContext,
        user_interfaces: &mut UiContainer,
        dt: f32,
        elapsed_time: f32,
        input_state: &InputState,
        error_queue: &mut ErrorQueue,
    ) {
        self.wait_list
            .retain_mut(|context| !context.is_all_loaded());

        if !self.wait_list.is_empty() {
            return;
        }

        self.scripted_scenes
            .retain(|s| scenes.is_valid_handle(s.handle));

        'scene_loop: for scripted_scene in self.scripted_scenes.iter_mut() {
            let scene = &mut scenes[scripted_scene.handle];

            // Disabled scenes should not update their scripts.
            if !*scene.enabled {
                continue 'scene_loop;
            }

            // Fill in initial handles to nodes to initialize, start, update.
            let mut update_queue = VecDeque::new();
            let mut start_queue = VecDeque::new();
            let script_message_sender = scene.graph.script_message_sender.clone();
            for (handle, node) in scene.graph.pair_iter_mut() {
                // Remove unused script entries.
                node.scripts
                    .retain(|e| e.script.is_some() && !e.should_be_deleted);

                if node.is_globally_enabled() {
                    for (i, entry) in node.scripts.iter().enumerate() {
                        if let Some(script) = entry.script.as_ref() {
                            if script.initialized {
                                if script.started {
                                    update_queue.push_back((handle, i));
                                } else {
                                    start_queue.push_back((handle, i));
                                }
                            } else {
                                script_message_sender
                                    .send(NodeScriptMessage::InitializeScript {
                                        handle,
                                        script_index: i,
                                    })
                                    .unwrap();
                            }
                        }
                    }
                }
            }

            // We'll gather all scripts queued for destruction and destroy them all at once at the
            // end of the frame.
            let mut destruction_queue = VecDeque::new();

            let max_iterations = 64;

            'update_loop: for update_loop_iteration in 0..max_iterations {
                let mut context = ScriptContext {
                    dt,
                    elapsed_time,
                    plugins: PluginsRefMut(plugins),
                    handle: Default::default(),
                    scene,
                    scene_handle: scripted_scene.handle,
                    resource_manager,
                    message_sender: &scripted_scene.message_sender,
                    message_dispatcher: &mut scripted_scene.message_dispatcher,
                    task_pool,
                    graphics_context,
                    user_interfaces,
                    script_index: 0,
                    input_state,
                };

                'init_loop: for init_loop_iteration in 0..max_iterations {
                    // Process events first. `on_init` of a script can also create some other instances
                    // and these will be correctly initialized on current frame.
                    while let Ok(event) = context.scene.graph.script_message_receiver.try_recv() {
                        match event {
                            NodeScriptMessage::InitializeScript {
                                handle,
                                script_index,
                            } => {
                                context.handle = handle;
                                context.script_index = script_index;

                                process_node_script(
                                    "on_init",
                                    script_index,
                                    scripted_scene.handle,
                                    &mut context,
                                    error_queue,
                                    &mut |script, context| {
                                        if !script.initialized {
                                            script.on_init(context)?;
                                            script.initialized = true;
                                        }

                                        // `on_start` must be called even if the script was initialized.
                                        start_queue.push_back((handle, script_index));

                                        Ok(())
                                    },
                                );
                            }
                            NodeScriptMessage::DestroyScript {
                                handle,
                                script,
                                script_index,
                            } => {
                                // Destruction is delayed to the end of the frame.
                                destruction_queue.push_back((handle, script, script_index));
                            }
                        }
                    }

                    if start_queue.is_empty() {
                        // There is no more new nodes, we can safely leave the init loop.
                        break 'init_loop;
                    } else {
                        // Call `on_start` for every recently initialized node and go to next
                        // iteration of init loop. This is needed because `on_start` can spawn
                        // some other nodes that must be initialized before update.
                        while let Some((handle, script_index)) = start_queue.pop_front() {
                            context.handle = handle;
                            context.script_index = script_index;

                            process_node_script(
                                "on_start",
                                script_index,
                                scripted_scene.handle,
                                &mut context,
                                error_queue,
                                &mut |script, context| {
                                    if script.initialized && !script.started {
                                        let result = script.on_start(context);
                                        script.started = true;
                                        update_queue.push_back((handle, script_index));
                                        result
                                    } else {
                                        Ok(())
                                    }
                                },
                            );
                        }
                    }

                    if init_loop_iteration == max_iterations - 1 {
                        Log::warn(
                            "Infinite init loop detected! Most likely some of \
                    your scripts causing infinite prefab instantiation!",
                        )
                    }
                }

                // Update all initialized and started scripts until there is something to initialize.
                if update_queue.is_empty() {
                    break 'update_loop;
                } else {
                    while let Some((handle, script_index)) = update_queue.pop_front() {
                        context.handle = handle;
                        context.script_index = script_index;

                        process_node_script(
                            "on_update",
                            script_index,
                            scripted_scene.handle,
                            &mut context,
                            error_queue,
                            &mut |script, context| script.on_update(context),
                        );
                    }
                }

                if update_loop_iteration == max_iterations - 1 {
                    Log::warn(
                        "Infinite update loop detected! Most likely some of \
                    your scripts causing infinite prefab instantiation!",
                    )
                }
            }

            // Dispatch script messages only when everything is initialized and updated. This has to
            // be done this way, because all those methods could spawn new messages. However, if a new
            // message is spawned directly in `on_message` the dispatcher will correctly handle it
            // on this frame, since it will be placed in the common queue anyway.
            scripted_scene.message_dispatcher.dispatch_messages(
                scene,
                scripted_scene.handle,
                plugins,
                resource_manager,
                dt,
                elapsed_time,
                &scripted_scene.message_sender,
                user_interfaces,
                graphics_context,
                task_pool,
                input_state,
                error_queue,
            );

            // As the last step, destroy queued scripts.
            let mut context = ScriptDeinitContext {
                elapsed_time,
                plugins: PluginsRefMut(plugins),
                resource_manager,
                scene,
                scene_handle: scripted_scene.handle,
                node_handle: Default::default(),
                message_sender: &scripted_scene.message_sender,
                user_interfaces,
                graphics_context,
                task_pool,
                script_index: 0,
                input_state,
            };
            while let Some((handle, mut script, index)) = destruction_queue.pop_front() {
                context.node_handle = handle;
                context.script_index = index;

                // Unregister self in message dispatcher.
                scripted_scene.message_dispatcher.unsubscribe(handle);

                // `on_deinit` could also spawn new nodes, but we won't take those into account on
                // this frame. They'll be correctly handled on next frame.
                if let Err(error) = script.on_deinit(&mut context) {
                    error_queue.push_back(GameErrorContainer {
                        source: GameErrorSource::ScriptMethod {
                            scene_handle: scripted_scene.handle,
                            node_handle: handle,
                            method_name: "on_deinit",
                        },
                        error,
                    });
                }
            }
        }

        // Process scripts from destroyed scenes.
        for (handle, mut detached_scene) in scenes.destruction_list.drain(..) {
            if let Some(scripted_scene) = self.scripted_scenes.iter().find(|s| s.handle == handle) {
                let mut context = ScriptDeinitContext {
                    elapsed_time,
                    plugins: PluginsRefMut(plugins),
                    resource_manager,
                    scene: &mut detached_scene,
                    scene_handle: scripted_scene.handle,
                    node_handle: Default::default(),
                    message_sender: &scripted_scene.message_sender,
                    task_pool,
                    graphics_context,
                    user_interfaces,
                    script_index: 0,
                    input_state,
                };

                // Destroy every script instance from nodes that were still alive.
                for node_index in 0..context.scene.graph.capacity() {
                    let handle_node = context.scene.graph.handle_from_index(node_index);
                    context.node_handle = handle_node;

                    process_node_scripts(
                        "on_deinit",
                        &mut context,
                        scripted_scene.handle,
                        error_queue,
                        &mut |script, context| {
                            if script.initialized {
                                script.on_deinit(context)
                            } else {
                                Ok(())
                            }
                        },
                    );
                }
            }
        }
    }
}

struct ResourceGraphVertex {
    resource: ModelResource,
    children: Vec<ResourceGraphVertex>,
}

impl ResourceGraphVertex {
    pub fn new(model: ModelResource, resource_manager: ResourceManager) -> Self {
        let mut children = Vec::new();

        // Look for dependent resources.
        let mut dependent_resources = HashSet::new();
        for resource in resource_manager.state().iter() {
            if let Some(other_model) = resource.try_cast::<Model>() {
                let mut state = other_model.state();
                if let Some(model_data) = state.data() {
                    if model_data
                        .get_scene()
                        .graph
                        .linear_iter()
                        .any(|n| n.resource.as_ref() == Some(&model))
                    {
                        dependent_resources.insert(other_model.clone());
                    }
                }
            }
        }

        children.extend(
            dependent_resources
                .into_iter()
                .map(|r| ResourceGraphVertex::new(r, resource_manager.clone())),
        );

        Self {
            resource: model,
            children,
        }
    }

    pub fn resolve(&self) {
        Log::info(format!(
            "Resolving {} resource from dependency graph...",
            self.resource.resource_uuid()
        ));

        // Wait until resource is fully loaded, then resolve.
        if block_on(self.resource.clone()).is_ok() {
            self.resource.data_ref().get_scene_mut();

            for child in self.children.iter() {
                child.resolve();
            }
        }
    }
}

struct ResourceDependencyGraph {
    root: ResourceGraphVertex,
}

impl ResourceDependencyGraph {
    pub fn new(model: ModelResource, resource_manager: ResourceManager) -> Self {
        Self {
            root: ResourceGraphVertex::new(model, resource_manager),
        }
    }

    pub fn resolve(&self) {
        self.root.resolve()
    }
}

/// A result returned by a graphics server constructor.
pub type GraphicsServerConstructorResult = Result<(Window, SharedGraphicsServer), FrameworkError>;

/// Graphics server constructor callback responsible for actual server creation. Graphics server
/// initialization usually tied together with window creation on some operating systems, that's why
/// the constructor accepts window builder and must return the window built with the builder as well
/// as the server.
pub type GraphicsServerConstructorCallback = dyn Fn(
    &GraphicsContextParams,
    &ActiveEventLoop,
    WindowAttributes,
    bool,
) -> GraphicsServerConstructorResult;

/// Graphics server constructor is used to initialize different graphics servers in unified manner.
/// [`Default`] trait implementation currently creates OpenGL graphics server.
#[derive(Clone)]
pub struct GraphicsServerConstructor(Rc<GraphicsServerConstructorCallback>);

impl Default for GraphicsServerConstructor {
    fn default() -> Self {
        Self(Rc::new(
            |params, window_target, window_builder, named_objects| {
                GlGraphicsServer::new(
                    params.vsync,
                    params.msaa_sample_count,
                    window_target,
                    window_builder,
                    named_objects,
                )
            },
        ))
    }
}

/// A set of parameters that could be used to initialize graphics context.
#[derive(Clone)]
pub struct GraphicsContextParams {
    /// Attributes of the main application window.
    pub window_attributes: WindowAttributes,

    /// Whether to use vertical synchronization or not. V-sync will force your game to render frames with the synchronization
    /// rate of your monitor (which is ~60 FPS). Keep in mind that vertical synchronization might not be available on your OS.
    pub vsync: bool,

    /// Amount of samples for MSAA. Must be a power of two (1, 2, 4, 8). `None` means disabled.
    /// MSAA works only for forward rendering and does not work for deferred rendering.
    pub msaa_sample_count: Option<u8>,

    /// Graphic server constructor. See [`GraphicsServerConstructor`] docs for more info.
    pub graphics_server_constructor: GraphicsServerConstructor,

    /// A flag, that if raised tells the engine to assign meaningful names for GPU objects. This
    /// option is very useful for debugging. This option is off by default, because if may cause
    /// crashes on some video driver due to poor implementation in the driver.
    pub named_objects: bool,
}

impl Default for GraphicsContextParams {
    fn default() -> Self {
        Self {
            window_attributes: Default::default(),
            vsync: true,
            msaa_sample_count: None,
            graphics_server_constructor: Default::default(),
            named_objects: false,
        }
    }
}

/// Engine initialization parameters.
pub struct EngineInitParams {
    /// A set of parameters for graphics context initialization. Keep in mind that the engine **will not** initialize
    /// graphics context for you. Instead, you need to call [`Engine::initialize_graphics_context`] on [`Event::Resumed`]
    /// event and [`Engine::destroy_graphics_context`] on [`Event::Suspended`] event. If you don't need a graphics context
    /// (for example for game servers), then you can pass [`Default::default`] here and do not call any methods.
    pub graphics_context_params: GraphicsContextParams,
    /// A special container that is able to create nodes by their type UUID.
    pub serialization_context: Arc<SerializationContext>,
    /// A container with widget constructors.
    pub widget_constructors: Arc<WidgetConstructorContainer>,
    /// A container for dynamic types. See [`DynTypeConstructorContainer`] docs for more info.
    pub dyn_type_constructors: Arc<DynTypeConstructorContainer>,
    /// A resource manager.
    pub resource_manager: ResourceManager,
    /// Task pool for asynchronous task management.
    pub task_pool: Arc<TaskPool>,
}

fn process_node_script<T, C>(
    caller_name: &'static str,
    index: usize,
    scene_handle: Handle<Scene>,
    context: &mut C,
    error_queue: &mut ErrorQueue,
    func: &mut T,
) -> bool
where
    T: FnMut(&mut Script, &mut C) -> GameResult,
    C: UniversalScriptContext,
{
    let Ok(node) = context.node() else {
        // A node was destroyed.
        return false;
    };

    if !node.is_globally_enabled() {
        return false;
    }

    let Some(entry) = node.scripts.get_mut(index) else {
        // All scripts were visited.
        return false;
    };

    let Some(mut script) = entry.take() else {
        return false;
    };

    if let Err(error) = func(&mut script, context) {
        let node = context.node();
        let handle = node.map_or(Handle::NONE, |n| n.handle());
        error_queue.push_back(GameErrorContainer {
            source: GameErrorSource::ScriptMethod {
                scene_handle,
                node_handle: handle,
                method_name: caller_name,
            },
            error,
        });
    }

    match context.node() {
        Ok(node) => {
            let entry = node
                .scripts
                .get_mut(index)
                .expect("Scripts array cannot be modified!");

            if entry.should_be_deleted {
                context.destroy_script_deferred(script, index);
            } else {
                // Put the script back at its place.
                entry.script = Some(script);
            }
        }
        Err(_) => {
            // If the node was deleted by the `func` call, we must send the script to destruction
            // queue, not silently drop it.
            context.destroy_script_deferred(script, index);
        }
    }

    true
}

fn process_node_scripts<T, C>(
    caller_name: &'static str,
    context: &mut C,
    scene_handle: Handle<Scene>,
    error_queue: &mut ErrorQueue,
    func: &mut T,
) where
    T: FnMut(&mut Script, &mut C) -> GameResult,
    C: UniversalScriptContext,
{
    let mut index = 0;
    loop {
        context.set_script_index(index);

        if !process_node_script(caller_name, index, scene_handle, context, error_queue, func) {
            return;
        }

        // Advance to the next script.
        index += 1;
    }
}

pub(crate) fn process_scripts<T>(
    caller_name: &'static str,
    scene: &mut Scene,
    scene_handle: Handle<Scene>,
    plugins: &mut [PluginContainer],
    resource_manager: &ResourceManager,
    message_sender: &ScriptMessageSender,
    message_dispatcher: &mut ScriptMessageDispatcher,
    task_pool: &mut TaskPoolHandler,
    graphics_context: &mut GraphicsContext,
    user_interfaces: &mut UiContainer,
    dt: f32,
    elapsed_time: f32,
    input_state: &InputState,
    error_queue: &mut ErrorQueue,
    mut func: T,
) where
    T: FnMut(&mut Script, &mut ScriptContext) -> GameResult,
{
    let mut context = ScriptContext {
        dt,
        elapsed_time,
        plugins: PluginsRefMut(plugins),
        handle: Default::default(),
        scene,
        scene_handle,
        resource_manager,
        message_sender,
        message_dispatcher,
        task_pool,
        graphics_context,
        user_interfaces,
        script_index: 0,
        input_state,
    };

    for node_index in 0..context.scene.graph.capacity() {
        context.handle = context.scene.graph.handle_from_index(node_index);

        process_node_scripts(
            caller_name,
            &mut context,
            scene_handle,
            error_queue,
            &mut func,
        );
    }
}

pub(crate) fn initialize_resource_manager_loaders(
    resource_manager: &ResourceManager,
    serialization_context: Arc<SerializationContext>,
    widget_constructors: Arc<WidgetConstructorContainer>,
    dyn_type_constructors: Arc<DynTypeConstructorContainer>,
) {
    let model_loader = ModelLoader {
        resource_manager: resource_manager.clone(),
        serialization_context,
        dyn_type_constructors: dyn_type_constructors.clone(),
        default_import_options: Default::default(),
    };

    let mut state = resource_manager.state();

    for shader in ShaderResource::standard_shaders() {
        state.built_in_resources.add((*shader).clone());
    }
    state.built_in_resources.add(GLTF_SHADER.clone());

    for texture in SkyBoxKind::built_in_skybox_textures() {
        state.built_in_resources.add(texture.clone());
    }

    state.built_in_resources.add(BUILT_IN_FONT.clone());
    state.built_in_resources.add(BUILT_IN_BOLD.clone());
    state.built_in_resources.add(BUILT_IN_ITALIC.clone());
    state.built_in_resources.add(BOLD_ITALIC.clone());

    state.built_in_resources.add(texture::PLACEHOLDER.clone());
    state.built_in_resources.add(texture::PURE_COLOR.clone());
    state.built_in_resources.add(style::DEFAULT_STYLE.clone());
    state.built_in_resources.add(style::LIGHT_STYLE.clone());

    for material in [
        &*material::STANDARD,
        &*material::STANDARD_2D,
        &*material::STANDARD_SPRITE,
        &*material::STANDARD_TERRAIN,
        &*material::STANDARD_TWOSIDES,
        &*material::STANDARD_PARTICLE_SYSTEM,
        &*material::STANDARD_WIDGET,
    ] {
        state.built_in_resources.add(material.clone());
    }

    for surface in [
        &*surface::CUBE,
        &*surface::QUAD,
        &*surface::CYLINDER,
        &*surface::SPHERE,
        &*surface::CONE,
        &*surface::TORUS,
    ] {
        state.built_in_resources.add(surface.clone());
    }

    state.constructors_container.add::<Texture>();
    state.constructors_container.add::<Shader>();
    state.constructors_container.add::<Model>();
    state.constructors_container.add::<CurveResourceState>();
    state.constructors_container.add::<SoundBuffer>();
    state.constructors_container.add::<HrirSphereResourceData>();
    state.constructors_container.add::<Material>();
    state.constructors_container.add::<Font>();
    state.constructors_container.add::<UserInterface>();
    state.constructors_container.add::<SurfaceData>();
    state.constructors_container.add::<TileSet>();
    state.constructors_container.add::<TileMapBrush>();
    state.constructors_container.add::<TileMapData>();
    state.constructors_container.add::<CustomTileCollider>();
    state.constructors_container.add::<AnimationTracksData>();
    state.constructors_container.add::<Style>();

    let mut loaders = state.loaders.safe_lock();
    let gltf_loader = super::resource::gltf::GltfLoader {
        resource_manager: resource_manager.clone(),
        default_import_options: Default::default(),
    };
    loaders.set(gltf_loader);
    loaders.set(model_loader);
    loaders.set(TextureLoader {
        default_import_options: Default::default(),
    });
    loaders.set(SoundBufferLoader {
        default_import_options: Default::default(),
    });
    loaders.set(ShaderLoader);
    loaders.set(CurveLoader);
    loaders.set(HrirSphereLoader);
    loaders.set(MaterialLoader {
        resource_manager: resource_manager.clone(),
    });
    loaders.set(FontLoader::new(resource_manager.clone()));
    loaders.set(UserInterfaceLoader {
        resource_manager: resource_manager.clone(),
        constructors: widget_constructors,
        dyn_type_constructors,
    });
    loaders.set(SurfaceDataLoader {});
    loaders.set(TileSetLoader {
        resource_manager: resource_manager.clone(),
    });
    loaders.set(TileMapBrushLoader {
        resource_manager: resource_manager.clone(),
    });
    loaders.set(StyleLoader {
        resource_manager: resource_manager.clone(),
    });
}

/// A controller for the application loop.
#[derive(Copy, Clone)]
pub enum ApplicationLoopController<'a> {
    /// Headless loop controller. This variant is used when the engine is running in headless mode
    /// (with no window, graphics, sound, etc. support), usually used by game servers.
    Headless {
        /// A variable that controls execution of the game loop. If set to `false` the loop will
        /// exit and the application will end its execution.
        running: &'a Cell<bool>,
    },
    /// Normal application loop controller with full window, graphics, sound support.
    ActiveEventLoop(&'a ActiveEventLoop),
    /// Normal application loop controller without a window.
    EventLoop(&'a EventLoop<()>),
}

impl ApplicationLoopController<'_> {
    /// Asks the loop controller to end the application execution.
    pub fn exit(&self) {
        match self {
            ApplicationLoopController::Headless { running } => running.set(false),
            ApplicationLoopController::ActiveEventLoop(event_loop) => event_loop.exit(),
            ApplicationLoopController::EventLoop(_) => {
                warn!("Can't exit the loop until it is activated!")
            }
        }
    }

    /// Returns `true` if the loop will be destroyed in the next frame and the application will
    /// shut down.
    pub fn exiting(&self) -> bool {
        match self {
            ApplicationLoopController::Headless { running } => !running.get(),
            ApplicationLoopController::ActiveEventLoop(event_loop) => event_loop.exiting(),
            ApplicationLoopController::EventLoop(_) => false,
        }
    }
}

impl Engine {
    /// Creates new instance of engine from given initialization parameters. Automatically creates all sub-systems
    /// (sound, ui, resource manager, etc.) **except** graphics context. Graphics context should be created manually
    /// only on [`Event::Resumed`] by calling [`Engine::initialize_graphics_context`] and destroyed on [`Event::Suspended`]
    /// by calling [`Engine::destroy_graphics_context`]. If you don't need a graphics context (for example if you're
    /// making a game server), then you can ignore these methods.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fyrox_impl::{
    /// #     asset::manager::ResourceManager,
    /// #     engine::{
    /// #         Engine, EngineInitParams, GraphicsContextParams,
    /// #         SerializationContext,
    /// #     },
    /// #     event_loop::EventLoop,
    /// #     window::WindowAttributes,
    /// # };
    /// # use std::sync::Arc;
    /// use fyrox_core::dyntype::DynTypeConstructorContainer;
    /// # use fyrox_core::task::TaskPool;
    /// # use fyrox_resource::io::FsResourceIo;
    /// # use fyrox_ui::constructor::new_widget_constructor_container;
    ///
    /// let mut window_attributes = WindowAttributes::default();
    /// window_attributes.title = "Some title".to_string();
    /// let graphics_context_params = GraphicsContextParams {
    ///     window_attributes,
    ///     vsync: true,
    ///     msaa_sample_count: None,
    ///     graphics_server_constructor: Default::default(),
    ///     named_objects: false
    /// };
    /// let task_pool = Arc::new(TaskPool::new());
    ///
    /// Engine::new(EngineInitParams {
    ///     graphics_context_params,
    ///     resource_manager: ResourceManager::new(Arc::new(FsResourceIo), task_pool.clone()),
    ///     dyn_type_constructors: Arc::new(DynTypeConstructorContainer::default()),
    ///     serialization_context: Arc::new(SerializationContext::new()),
    ///     task_pool,
    ///     widget_constructors: Arc::new(new_widget_constructor_container()),
    /// })
    /// .unwrap();
    /// ```
    #[inline]
    #[allow(unused_variables)]
    pub fn new(params: EngineInitParams) -> Result<Self, EngineError> {
        let EngineInitParams {
            graphics_context_params,
            serialization_context,
            widget_constructors,
            dyn_type_constructors,
            resource_manager,
            task_pool,
        } = params;

        #[cfg(target_arch = "wasm32")]
        wasm_utils::set_panic_hook();

        initialize_resource_manager_loaders(
            &resource_manager,
            serialization_context.clone(),
            widget_constructors.clone(),
            dyn_type_constructors.clone(),
        );

        let (rx, tx) = channel();
        resource_manager.state().event_broadcaster.add(rx);

        let sound_engine = SoundEngine::without_device();

        Ok(Self {
            graphics_context: GraphicsContext::Uninitialized(graphics_context_params),
            model_events_receiver: tx,
            resource_manager,
            scenes: SceneContainer::new(sound_engine.clone()),
            sound_engine,
            user_interfaces: Default::default(),
            performance_statistics: Default::default(),
            plugins: Default::default(),
            serialization_context,
            widget_constructors,
            dyn_type_constructors,
            script_processor: Default::default(),
            plugins_enabled: false,
            elapsed_time: 0.0,
            task_pool: TaskPoolHandler::new(task_pool),
            input_state: Default::default(),
            error_queue: Default::default(),
        })
    }

    /// Tries to initialize the graphics context. The method will attempt to use the info stored in `graphics_context`
    /// variable of the engine to attempt to initialize the graphics context. It will fail if the graphics context is
    /// already initialized as well as if there any platform-dependent error (for example your hardware does not support
    /// OpenGL 3.3 Core or OpenGL ES 3.0).
    ///
    /// This method should be called on [`Event::Resumed`] of your game loop, however you can ignore it if you don't need
    /// graphics context at all (for example - if you're making game server).
    pub fn initialize_graphics_context(
        &mut self,
        event_loop: &ActiveEventLoop,
    ) -> Result<(), EngineError> {
        if let GraphicsContext::Uninitialized(params) = &self.graphics_context {
            let (window, server) = params.graphics_server_constructor.0(
                params,
                event_loop,
                params.window_attributes.clone(),
                params.named_objects,
            )?;
            let frame_size = (window.inner_size().width, window.inner_size().height);

            let renderer = Renderer::new(server, frame_size, &self.resource_manager)?;

            for ui in self.user_interfaces.iter_mut() {
                ui.set_screen_size(Vector2::new(frame_size.0 as f32, frame_size.1 as f32));
            }

            self.graphics_context = GraphicsContext::Initialized(InitializedGraphicsContext {
                renderer,
                window,
                params: params.clone(),
            });

            if let Err(err) = self.sound_engine.initialize_audio_output_device() {
                Log::err(format!(
                    "Unable to initialize audio output device! Reason: {err:?}"
                ));
            }

            Ok(())
        } else {
            Err(EngineError::Custom(
                "Graphics context is already initialized!".to_string(),
            ))
        }
    }

    /// Tries to destroy current graphics context. It will succeed only if the `graphics_context` is fully initialized.
    /// The method will try to save all possible runtime changes of the window, so the next [`Engine::initialize_graphics_context`]
    /// will result in the almost exact copy of the context that was made before destruction.
    ///
    /// This method should be called on [`Event::Suspended`] of your game loop, however if you do not use any graphics context
    /// (for example - if you're making a game server), then you can ignore this method completely.
    pub fn destroy_graphics_context(&mut self) -> Result<(), EngineError> {
        if let GraphicsContext::Initialized(ref ctx) = self.graphics_context {
            let params = &ctx.params;
            let window = &ctx.window;

            let mut window_attributes = WindowAttributes::default();

            window_attributes.inner_size = Some(Size::Physical(window.inner_size()));
            window_attributes.min_inner_size = params.window_attributes.min_inner_size;
            window_attributes.max_inner_size = params.window_attributes.max_inner_size;
            window_attributes.position = window.outer_position().ok().map(Position::Physical);
            window_attributes.resizable = window.is_resizable();
            window_attributes.enabled_buttons = window.enabled_buttons();
            window_attributes.title = window.title();
            window_attributes.maximized = window.is_maximized();
            window_attributes.visible = window.is_visible().unwrap_or(true);
            window_attributes.transparent = params.window_attributes.transparent;
            window_attributes.decorations = window.is_decorated();
            window_attributes.preferred_theme = params.window_attributes.preferred_theme;
            window_attributes.resize_increments = window.resize_increments().map(Size::Physical);
            window_attributes.content_protected = params.window_attributes.content_protected;
            window_attributes.window_level = params.window_attributes.window_level;
            window_attributes.active = params.window_attributes.active;
            window_attributes
                .window_icon
                .clone_from(&params.window_attributes.window_icon);

            self.graphics_context = GraphicsContext::Uninitialized(GraphicsContextParams {
                window_attributes,
                vsync: params.vsync,
                msaa_sample_count: params.msaa_sample_count,
                graphics_server_constructor: params.graphics_server_constructor.clone(),
                named_objects: params.named_objects,
            });

            self.sound_engine.destroy_audio_output_device();

            Ok(())
        } else {
            Err(EngineError::Custom(
                "Graphics context is already destroyed!".to_string(),
            ))
        }
    }

    /// Adjust size of the frame to be rendered. Must be called after the window size changes.
    /// Will update the renderer and GL context frame size.
    pub fn set_frame_size(&mut self, new_size: (u32, u32)) -> Result<(), FrameworkError> {
        if let GraphicsContext::Initialized(ctx) = &mut self.graphics_context {
            ctx.renderer.set_frame_size(new_size)?;
        }

        Ok(())
    }

    /// Amount of time (in seconds) that passed from creation of the engine. Keep in mind, that
    /// this value is **not** guaranteed to match real time. A user can change delta time with
    /// which the engine "ticks" and this delta time affects elapsed time.
    pub fn elapsed_time(&self) -> f32 {
        self.elapsed_time
    }

    /// Performs single update tick with given time delta. Engine internally will perform update
    /// of all scenes, sub-systems, user interface, etc. Must be called in order to get engine
    /// functioning.
    ///
    /// ## Parameters
    ///
    /// `lag` - is a reference to time accumulator, that holds remaining amount of time that should be used
    /// to update a plugin. A caller splits `lag` into multiple sub-steps using `dt` and thus stabilizes
    /// update rate. The main use of this variable, is to be able to reset `lag` when you doing some heavy
    /// calculations in a your game loop (i.e. loading a new level) so the engine won't try to "catch up" with
    /// all the time that was spent in heavy calculation. The engine does **not** use this variable itself,
    /// but the plugins attach may use it, that's why you need to provide it. If you don't use plugins, then
    /// put `&mut 0.0` here.
    pub fn update(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
        switches: FxHashMap<Handle<Scene>, GraphUpdateSwitches>,
    ) {
        self.pre_update(dt, controller, lag, switches);
        self.post_update(dt, &Default::default(), lag, controller);
        self.handle_plugins_hot_reloading(dt, controller, lag, |_| {});
    }

    /// Tries to hot-reload dynamic plugins marked for reloading.
    ///
    /// ## Platform-specific
    ///
    /// - Windows, Unix-like systems (Linux, macOS, FreeBSD, etc) - fully supported.
    /// - WebAssembly - not supported
    /// - Android - not supported
    pub fn handle_plugins_hot_reloading<F>(
        &mut self,
        #[allow(unused_variables)] dt: f32,
        #[allow(unused_variables)] controller: ApplicationLoopController,
        #[allow(unused_variables)] lag: &mut f32,
        #[allow(unused_variables)] on_reloaded: F,
    ) where
        F: FnMut(&dyn Plugin),
    {
        #[cfg(any(unix, windows))]
        {
            if let Err(message) = self.reload_dynamic_plugins(dt, controller, lag, on_reloaded) {
                Log::err(format!(
                    "Unable to reload dynamic plugins. Reason: {message}"
                ))
            }
        }
    }

    /// Performs pre update for the engine.
    ///
    /// Normally, this is called from `Engine::update()`.
    /// You should only call this manually if you don't use that method.
    ///
    /// ## Parameters
    ///
    /// `lag` - is a reference to time accumulator, that holds remaining amount of time that should be used
    /// to update a plugin. A caller splits `lag` into multiple sub-steps using `dt` and thus stabilizes
    /// update rate. The main use of this variable, is to be able to reset `lag` when you doing some heavy
    /// calculations in a your game loop (i.e. loading a new level) so the engine won't try to "catch up" with
    /// all the time that was spent in heavy calculation. The engine does **not** use this variable itself,
    /// but the plugins attach may use it, that's why you need to provide it. If you don't use plugins, then
    /// put `&mut 0.0` here.
    pub fn pre_update(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
        switches: FxHashMap<Handle<Scene>, GraphUpdateSwitches>,
    ) {
        // Run some plugin and script methods, potentially causing nodes to be added
        // or removed. This is where most of the rules of the game happen.
        self.update_plugins(dt, controller, lag);
        self.handle_scripts(dt);

        // Now that the plugins and scripts have made whatever changes are needed, we must respond
        // to those changes by updating the scenes and the state of the engine.

        self.resource_manager.state().update(dt);
        self.handle_model_events();

        let window_size = if let GraphicsContext::Initialized(ctx) = &mut self.graphics_context {
            let inner_size = ctx.window.inner_size();
            let window_size = Vector2::new(inner_size.width as f32, inner_size.height as f32);
            ctx.renderer.update_caches(&self.resource_manager, dt);
            window_size
        } else {
            Vector2::new(1.0, 1.0)
        };

        for (handle, scene) in self.scenes.pair_iter_mut().filter(|(_, s)| *s.enabled) {
            let frame_size =
                scene
                    .rendering_options
                    .render_target
                    .as_ref()
                    .map_or(window_size, |rt| {
                        if let TextureKind::Rectangle { width, height } = rt.data_ref().kind() {
                            Vector2::new(width as f32, height as f32)
                        } else {
                            panic!("only rectangle textures can be used as render target!");
                        }
                    });

            scene.update(
                frame_size,
                dt,
                switches.get(&handle).cloned().unwrap_or_default(),
            );
        }
    }

    /// Performs post update for the engine.
    ///
    /// Normally, this is called from `Engine::update()`.
    /// You should only call this manually if you don't use that method.
    pub fn post_update(
        &mut self,
        dt: f32,
        ui_update_switches: &UiUpdateSwitches,
        lag: &mut f32,
        controller: ApplicationLoopController,
    ) {
        let screen_size = if let GraphicsContext::Initialized(ref ctx) = self.graphics_context {
            let inner_size = ctx.window.inner_size();
            Some(Vector2::new(
                inner_size.width as f32,
                inner_size.height as f32,
            ))
        } else {
            None
        };

        let time = instant::Instant::now();
        for ui in self.user_interfaces.iter_mut() {
            let screen_size = screen_size.unwrap_or_else(|| ui.screen_size());
            ui.update(screen_size, dt, ui_update_switches);
        }
        self.performance_statistics.ui_time = instant::Instant::now() - time;
        self.elapsed_time += dt;

        if let GraphicsContext::Initialized(_) = self.graphics_context {
            self.post_update_plugins(dt, controller, lag);

            self.input_state.mouse.speed = Vector2::default();
            self.input_state.keyboard.released_keys.clear();
            self.input_state.keyboard.pressed_keys.clear();
        }
    }

    /// Returns true if the scene is registered for script processing.
    pub fn has_scripted_scene(&self, scene: Handle<Scene>) -> bool {
        self.script_processor.has_scripted_scene(scene)
    }

    /// Registers a scene for script processing.
    pub fn register_scripted_scene(&mut self, scene: Handle<Scene>) {
        self.script_processor
            .register_scripted_scene(scene, &self.resource_manager)
    }

    fn handle_scripts(&mut self, dt: f32) {
        let time = instant::Instant::now();

        self.script_processor.handle_scripts(
            &mut self.scenes,
            &mut self.plugins,
            &self.resource_manager,
            &mut self.task_pool,
            &mut self.graphics_context,
            &mut self.user_interfaces,
            dt,
            self.elapsed_time,
            &self.input_state,
            &mut self.error_queue,
        );

        self.performance_statistics.scripts_time = instant::Instant::now() - time;
    }

    fn handle_async_tasks(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        while let Some(result) = self.task_pool.inner().next_task_result() {
            if let Some(plugin_task_handler) = self.task_pool.pop_plugin_task_handler(result.id) {
                // Handle plugin task.
                let mut ctx = PluginContext {
                    scenes: &mut self.scenes,
                    resource_manager: &self.resource_manager,
                    graphics_context: &mut self.graphics_context,
                    dt,
                    lag,
                    user_interfaces: &mut self.user_interfaces,
                    serialization_context: &self.serialization_context,
                    widget_constructors: &self.widget_constructors,
                    dyn_type_constructors: &self.dyn_type_constructors,
                    performance_statistics: &self.performance_statistics,
                    elapsed_time: self.elapsed_time,
                    script_processor: &self.script_processor,
                    loop_controller: controller,
                    task_pool: &mut self.task_pool,
                    input_state: &self.input_state,
                };
                try_enqueue_plugin_error(
                    "handle_async_tasks",
                    (plugin_task_handler)(result.payload, &mut self.plugins, &mut ctx),
                    &mut self.error_queue,
                )
            } else if let Some(node_task_handler) = self.task_pool.pop_node_task_handler(result.id)
            {
                // Handle script task.
                if let Some(scripted_scene) = self
                    .script_processor
                    .scripted_scenes
                    .iter_mut()
                    .find(|e| e.handle == node_task_handler.scene_handle)
                {
                    let payload = result.payload;
                    if let Ok(scene) = self.scenes.try_get_mut(node_task_handler.scene_handle) {
                        if let Ok(node) =
                            scene.graph.try_get_node_mut(node_task_handler.node_handle)
                        {
                            if let Some(mut script) = node
                                .scripts
                                .get_mut(node_task_handler.script_index)
                                .and_then(|e| e.script.take())
                            {
                                let mut ctx = ScriptContext {
                                    dt,
                                    elapsed_time: self.elapsed_time,
                                    plugins: PluginsRefMut(&mut self.plugins),
                                    handle: node_task_handler.node_handle,
                                    scene,
                                    scene_handle: scripted_scene.handle,
                                    resource_manager: &self.resource_manager,
                                    message_sender: &scripted_scene.message_sender,
                                    message_dispatcher: &mut scripted_scene.message_dispatcher,
                                    task_pool: &mut self.task_pool,
                                    graphics_context: &mut self.graphics_context,
                                    user_interfaces: &mut self.user_interfaces,
                                    script_index: node_task_handler.script_index,
                                    input_state: &self.input_state,
                                };
                                try_enqueue_plugin_error(
                                    "handle_async_tasks",
                                    (node_task_handler.closure)(
                                        payload,
                                        script.deref_mut(),
                                        &mut ctx,
                                    ),
                                    &mut self.error_queue,
                                );

                                if let Ok(node) =
                                    scene.graph.try_get_node_mut(node_task_handler.node_handle)
                                {
                                    if let Some(entry) =
                                        node.scripts.get_mut(node_task_handler.script_index)
                                    {
                                        if entry.should_be_deleted {
                                            Log::verify(scene.graph.script_message_sender.send(
                                                NodeScriptMessage::DestroyScript {
                                                    script,
                                                    handle: node_task_handler.node_handle,
                                                    script_index: node_task_handler.script_index,
                                                },
                                            ));
                                        } else {
                                            entry.script = Some(script);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn update_plugins(&mut self, dt: f32, controller: ApplicationLoopController, lag: &mut f32) {
        let time = instant::Instant::now();

        if self.plugins_enabled {
            // Handle asynchronous tasks first.
            self.handle_async_tasks(dt, controller, lag);

            // Then update all the plugins.
            let mut context = PluginContext {
                scenes: &mut self.scenes,
                resource_manager: &self.resource_manager,
                graphics_context: &mut self.graphics_context,
                dt,
                lag,
                user_interfaces: &mut self.user_interfaces,
                serialization_context: &self.serialization_context,
                widget_constructors: &self.widget_constructors,
                dyn_type_constructors: &self.dyn_type_constructors,
                performance_statistics: &self.performance_statistics,
                elapsed_time: self.elapsed_time,
                script_processor: &self.script_processor,
                loop_controller: controller,
                task_pool: &mut self.task_pool,
                input_state: &self.input_state,
            };

            for plugin in self.plugins.iter_mut() {
                try_enqueue_plugin_error(
                    "update",
                    plugin.update(&mut context),
                    &mut self.error_queue,
                );
            }

            let mut uis = self
                .user_interfaces
                .pair_iter()
                .map(|(h, _)| h)
                .collect::<VecDeque<_>>();

            while let Some(ui) = uis.pop_front() {
                while let Some(message) = self
                    .user_interfaces
                    .try_get_mut(ui)
                    .ok()
                    .and_then(|ui| ui.poll_message())
                {
                    let mut context = PluginContext {
                        scenes: &mut self.scenes,
                        resource_manager: &self.resource_manager,
                        graphics_context: &mut self.graphics_context,
                        dt,
                        lag,
                        user_interfaces: &mut self.user_interfaces,
                        serialization_context: &self.serialization_context,
                        widget_constructors: &self.widget_constructors,
                        dyn_type_constructors: &self.dyn_type_constructors,
                        performance_statistics: &self.performance_statistics,
                        elapsed_time: self.elapsed_time,
                        script_processor: &self.script_processor,
                        loop_controller: controller,
                        task_pool: &mut self.task_pool,
                        input_state: &self.input_state,
                    };

                    for plugin in self.plugins.iter_mut() {
                        try_enqueue_plugin_error(
                            "on_ui_message",
                            plugin.on_ui_message(&mut context, &message, ui),
                            &mut self.error_queue,
                        );
                    }
                }
            }
        }

        self.performance_statistics.plugins_time = instant::Instant::now() - time;
    }

    fn post_update_plugins(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        let time = instant::Instant::now();

        if self.plugins_enabled {
            let mut context = PluginContext {
                scenes: &mut self.scenes,
                resource_manager: &self.resource_manager,
                graphics_context: &mut self.graphics_context,
                dt,
                lag,
                user_interfaces: &mut self.user_interfaces,
                serialization_context: &self.serialization_context,
                widget_constructors: &self.widget_constructors,
                dyn_type_constructors: &self.dyn_type_constructors,
                performance_statistics: &self.performance_statistics,
                elapsed_time: self.elapsed_time,
                script_processor: &self.script_processor,
                loop_controller: controller,
                task_pool: &mut self.task_pool,
                input_state: &self.input_state,
            };

            for plugin in self.plugins.iter_mut() {
                try_enqueue_plugin_error(
                    "post_update",
                    plugin.post_update(&mut context),
                    &mut self.error_queue,
                );
            }

            while let Some(container) = self.error_queue.pop_back() {
                for plugin in self.plugins.iter_mut() {
                    if plugin.on_game_error(&mut context, &container.error) {
                        continue;
                    }
                    match container.source {
                        GameErrorSource::PluginMethod(method_name) => {
                            err!(
                                "An error occurred in {method_name} plugin method. Reason: {}",
                                container.error
                            );
                        }
                        GameErrorSource::ScriptMethod {
                            scene_handle,
                            node_handle,
                            method_name,
                        } => {
                            let node_name = context
                                .scenes
                                .try_get(scene_handle)
                                .ok()
                                .and_then(|scene| {
                                    scene.graph.try_get(node_handle).ok().map(|n| n.name())
                                })
                                .unwrap_or("<undefined>");

                            err!(
                                "An error occurred during {method_name} call in {node_handle} \
                            node (name: {node_name}). Reason: {}",
                                container.error
                            );
                        }
                    }
                }
            }
        }

        self.performance_statistics.plugins_time += instant::Instant::now() - time;
    }

    /// Should be called on every OS event to update the internal state of the engine accordingly.
    pub fn handle_os_events(
        &mut self,
        event: &Event<()>,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        match event {
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::KeyboardInput { event, .. } => {
                    let keyboard = &mut self.input_state.keyboard;

                    match event.state {
                        ElementState::Pressed => {
                            if keyboard
                                .keys
                                .get(&event.physical_key)
                                .is_none_or(|state| *state == ElementState::Released)
                            {
                                keyboard.pressed_keys.insert(event.physical_key);
                            }
                        }
                        ElementState::Released => {
                            if keyboard
                                .keys
                                .get(&event.physical_key)
                                .is_some_and(|state| *state == ElementState::Pressed)
                            {
                                keyboard.released_keys.insert(event.physical_key);
                            }
                        }
                    }

                    keyboard.keys.insert(event.physical_key, event.state);
                }
                WindowEvent::CursorMoved { position, .. } => {
                    self.input_state.mouse.position =
                        Vector2::new(position.x as f32, position.y as f32);
                }
                _ => (),
            },
            Event::DeviceEvent { event, .. } => match event {
                DeviceEvent::MouseMotion { delta } => {
                    self.input_state.mouse.speed = Vector2::new(delta.0 as f32, delta.1 as f32);
                }
                DeviceEvent::Button { button, state } => {
                    let mouse = &mut self.input_state.mouse;

                    match *state {
                        ElementState::Pressed => {
                            if mouse
                                .buttons_state
                                .get(button)
                                .is_none_or(|state| *state == ElementState::Released)
                            {
                                mouse.pressed_buttons.insert(*button);
                            }
                        }
                        ElementState::Released => {
                            if mouse
                                .buttons_state
                                .get(button)
                                .is_some_and(|state| *state == ElementState::Pressed)
                            {
                                mouse.released_buttons.insert(*button);
                            }
                        }
                    }

                    mouse.buttons_state.insert(*button, *state);
                }
                _ => (),
            },
            _ => (),
        }

        if self.plugins_enabled {
            for plugin in self.plugins.iter_mut() {
                let ctx = PluginContext {
                    scenes: &mut self.scenes,
                    resource_manager: &self.resource_manager,
                    graphics_context: &mut self.graphics_context,
                    dt,
                    lag,
                    user_interfaces: &mut self.user_interfaces,
                    serialization_context: &self.serialization_context,
                    widget_constructors: &self.widget_constructors,
                    dyn_type_constructors: &self.dyn_type_constructors,
                    performance_statistics: &self.performance_statistics,
                    elapsed_time: self.elapsed_time,
                    script_processor: &self.script_processor,
                    loop_controller: controller,
                    task_pool: &mut self.task_pool,
                    input_state: &self.input_state,
                };

                try_enqueue_plugin_error(
                    "on_os_event",
                    plugin.on_os_event(event, ctx),
                    &mut self.error_queue,
                );
            }
        }
    }

    pub(crate) fn handle_graphics_context_created_by_plugins(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        if self.plugins_enabled {
            for plugin in self.plugins.iter_mut() {
                let ctx = PluginContext {
                    scenes: &mut self.scenes,
                    resource_manager: &self.resource_manager,
                    graphics_context: &mut self.graphics_context,
                    dt,
                    lag,
                    user_interfaces: &mut self.user_interfaces,
                    serialization_context: &self.serialization_context,
                    widget_constructors: &self.widget_constructors,
                    dyn_type_constructors: &self.dyn_type_constructors,
                    performance_statistics: &self.performance_statistics,
                    elapsed_time: self.elapsed_time,
                    script_processor: &self.script_processor,
                    loop_controller: controller,
                    task_pool: &mut self.task_pool,
                    input_state: &self.input_state,
                };

                try_enqueue_plugin_error(
                    "on_graphics_context_initialized",
                    plugin.on_graphics_context_initialized(ctx),
                    &mut self.error_queue,
                );
            }
        }
    }

    pub(crate) fn handle_graphics_context_destroyed_by_plugins(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        if self.plugins_enabled {
            for plugin in self.plugins.iter_mut() {
                let ctx = PluginContext {
                    scenes: &mut self.scenes,
                    resource_manager: &self.resource_manager,
                    graphics_context: &mut self.graphics_context,
                    dt,
                    lag,
                    user_interfaces: &mut self.user_interfaces,
                    serialization_context: &self.serialization_context,
                    widget_constructors: &self.widget_constructors,
                    dyn_type_constructors: &self.dyn_type_constructors,
                    performance_statistics: &self.performance_statistics,
                    elapsed_time: self.elapsed_time,
                    script_processor: &self.script_processor,
                    loop_controller: controller,
                    task_pool: &mut self.task_pool,
                    input_state: &self.input_state,
                };

                try_enqueue_plugin_error(
                    "on_graphics_context_destroyed",
                    plugin.on_graphics_context_destroyed(ctx),
                    &mut self.error_queue,
                );
            }
        }
    }

    pub(crate) fn handle_before_rendering_by_plugins(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) {
        if self.plugins_enabled {
            for plugin in self.plugins.iter_mut() {
                let ctx = PluginContext {
                    scenes: &mut self.scenes,
                    resource_manager: &self.resource_manager,
                    graphics_context: &mut self.graphics_context,
                    dt,
                    lag,
                    user_interfaces: &mut self.user_interfaces,
                    serialization_context: &self.serialization_context,
                    widget_constructors: &self.widget_constructors,
                    dyn_type_constructors: &self.dyn_type_constructors,
                    performance_statistics: &self.performance_statistics,
                    elapsed_time: self.elapsed_time,
                    script_processor: &self.script_processor,
                    loop_controller: controller,
                    task_pool: &mut self.task_pool,
                    input_state: &self.input_state,
                };

                try_enqueue_plugin_error(
                    "before_rendering",
                    plugin.before_rendering(ctx),
                    &mut self.error_queue,
                );
            }
        }
    }

    /// Passes specified OS event to every script of the specified scene.
    ///
    /// # Important notes
    ///
    /// This method is intended to be used by the editor and game runner. If you're using the
    /// engine as a framework, then you should not call this method because you'll most likely
    /// do something wrong.
    pub(crate) fn handle_os_event_by_scripts(
        &mut self,
        event: &Event<()>,
        scene_handle: Handle<Scene>,
        dt: f32,
    ) {
        if let Some(scripted_scene) = self
            .script_processor
            .scripted_scenes
            .iter_mut()
            .find(|s| s.handle == scene_handle)
        {
            let scene = &mut self.scenes[scene_handle];
            if *scene.enabled {
                process_scripts(
                    "on_os_event",
                    scene,
                    scene_handle,
                    &mut self.plugins,
                    &self.resource_manager,
                    &scripted_scene.message_sender,
                    &mut scripted_scene.message_dispatcher,
                    &mut self.task_pool,
                    &mut self.graphics_context,
                    &mut self.user_interfaces,
                    dt,
                    self.elapsed_time,
                    &self.input_state,
                    &mut self.error_queue,
                    |script, context| {
                        if script.initialized && script.started {
                            script.on_os_event(event, context)
                        } else {
                            Ok(())
                        }
                    },
                )
            }
        }
    }

    /// Handle hot-reloading of resources.
    ///
    /// Normally, this is called from `Engine::update()`.
    /// You should only call this manually if you don't use that method.
    pub fn handle_model_events(&mut self) {
        while let Ok(event) = self.model_events_receiver.try_recv() {
            if let ResourceEvent::Reloaded(resource) = event {
                if let Some(model) = resource.try_cast::<Model>() {
                    Log::info(format!(
                        "A model resource {} was reloaded, propagating changes...",
                        model.resource_uuid()
                    ));

                    // Build resource dependency graph and resolve it first.
                    ResourceDependencyGraph::new(model, self.resource_manager.clone()).resolve();

                    Log::info("Propagating changes to active scenes...");

                    // Resolve all scenes.
                    // TODO: This might be inefficient if there is bunch of scenes loaded,
                    // however this seems to be very rare case so it should be ok.
                    for scene in self.scenes.iter_mut() {
                        scene.resolve();
                    }
                }
            }
        }
    }

    /// Performs rendering of single frame, must be called from your game loop, otherwise you won't
    /// see anything.
    #[inline]
    pub fn render(&mut self) -> Result<(), FrameworkError> {
        for ui in self.user_interfaces.iter_mut() {
            ui.set_time(self.elapsed_time);
        }

        if let GraphicsContext::Initialized(ref mut ctx) = self.graphics_context {
            ctx.renderer.render_and_swap_buffers(
                &self.scenes,
                self.elapsed_time,
                self.user_interfaces
                    .iter_mut()
                    .filter(|ui| match ui.render_mode {
                        RenderMode::EveryFrame => true,
                        RenderMode::OnChanges => ui.need_render,
                    })
                    .map(|ui| {
                        ui.need_render = false;
                        UiRenderInfo {
                            ui,
                            render_target: ui.render_target.clone(),
                            clear_color: Default::default(),
                            resource_manager: &self.resource_manager,
                        }
                    }),
                &ctx.window,
                &self.resource_manager,
            )?;
        }

        Ok(())
    }

    /// Enables or disables registered plugins.
    pub(crate) fn enable_plugins(
        &mut self,
        scene_path: Option<&str>,
        enabled: bool,
        controller: ApplicationLoopController,
    ) {
        if self.plugins_enabled != enabled {
            self.plugins_enabled = enabled;

            if self.plugins_enabled {
                // Create and initialize instances.
                for plugin in self.plugins.iter_mut() {
                    let ctx = PluginContext {
                        scenes: &mut self.scenes,
                        resource_manager: &self.resource_manager,
                        graphics_context: &mut self.graphics_context,
                        dt: 0.0,
                        lag: &mut 0.0,
                        user_interfaces: &mut self.user_interfaces,
                        serialization_context: &self.serialization_context,
                        widget_constructors: &self.widget_constructors,
                        dyn_type_constructors: &self.dyn_type_constructors,
                        performance_statistics: &self.performance_statistics,
                        elapsed_time: self.elapsed_time,
                        script_processor: &self.script_processor,
                        loop_controller: controller,
                        task_pool: &mut self.task_pool,
                        input_state: &self.input_state,
                    };

                    try_enqueue_plugin_error(
                        "init",
                        plugin.init(scene_path, ctx),
                        &mut self.error_queue,
                    );
                }
            } else {
                self.handle_scripts(0.0);

                for mut plugin in self.plugins.drain(..) {
                    let ctx = PluginContext {
                        scenes: &mut self.scenes,
                        resource_manager: &self.resource_manager,
                        graphics_context: &mut self.graphics_context,
                        dt: 0.0,
                        lag: &mut 0.0,
                        user_interfaces: &mut self.user_interfaces,
                        serialization_context: &self.serialization_context,
                        widget_constructors: &self.widget_constructors,
                        dyn_type_constructors: &self.dyn_type_constructors,
                        performance_statistics: &self.performance_statistics,
                        elapsed_time: self.elapsed_time,
                        script_processor: &self.script_processor,
                        loop_controller: controller,
                        task_pool: &mut self.task_pool,
                        input_state: &self.input_state,
                    };

                    // Deinit plugin first.
                    try_enqueue_plugin_error(
                        "on_deinit",
                        plugin.on_deinit(ctx),
                        &mut self.error_queue,
                    );
                }
            }
        }
    }

    fn register_plugin_internal(
        serialization_context: &Arc<SerializationContext>,
        widget_constructors: &Arc<WidgetConstructorContainer>,
        dyn_type_constructors: &Arc<DynTypeConstructorContainer>,
        resource_manager: &ResourceManager,
        plugin: &dyn Plugin,
        error_queue: &mut ErrorQueue,
    ) {
        try_enqueue_plugin_error(
            "register",
            plugin.register(PluginRegistrationContext {
                serialization_context,
                widget_constructors,
                dyn_type_constructors,
                resource_manager,
            }),
            error_queue,
        );
    }

    fn register_plugin(&mut self, plugin: &dyn Plugin) {
        Self::register_plugin_internal(
            &self.serialization_context,
            &self.widget_constructors,
            &self.dyn_type_constructors,
            &self.resource_manager,
            plugin,
            &mut self.error_queue,
        )
    }

    /// Adds a new static plugin.
    pub fn add_plugin<P>(&mut self, plugin: P)
    where
        P: Plugin + 'static,
    {
        self.register_plugin(&plugin);

        self.plugins.push(PluginContainer::Static(Box::new(plugin)));
    }

    /// Tries to add a new dynamic plugin. This method attempts to load a dynamic library by the
    /// given path and searches for `fyrox_plugin` function. This function is called to create a
    /// plugin instance. This method will fail if there's no dynamic library at the given path or
    /// the `fyrox_plugin` function is not found.
    ///
    /// # Hot reloading
    ///
    /// This method can enable hot reloading for the plugin, by setting `reload_when_changed` parameter
    /// to `true`. When enabled, the engine will clone the library to implementation-defined path
    /// and load it. It will setup file system watcher to receive changes from the OS and reload
    /// the plugin.
    pub fn add_dynamic_plugin<P>(
        &mut self,
        path: P,
        reload_when_changed: bool,
        use_relative_paths: bool,
    ) -> Result<&dyn Plugin, String>
    where
        P: AsRef<Path> + 'static,
    {
        Ok(self.add_dynamic_plugin_custom(DyLibDynamicPlugin::new(
            path,
            reload_when_changed,
            use_relative_paths,
        )?))
    }

    /// Adds a new abstract dynamic plugin
    pub fn add_dynamic_plugin_custom<P>(&mut self, plugin: P) -> &dyn Plugin
    where
        P: DynamicPlugin + 'static,
    {
        let display_name = plugin.display_name();

        let plugin_container = PluginContainer::Dynamic(Box::new(plugin));

        self.register_plugin(plugin_container.deref());
        self.plugins.push(plugin_container);

        Log::info(format!("Plugin {display_name:?} was loaded successfully"));

        &**self.plugins.last().unwrap()
    }

    /// Tries to reload a specified plugin. This method tries to perform least invasive reloading, by
    /// only detaching parts from the scenes and engine internals, that belongs to reloadable plugin.
    pub fn reload_plugin(
        &mut self,
        plugin_index: usize,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
    ) -> Result<(), String> {
        let plugin_container = &mut self.plugins[plugin_index];
        let PluginContainer::Dynamic(plugin) = plugin_container else {
            return Err(format!(
                "Plugin {plugin_index} is static and cannot be reloaded!",
            ));
        };

        if !plugin.is_loaded() {
            // TODO: this means that something bad happened during plugin reloading.
            // don't we want to recover from this situation by trying to load it again
            // (maybe with clearing  `need_reload` flag, to perform new attempt only when something is changed)
            return Err(format!("Cannot reload unloaded plugin {plugin_index}!"));
        }
        plugin.prepare_to_reload();

        let plugin_type_id = plugin.as_loaded_ref().type_id();
        let plugin_assembly_name = plugin.as_loaded_ref().assembly_name();

        // Collect all the data that belongs to the plugin
        let mut scenes_state = Vec::new();
        for (scene_handle, scene) in self.scenes.pair_iter_mut() {
            if let Some(data) = hotreload::SceneState::try_create_from_plugin(
                scene_handle,
                scene,
                &self.serialization_context,
                plugin.as_loaded_ref(),
            )? {
                scenes_state.push(data);
            }
        }

        // Check every prefab for plugin content.
        let mut prefab_scenes = Vec::new();
        let rm_state = self.resource_manager.state();
        for resource in rm_state.resources().iter() {
            if let Some(model) = resource.try_cast::<Model>() {
                let mut model_state = model.state();
                if let Some(data) = model_state.data() {
                    if let Some(scene_state) = hotreload::SceneState::try_create_from_plugin(
                        Handle::NONE,
                        &mut data.scene,
                        &self.serialization_context,
                        plugin.as_loaded_ref(),
                    )? {
                        prefab_scenes.push((model.clone(), scene_state));
                    }
                }
            }
        }
        drop(rm_state);

        // Search for script constructors, that belongs to dynamic plugins and remove them.
        let mut constructors = FxHashSet::default();
        for (type_uuid, constructor) in self.serialization_context.script_constructors.map().iter()
        {
            if constructor.assembly_name == plugin_assembly_name {
                constructors.insert(*type_uuid);
            }
        }
        for type_uuid in constructors.iter() {
            self.serialization_context
                .script_constructors
                .remove(*type_uuid);
        }

        // Search for node constructors, that belongs to dynamic plugins and remove them.
        let mut constructors = FxHashSet::default();
        for (type_uuid, constructor) in self.serialization_context.node_constructors.map().iter() {
            if constructor.assembly_name == plugin_assembly_name {
                constructors.insert(*type_uuid);
            }
        }
        for type_uuid in constructors.iter() {
            self.serialization_context
                .node_constructors
                .remove(*type_uuid);
        }

        // Search for widget constructors, that belongs to dynamic plugins and remove them.
        let mut constructors = FxHashSet::default();
        for (type_uuid, constructor) in self.widget_constructors.map().iter() {
            if constructor.assembly_name == plugin_assembly_name {
                constructors.insert(*type_uuid);
            }
        }
        for type_uuid in constructors.iter() {
            self.widget_constructors.remove(*type_uuid);
        }

        // Search for dyn type constructors, that belongs to dynamic plugins and remove them.
        let mut dyn_type_constructors = FxHashSet::default();
        for (type_uuid, constructor) in self.dyn_type_constructors.inner().iter() {
            if constructor.assembly_name == plugin_assembly_name {
                dyn_type_constructors.insert(*type_uuid);
            }
        }
        for type_uuid in dyn_type_constructors.iter() {
            self.dyn_type_constructors.remove(type_uuid);
        }

        // Reload resources, that belongs to the plugin.
        {
            let mut resources_to_reload = FxHashSet::default();
            let mut state = self.resource_manager.state();
            for resource in state.resources().iter() {
                let data = resource.lock();
                if let ResourceState::Ok { ref data, .. } = data.state {
                    data.as_reflect(&mut |reflect| {
                        if reflect.assembly_name() == plugin_assembly_name {
                            resources_to_reload.insert(resource.clone());
                        }
                    })
                }
            }

            for resource_to_reload in resources_to_reload.iter() {
                Log::info(format!(
                    "Reloading {:?} resource, because it is used in plugin {plugin_assembly_name}",
                    state.resource_path(resource_to_reload)
                ));

                state.reload_resource(resource_to_reload.clone());
            }

            drop(state);

            block_on(join_all(resources_to_reload));
        }

        // Unload custom render passes (if any).
        if let GraphicsContext::Initialized(ref mut graphics_context) = self.graphics_context {
            let render_passes = graphics_context.renderer.render_passes().to_vec();
            for render_pass in render_passes {
                if render_pass.borrow().source_type_id() == plugin_type_id {
                    graphics_context.renderer.remove_render_pass(render_pass);
                }
            }
        }

        let mut visitor = hotreload::make_writing_visitor();
        plugin
            .as_loaded_mut()
            .visit("Plugin", &mut visitor)
            .map_err(|e| e.to_string())?;
        let mut binary_blob = Cursor::new(Vec::<u8>::new());
        visitor
            .save_binary_to_memory(&mut binary_blob)
            .map_err(|e| e.to_string())?;

        Log::info(format!(
            "Plugin {plugin_index} was serialized successfully!"
        ));

        // Explicitly drop the visitor to prevent any destructors from the previous version of
        // the plugin to run at the end of the scope. This could happen, because the visitor
        // manages serialized smart pointers and if they'll be kept alive longer than the plugin
        // there's a very high chance of hard crash.
        drop(visitor);

        let binary_blob = binary_blob.into_inner();

        plugin.reload(&mut |plugin| {
            // Re-register the plugin. This is needed, because it might contain new script/node/widget
            // types (or removed ones too). This is done right before deserialization, because plugin
            // might contain some entities, that have dynamic registration.
            Self::register_plugin_internal(
                &self.serialization_context,
                &self.widget_constructors,
                &self.dyn_type_constructors,
                &self.resource_manager,
                plugin,
                &mut self.error_queue,
            );

            // New plugins may add custom resources and we must re-scan the data folder to include
            // such resources in the registry.
            self.resource_manager.update_or_load_registry();

            let mut visitor = hotreload::make_reading_visitor(
                &binary_blob,
                &self.serialization_context,
                &self.resource_manager,
                &self.widget_constructors,
                &self.dyn_type_constructors,
            )
            .map_err(|e| e.to_string())?;

            plugin
                .visit("Plugin", &mut visitor)
                .map_err(|e| e.to_string())?;
            Ok(())
        })?;

        // Deserialize prefab scene content.
        for (model, scene_state) in prefab_scenes {
            Log::info(format!(
                "Deserializing {} prefab content...",
                model.resource_uuid()
            ));

            scene_state.deserialize_into_prefab_scene(
                &model,
                &self.serialization_context,
                &self.resource_manager,
                &self.widget_constructors,
                &self.dyn_type_constructors,
            )?;
        }

        // Deserialize scene content.
        for scene_state in scenes_state {
            let scene = &mut self.scenes[scene_state.scene];
            scene_state.deserialize_into_scene(
                scene,
                &self.serialization_context,
                &self.resource_manager,
                &self.widget_constructors,
                &self.dyn_type_constructors,
            )?;
        }

        // Call `on_loaded` for plugins, so they could restore some runtime non-serializable state.
        let ctx = PluginContext {
            scenes: &mut self.scenes,
            resource_manager: &self.resource_manager,
            user_interfaces: &mut self.user_interfaces,
            graphics_context: &mut self.graphics_context,
            dt,
            lag,
            serialization_context: &self.serialization_context,
            widget_constructors: &self.widget_constructors,
            dyn_type_constructors: &self.dyn_type_constructors,
            performance_statistics: &Default::default(),
            elapsed_time: self.elapsed_time,
            script_processor: &self.script_processor,
            loop_controller: controller,
            task_pool: &mut self.task_pool,
            input_state: &self.input_state,
        };
        try_enqueue_plugin_error(
            "on_loaded",
            plugin.as_loaded_mut().on_loaded(ctx),
            &mut self.error_queue,
        );

        Log::info(format!("Plugin {plugin_index} was successfully reloaded!"));

        Ok(())
    }

    /// Returns a reference to the plugins.
    pub fn plugins(&self) -> &[PluginContainer] {
        &self.plugins
    }

    /// Returns a mutable reference to the plugins.
    pub fn plugins_mut(&mut self) -> &mut [PluginContainer] {
        &mut self.plugins
    }

    /// Tries to reload all dynamic plugins registered in the engine, that needs to be reloaded.
    pub fn reload_dynamic_plugins<F>(
        &mut self,
        dt: f32,
        controller: ApplicationLoopController,
        lag: &mut f32,
        mut on_reloaded: F,
    ) -> Result<(), String>
    where
        F: FnMut(&dyn Plugin),
    {
        for plugin_index in 0..self.plugins.len() {
            if let PluginContainer::Dynamic(plugin) = &self.plugins[plugin_index] {
                if plugin.is_reload_needed_now() {
                    self.reload_plugin(plugin_index, dt, controller, lag)?;

                    on_reloaded(self.plugins[plugin_index].deref_mut());
                }
            }
        }

        Ok(())
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        // Destroy all scenes first and correctly destroy all script instances.
        // This will ensure that any `on_destroy` logic will be executed before
        // engine destroyed.
        let scenes = self
            .scenes
            .pair_iter()
            .map(|(h, _)| h)
            .collect::<Vec<Handle<Scene>>>();

        for handle in scenes {
            self.scenes.remove(handle);
        }

        // Finally disable plugins.
        self.enable_plugins(
            None,
            false,
            ApplicationLoopController::Headless {
                running: &Default::default(),
            },
        );
    }
}

#[cfg(test)]
mod test {
    use crate::engine::ApplicationLoopController;
    use crate::plugin::error::GameResult;
    use crate::scene::pivot::Pivot;
    use crate::{
        asset::manager::ResourceManager,
        core::{
            pool::Handle, reflect::prelude::*, task::TaskPool, type_traits::prelude::*,
            visitor::prelude::*,
        },
        engine::{task::TaskPoolHandler, GraphicsContext, ScriptProcessor},
        graph::SceneGraph,
        scene::{base::BaseBuilder, node::Node, pivot::PivotBuilder, Scene, SceneContainer},
        script::{
            ScriptContext, ScriptDeinitContext, ScriptMessageContext, ScriptMessagePayload,
            ScriptTrait,
        },
    };
    use fyrox_resource::io::FsResourceIo;
    use fyrox_ui::UiContainer;
    use std::cell::Cell;
    use std::sync::{
        mpsc::{self, Sender, TryRecvError},
        Arc,
    };

    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    struct Source {
        node_handle: Handle<Node>,
        script_index: usize,
    }

    impl Source {
        fn from_ctx(ctx: &ScriptContext) -> Self {
            Self {
                node_handle: ctx.handle,
                script_index: ctx.script_index,
            }
        }

        fn from_deinit_ctx(ctx: &ScriptDeinitContext) -> Self {
            Self {
                node_handle: ctx.node_handle,
                script_index: ctx.script_index,
            }
        }

        fn from_msg_ctx(ctx: &ScriptMessageContext) -> Self {
            Self {
                node_handle: ctx.handle,
                script_index: ctx.script_index,
            }
        }
    }

    #[allow(clippy::enum_variant_names)]
    #[derive(PartialEq, Eq, Clone, Debug)]
    enum Event {
        Initialized(Source),
        Started(Source),
        Updated(Source),
        Destroyed(Source),
        EventReceived(Source),
    }

    #[derive(Debug, Clone, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "2569de84-d4b2-427d-969b-d5c7b31a0ba6")]
    struct MyScript {
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
        spawned: bool,
    }

    impl ScriptTrait for MyScript {
        fn on_init(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Initialized(Source::from_ctx(ctx)))
                .unwrap();

            // Spawn new entity with script.
            let handle = PivotBuilder::new(BaseBuilder::new().with_script(MySubScript {
                sender: self.sender.clone(),
            }))
            .build(&mut ctx.scene.graph);
            assert_eq!(handle, Handle::<Pivot>::new(2, 1));

            Ok(())
        }

        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Started(Source::from_ctx(ctx)))
                .unwrap();

            // Spawn new entity with script.
            let handle = PivotBuilder::new(BaseBuilder::new().with_script(MySubScript {
                sender: self.sender.clone(),
            }))
            .build(&mut ctx.scene.graph);
            assert_eq!(handle, Handle::<Pivot>::new(3, 1));

            Ok(())
        }

        fn on_deinit(&mut self, ctx: &mut ScriptDeinitContext) -> GameResult {
            self.sender
                .send(Event::Destroyed(Source::from_deinit_ctx(ctx)))
                .unwrap();

            Ok(())
        }

        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Updated(Source::from_ctx(ctx)))
                .unwrap();

            if !self.spawned {
                // Spawn new entity with script.
                PivotBuilder::new(BaseBuilder::new().with_script(MySubScript {
                    sender: self.sender.clone(),
                }))
                .build(&mut ctx.scene.graph);

                self.spawned = true;
            }

            Ok(())
        }
    }

    #[derive(Debug, Clone, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "1cebacd9-b500-4753-93be-39db344add21")]
    struct MySubScript {
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
    }

    impl ScriptTrait for MySubScript {
        fn on_init(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Initialized(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Started(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_deinit(&mut self, ctx: &mut ScriptDeinitContext) -> GameResult {
            self.sender
                .send(Event::Destroyed(Source::from_deinit_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Updated(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }
    }

    #[test]
    fn test_order() {
        let resource_manager =
            ResourceManager::new(Arc::new(FsResourceIo), Arc::new(Default::default()));
        let mut scene = Scene::new();

        let (tx, rx) = mpsc::channel();

        let node_handle = PivotBuilder::new(
            BaseBuilder::new()
                .with_script(MyScript {
                    sender: tx.clone(),
                    spawned: false,
                })
                .with_script(MySubScript { sender: tx }),
        )
        .build(&mut scene.graph)
        .to_base();
        assert_eq!(node_handle, Handle::<Pivot>::new(1, 1));

        let node_handle_0 = Source {
            node_handle,
            script_index: 0,
        };
        let node_handle_1 = Source {
            node_handle,
            script_index: 1,
        };

        let mut scene_container = SceneContainer::new(Default::default());

        let scene_handle = scene_container.add(scene);

        let mut script_processor = ScriptProcessor::default();

        script_processor.register_scripted_scene(scene_handle, &resource_manager);

        let handle_on_init = Source {
            node_handle: Handle::new(2, 1),
            script_index: 0,
        };
        let handle_on_start = Source {
            node_handle: Handle::new(3, 1),
            script_index: 0,
        };
        let handle_on_update1 = Source {
            node_handle: Handle::new(4, 1),
            script_index: 0,
        };
        let mut task_pool = TaskPoolHandler::new(Arc::new(TaskPool::new()));
        let mut gc = GraphicsContext::Uninitialized(Default::default());
        let mut user_interfaces = UiContainer::default();

        for iteration in 0..3 {
            script_processor.handle_scripts(
                &mut scene_container,
                &mut Vec::new(),
                &resource_manager,
                &mut task_pool,
                &mut gc,
                &mut user_interfaces,
                0.0,
                0.0,
                &Default::default(),
                &mut Default::default(),
            );

            match iteration {
                0 => {
                    assert_eq!(rx.try_recv(), Ok(Event::Initialized(node_handle_0)));
                    assert_eq!(rx.try_recv(), Ok(Event::Initialized(node_handle_1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Initialized(handle_on_init)));
                    assert_eq!(rx.try_recv(), Ok(Event::Started(node_handle_0)));
                    assert_eq!(rx.try_recv(), Ok(Event::Started(node_handle_1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Started(handle_on_init)));
                    assert_eq!(rx.try_recv(), Ok(Event::Initialized(handle_on_start)));
                    assert_eq!(rx.try_recv(), Ok(Event::Started(handle_on_start)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(node_handle_0)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(node_handle_1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_init)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_start)));
                    assert_eq!(rx.try_recv(), Ok(Event::Initialized(handle_on_update1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Started(handle_on_update1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_update1)));
                }
                1 => {
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(node_handle_0)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(node_handle_1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_init)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_start)));
                    assert_eq!(rx.try_recv(), Ok(Event::Updated(handle_on_update1)));
                    assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));

                    // Now destroy every node with script, next iteration should correctly destroy attached scripts.
                    let graph = &mut scene_container[scene_handle].graph;
                    graph.remove_node(node_handle);
                    graph.remove_node(handle_on_init.node_handle);
                    graph.remove_node(handle_on_start.node_handle);
                    graph.remove_node(handle_on_update1.node_handle);
                }
                2 => {
                    assert_eq!(rx.try_recv(), Ok(Event::Destroyed(node_handle_0)));
                    assert_eq!(rx.try_recv(), Ok(Event::Destroyed(node_handle_1)));
                    assert_eq!(rx.try_recv(), Ok(Event::Destroyed(handle_on_init)));
                    assert_eq!(rx.try_recv(), Ok(Event::Destroyed(handle_on_start)));
                    assert_eq!(rx.try_recv(), Ok(Event::Destroyed(handle_on_update1)));

                    // Every instance holding sender died, so receiver is disconnected from sender.
                    assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
                }
                _ => (),
            }
        }
    }

    #[derive(Debug, ScriptMessagePayload)]
    enum MyMessage {
        Foo(usize),
        Bar(String),
    }

    #[derive(Debug, Clone, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "bf2976ad-f41d-4de6-9a32-b1a293956058")]
    struct ScriptListeningToMessages {
        index: u32,
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
    }

    impl ScriptTrait for ScriptListeningToMessages {
        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            ctx.message_dispatcher.subscribe_to::<MyMessage>(ctx.handle);
            Ok(())
        }

        fn on_message(
            &mut self,
            message: &mut dyn ScriptMessagePayload,
            ctx: &mut ScriptMessageContext,
        ) -> GameResult {
            let typed_message = message.downcast_ref::<MyMessage>().unwrap();
            match self.index {
                0 => {
                    if let MyMessage::Foo(num) = typed_message {
                        assert_eq!(*num, 123);
                        self.sender
                            .send(Event::EventReceived(Source::from_msg_ctx(ctx)))
                            .unwrap();
                    } else {
                        unreachable!()
                    }
                }
                1 => {
                    if let MyMessage::Bar(string) = typed_message {
                        assert_eq!(string, "Foobar");
                        self.sender
                            .send(Event::EventReceived(Source::from_msg_ctx(ctx)))
                            .unwrap();
                    } else {
                        unreachable!()
                    }
                }
                _ => (),
            }

            self.index += 1;

            Ok(())
        }
    }

    #[derive(Debug, Clone, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "6bcbf9b4-9546-42d3-965a-de055ab85475")]
    struct ScriptSendingMessages {
        index: u32,
    }

    impl ScriptTrait for ScriptSendingMessages {
        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            match self.index {
                0 => ctx.message_sender.send_global(MyMessage::Foo(123)),
                1 => ctx
                    .message_sender
                    .send_global(MyMessage::Bar("Foobar".to_string())),
                _ => (),
            }
            self.index += 1;

            Ok(())
        }
    }

    #[test]
    fn test_messages() {
        let resource_manager =
            ResourceManager::new(Arc::new(FsResourceIo), Arc::new(Default::default()));
        let mut scene = Scene::new();

        let (tx, rx) = mpsc::channel();

        PivotBuilder::new(BaseBuilder::new().with_script(ScriptSendingMessages { index: 0 }))
            .build(&mut scene.graph);

        let receiver_messages =
            PivotBuilder::new(BaseBuilder::new().with_script(ScriptListeningToMessages {
                sender: tx,
                index: 0,
            }))
            .build(&mut scene.graph)
            .to_base();
        let receiver_messages_source = Source {
            node_handle: receiver_messages,
            script_index: 0,
        };

        let mut scene_container = SceneContainer::new(Default::default());

        let scene_handle = scene_container.add(scene);

        let mut script_processor = ScriptProcessor::default();
        let mut task_pool = TaskPoolHandler::new(Arc::new(TaskPool::new()));
        let mut gc = GraphicsContext::Uninitialized(Default::default());
        let mut user_interfaces = UiContainer::default();

        script_processor.register_scripted_scene(scene_handle, &resource_manager);

        for iteration in 0..2 {
            script_processor.handle_scripts(
                &mut scene_container,
                &mut Vec::new(),
                &resource_manager,
                &mut task_pool,
                &mut gc,
                &mut user_interfaces,
                0.0,
                0.0,
                &Default::default(),
                &mut Default::default(),
            );

            match iteration {
                0 => {
                    assert_eq!(
                        rx.try_recv(),
                        Ok(Event::EventReceived(receiver_messages_source))
                    );
                    assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
                }
                1 => {
                    assert_eq!(
                        rx.try_recv(),
                        Ok(Event::EventReceived(receiver_messages_source))
                    );
                    assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
                }
                _ => (),
            }
        }
    }

    #[derive(Clone, Debug, PartialEq, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "7bcbf9b4-9546-42d3-965a-de055ab85475")]
    pub struct ScriptSpawningAsyncTasks {
        num: Option<u32>,
    }

    impl ScriptTrait for ScriptSpawningAsyncTasks {
        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            ctx.task_pool.spawn_script_task(
                ctx.scene_handle,
                ctx.handle,
                ctx.script_index,
                async move { 123u32 },
                |result, script: &mut ScriptSpawningAsyncTasks, _ctx| {
                    assert_eq!(result, 123u32);
                    script.num = Some(result);
                    Ok(())
                },
            );
            Ok(())
        }
    }

    #[derive(Clone, Debug, PartialEq, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "8bcbf9b4-9546-42d3-965a-de055ab85475")]
    pub struct ScriptWithoutAsyncTasks {}

    impl ScriptTrait for ScriptWithoutAsyncTasks {}

    #[test]
    #[cfg(not(target_os = "macos"))] // This fails on macOS for some reason.
    fn test_async_script_tasks() {
        use crate::engine::{Engine, EngineInitParams};

        let task_pool = Arc::new(TaskPool::default());
        let mut engine = Engine::new(EngineInitParams {
            graphics_context_params: Default::default(),
            serialization_context: Arc::new(Default::default()),
            widget_constructors: Arc::new(Default::default()),
            dyn_type_constructors: Arc::new(Default::default()),
            resource_manager: ResourceManager::new(Arc::new(FsResourceIo), task_pool.clone()),
            task_pool,
        })
        .unwrap();

        let is_running = Cell::new(true);

        engine.enable_plugins(
            None,
            true,
            ApplicationLoopController::Headless {
                running: &is_running,
            },
        );

        let mut scene = Scene::new();

        let handle = PivotBuilder::new(
            BaseBuilder::new()
                .with_script(ScriptSpawningAsyncTasks { num: None })
                .with_script(ScriptWithoutAsyncTasks {}),
        )
        .build(&mut scene.graph);

        let scene_handle = engine.scenes.add(scene);

        engine.register_scripted_scene(scene_handle);

        // Spin for some time.
        let mut time = 0.0;
        let dt = 1.0 / 60.0;
        let mut lag = 0.0;
        while time <= 10.0 {
            engine.update(
                dt,
                ApplicationLoopController::Headless {
                    running: &is_running,
                },
                &mut lag,
                Default::default(),
            );
            time += dt;
        }

        // Ensure that the tasks are finished and correctly handled.
        let mut scripts = engine.scenes[scene_handle].graph[handle].scripts();
        assert_eq!(
            scripts
                .next()
                .and_then(|s| s.cast::<ScriptSpawningAsyncTasks>()),
            Some(&ScriptSpawningAsyncTasks { num: Some(123) })
        );
        assert_eq!(
            scripts
                .next()
                .and_then(|s| s.cast::<ScriptWithoutAsyncTasks>()),
            Some(&ScriptWithoutAsyncTasks {})
        );
    }

    #[derive(Clone, Debug, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "9bcbf9b4-9546-42d3-965a-de055ab85475")]
    pub struct ScriptThatDeletesItself {
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
    }

    impl ScriptTrait for ScriptThatDeletesItself {
        fn on_init(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Initialized(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Started(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_deinit(&mut self, ctx: &mut ScriptDeinitContext) -> GameResult {
            self.sender
                .send(Event::Destroyed(Source::from_deinit_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Updated(Source::from_ctx(ctx)))
                .unwrap();

            let node = &mut ctx.scene.graph[ctx.handle];
            node.remove_script(ctx.script_index);
            Ok(())
        }
    }

    #[derive(Clone, Debug, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "9bcbf9b4-9546-42d3-965a-de055ab85475")]
    pub struct ScriptThatAddsScripts {
        num: usize,
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
    }

    impl ScriptTrait for ScriptThatAddsScripts {
        fn on_init(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Initialized(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Started(Source::from_ctx(ctx)))
                .unwrap();

            for i in 0..self.num {
                ctx.scene.graph[ctx.handle].add_script(SimpleScript {
                    stuff: i,
                    sender: self.sender.clone(),
                });
            }

            Ok(())
        }

        fn on_deinit(&mut self, ctx: &mut ScriptDeinitContext) -> GameResult {
            self.sender
                .send(Event::Destroyed(Source::from_deinit_ctx(ctx)))
                .unwrap();

            Ok(())
        }

        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Updated(Source::from_ctx(ctx)))
                .unwrap();

            Ok(())
        }
    }

    #[derive(Clone, Debug, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "9bcbf9b4-9546-42d3-965a-de055ab85475")]
    pub struct SimpleScript {
        stuff: usize,
        #[reflect(hidden)]
        #[visit(skip)]
        sender: Sender<Event>,
    }

    impl ScriptTrait for SimpleScript {
        fn on_init(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Initialized(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_start(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Started(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_deinit(&mut self, ctx: &mut ScriptDeinitContext) -> GameResult {
            self.sender
                .send(Event::Destroyed(Source::from_deinit_ctx(ctx)))
                .unwrap();
            Ok(())
        }

        fn on_update(&mut self, ctx: &mut ScriptContext) -> GameResult {
            self.sender
                .send(Event::Updated(Source::from_ctx(ctx)))
                .unwrap();
            Ok(())
        }
    }

    #[test]
    fn test_script_adding_removing() {
        let resource_manager =
            ResourceManager::new(Arc::new(FsResourceIo), Arc::new(Default::default()));
        let mut scene = Scene::new();

        let (tx, rx) = mpsc::channel();

        let node_handle = PivotBuilder::new(
            BaseBuilder::new()
                .with_script(ScriptThatDeletesItself { sender: tx.clone() })
                .with_script(ScriptThatAddsScripts { num: 2, sender: tx }),
        )
        .build(&mut scene.graph)
        .to_base();
        assert_eq!(node_handle, Handle::<Node>::new(1, 1));

        let mut scene_container = SceneContainer::new(Default::default());

        let scene_handle = scene_container.add(scene);

        let mut script_processor = ScriptProcessor::default();

        script_processor.register_scripted_scene(scene_handle, &resource_manager);

        let mut task_pool = TaskPoolHandler::new(Arc::new(TaskPool::new()));
        let mut gc = GraphicsContext::Uninitialized(Default::default());
        let mut user_interfaces = UiContainer::default();

        for iteration in 0..2 {
            script_processor.handle_scripts(
                &mut scene_container,
                &mut Vec::new(),
                &resource_manager,
                &mut task_pool,
                &mut gc,
                &mut user_interfaces,
                0.0,
                0.0,
                &Default::default(),
                &mut Default::default(),
            );

            match iteration {
                0 => {
                    for i in 0..2 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Initialized(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }
                    for i in 0..2 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Started(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }
                    for i in 2..4 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Initialized(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }
                    for i in 2..4 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Started(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }
                    for i in 0..4 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Updated(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }
                    assert_eq!(
                        rx.try_recv(),
                        Ok(Event::Destroyed(Source {
                            node_handle,
                            script_index: 0,
                        }))
                    );

                    assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
                }
                1 => {
                    for i in 0..3 {
                        assert_eq!(
                            rx.try_recv(),
                            Ok(Event::Updated(Source {
                                node_handle,
                                script_index: i,
                            }))
                        );
                    }

                    assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
                }
                _ => (),
            }
        }
    }
}