summaryrefslogtreecommitdiff
path: root/servers/rendering/rendering_server_scene.cpp
blob: d66708587a2472ae78cf63236fc2a9405689382e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
/*************************************************************************/
/*  rendering_server_scene.cpp                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#include "rendering_server_scene.h"

#include "core/os/os.h"
#include "rendering_server_globals.h"
#include "rendering_server_raster.h"

#include <new>

/* CAMERA API */

RID RenderingServerScene::camera_create() {

	Camera *camera = memnew(Camera);
	return camera_owner.make_rid(camera);
}

void RenderingServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->type = Camera::PERSPECTIVE;
	camera->fov = p_fovy_degrees;
	camera->znear = p_z_near;
	camera->zfar = p_z_far;
}

void RenderingServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->type = Camera::ORTHOGONAL;
	camera->size = p_size;
	camera->znear = p_z_near;
	camera->zfar = p_z_far;
}

void RenderingServerScene::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->type = Camera::FRUSTUM;
	camera->size = p_size;
	camera->offset = p_offset;
	camera->znear = p_z_near;
	camera->zfar = p_z_far;
}

void RenderingServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->transform = p_transform.orthonormalized();
}

void RenderingServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);

	camera->visible_layers = p_layers;
}

void RenderingServerScene::camera_set_environment(RID p_camera, RID p_env) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->env = p_env;
}

void RenderingServerScene::camera_set_camera_effects(RID p_camera, RID p_fx) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->effects = p_fx;
}

void RenderingServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);
	camera->vaspect = p_enable;
}

/* SCENARIO API */

void *RenderingServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {

	//RenderingServerScene *self = (RenderingServerScene*)p_self;
	Instance *A = p_A;
	Instance *B = p_B;

	//instance indices are designed so greater always contains lesser
	if (A->base_type > B->base_type) {
		SWAP(A, B); //lesser always first
	}

	if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		InstanceLightData::PairInfo pinfo;
		pinfo.geometry = A;
		pinfo.L = geom->lighting.push_back(B);

		List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);

		if (geom->can_cast_shadows) {

			light->shadow_dirty = true;
		}
		geom->lighting_dirty = true;

		return E; //this element should make freeing faster
	} else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		InstanceReflectionProbeData::PairInfo pinfo;
		pinfo.geometry = A;
		pinfo.L = geom->reflection_probes.push_back(B);

		List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);

		geom->reflection_dirty = true;

		return E; //this element should make freeing faster
	} else if (B->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		InstanceLightmapCaptureData::PairInfo pinfo;
		pinfo.geometry = A;
		pinfo.L = geom->lightmap_captures.push_back(B);

		List<InstanceLightmapCaptureData::PairInfo>::Element *E = lightmap_capture->geometries.push_back(pinfo);
		((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture

		return E; //this element should make freeing faster
	} else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		InstanceGIProbeData::PairInfo pinfo;
		pinfo.geometry = A;
		pinfo.L = geom->gi_probes.push_back(B);

		List<InstanceGIProbeData::PairInfo>::Element *E;
		if (A->dynamic_gi) {
			E = gi_probe->dynamic_geometries.push_back(pinfo);
		} else {
			E = gi_probe->geometries.push_back(pinfo);
		}

		geom->gi_probes_dirty = true;

		return E; //this element should make freeing faster

	} else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {

		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
		return gi_probe->lights.insert(A);
	}

	return nullptr;
}
void RenderingServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {

	//RenderingServerScene *self = (RenderingServerScene*)p_self;
	Instance *A = p_A;
	Instance *B = p_B;

	//instance indices are designed so greater always contains lesser
	if (A->base_type > B->base_type) {
		SWAP(A, B); //lesser always first
	}

	if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);

		geom->lighting.erase(E->get().L);
		light->geometries.erase(E);

		if (geom->can_cast_shadows) {
			light->shadow_dirty = true;
		}
		geom->lighting_dirty = true;

	} else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);

		geom->reflection_probes.erase(E->get().L);
		reflection_probe->geometries.erase(E);

		geom->reflection_dirty = true;
	} else if (B->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		List<InstanceLightmapCaptureData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapCaptureData::PairInfo>::Element *>(udata);

		geom->lightmap_captures.erase(E->get().L);
		lightmap_capture->geometries.erase(E);
		((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture

	} else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {

		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);

		List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);

		geom->gi_probes.erase(E->get().L);
		if (A->dynamic_gi) {
			gi_probe->dynamic_geometries.erase(E);
		} else {
			gi_probe->geometries.erase(E);
		}

		geom->gi_probes_dirty = true;

	} else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {

		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
		Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);

		gi_probe->lights.erase(E);
	}
}

RID RenderingServerScene::scenario_create() {

	Scenario *scenario = memnew(Scenario);
	ERR_FAIL_COND_V(!scenario, RID());
	RID scenario_rid = scenario_owner.make_rid(scenario);
	scenario->self = scenario_rid;

	scenario->octree.set_pair_callback(_instance_pair, this);
	scenario->octree.set_unpair_callback(_instance_unpair, this);
	scenario->reflection_probe_shadow_atlas = RSG::scene_render->shadow_atlas_create();
	RSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
	RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
	RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
	RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
	RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
	scenario->reflection_atlas = RSG::scene_render->reflection_atlas_create();
	return scenario_rid;
}

void RenderingServerScene::scenario_set_debug(RID p_scenario, RS::ScenarioDebugMode p_debug_mode) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND(!scenario);
	scenario->debug = p_debug_mode;
}

void RenderingServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND(!scenario);
	scenario->environment = p_environment;
}

void RenderingServerScene::scenario_set_camera_effects(RID p_scenario, RID p_camera_effects) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND(!scenario);
	scenario->camera_effects = p_camera_effects;
}

void RenderingServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND(!scenario);
	scenario->fallback_environment = p_environment;
}

void RenderingServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND(!scenario);
	RSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
}

/* INSTANCING API */

void RenderingServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) {

	if (p_update_aabb)
		p_instance->update_aabb = true;
	if (p_update_dependencies)
		p_instance->update_dependencies = true;

	if (p_instance->update_item.in_list())
		return;

	_instance_update_list.add(&p_instance->update_item);
}

RID RenderingServerScene::instance_create() {

	Instance *instance = memnew(Instance);
	ERR_FAIL_COND_V(!instance, RID());

	RID instance_rid = instance_owner.make_rid(instance);
	instance->self = instance_rid;

	return instance_rid;
}

void RenderingServerScene::instance_set_base(RID p_instance, RID p_base) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	Scenario *scenario = instance->scenario;

	if (instance->base_type != RS::INSTANCE_NONE) {
		//free anything related to that base

		if (scenario && instance->octree_id) {
			scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
			instance->octree_id = 0;
		}

		switch (instance->base_type) {
			case RS::INSTANCE_LIGHT: {

				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
#ifdef DEBUG_ENABLED
				if (light->geometries.size()) {
					ERR_PRINT("BUG, indexing did not unpair geometries from light.");
				}
#endif
				if (instance->scenario && light->D) {
					instance->scenario->directional_lights.erase(light->D);
					light->D = nullptr;
				}
				RSG::scene_render->free(light->instance);
			} break;
			case RS::INSTANCE_REFLECTION_PROBE: {

				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
				RSG::scene_render->free(reflection_probe->instance);
				if (reflection_probe->update_list.in_list()) {
					reflection_probe_render_list.remove(&reflection_probe->update_list);
				}
			} break;
			case RS::INSTANCE_LIGHTMAP_CAPTURE: {

				InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(instance->base_data);
				//erase dependencies, since no longer a lightmap
				while (lightmap_capture->users.front()) {
					instance_set_use_lightmap(lightmap_capture->users.front()->get()->self, RID(), RID());
				}
			} break;
			case RS::INSTANCE_GI_PROBE: {

				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
#ifdef DEBUG_ENABLED
				if (gi_probe->geometries.size()) {
					ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
				}
#endif
#ifdef DEBUG_ENABLED
				if (gi_probe->lights.size()) {
					ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
				}
#endif
				if (gi_probe->update_element.in_list()) {
					gi_probe_update_list.remove(&gi_probe->update_element);
				}

				if (instance->lightmap_capture) {
					Instance *capture = (Instance *)instance->lightmap_capture;
					InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(capture->base_data);
					lightmap_capture->users.erase(instance);
					instance->lightmap_capture = nullptr;
					instance->lightmap = RID();
				}

				RSG::scene_render->free(gi_probe->probe_instance);

			} break;
			default: {
			}
		}

		if (instance->base_data) {
			memdelete(instance->base_data);
			instance->base_data = nullptr;
		}

		instance->blend_values.clear();
		instance->materials.clear();
	}

	instance->base_type = RS::INSTANCE_NONE;
	instance->base = RID();

	if (p_base.is_valid()) {

		instance->base_type = RSG::storage->get_base_type(p_base);
		ERR_FAIL_COND(instance->base_type == RS::INSTANCE_NONE);

		switch (instance->base_type) {
			case RS::INSTANCE_LIGHT: {

				InstanceLightData *light = memnew(InstanceLightData);

				if (scenario && RSG::storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
					light->D = scenario->directional_lights.push_back(instance);
				}

				light->instance = RSG::scene_render->light_instance_create(p_base);

				instance->base_data = light;
			} break;
			case RS::INSTANCE_MESH:
			case RS::INSTANCE_MULTIMESH:
			case RS::INSTANCE_IMMEDIATE:
			case RS::INSTANCE_PARTICLES: {

				InstanceGeometryData *geom = memnew(InstanceGeometryData);
				instance->base_data = geom;
				if (instance->base_type == RS::INSTANCE_MESH) {
					instance->blend_values.resize(RSG::storage->mesh_get_blend_shape_count(p_base));
				}
			} break;
			case RS::INSTANCE_REFLECTION_PROBE: {

				InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
				reflection_probe->owner = instance;
				instance->base_data = reflection_probe;

				reflection_probe->instance = RSG::scene_render->reflection_probe_instance_create(p_base);
			} break;
			case RS::INSTANCE_LIGHTMAP_CAPTURE: {

				InstanceLightmapCaptureData *lightmap_capture = memnew(InstanceLightmapCaptureData);
				instance->base_data = lightmap_capture;
				//lightmap_capture->instance = RSG::scene_render->lightmap_capture_instance_create(p_base);
			} break;
			case RS::INSTANCE_GI_PROBE: {

				InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
				instance->base_data = gi_probe;
				gi_probe->owner = instance;

				if (scenario && !gi_probe->update_element.in_list()) {
					gi_probe_update_list.add(&gi_probe->update_element);
				}

				gi_probe->probe_instance = RSG::scene_render->gi_probe_instance_create(p_base);

			} break;
			default: {
			}
		}

		instance->base = p_base;

		//forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
		RSG::storage->base_update_dependency(p_base, instance);
	}

	_instance_queue_update(instance, true, true);
}
void RenderingServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->scenario) {

		instance->scenario->instances.remove(&instance->scenario_item);

		if (instance->octree_id) {
			instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
			instance->octree_id = 0;
		}

		switch (instance->base_type) {

			case RS::INSTANCE_LIGHT: {

				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
#ifdef DEBUG_ENABLED
				if (light->geometries.size()) {
					ERR_PRINT("BUG, indexing did not unpair geometries from light.");
				}
#endif
				if (light->D) {
					instance->scenario->directional_lights.erase(light->D);
					light->D = nullptr;
				}
			} break;
			case RS::INSTANCE_REFLECTION_PROBE: {
				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
				RSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);

			} break;
			case RS::INSTANCE_GI_PROBE: {

				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);

#ifdef DEBUG_ENABLED
				if (gi_probe->geometries.size()) {
					ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
				}
#endif
#ifdef DEBUG_ENABLED
				if (gi_probe->lights.size()) {
					ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
				}
#endif

				if (gi_probe->update_element.in_list()) {
					gi_probe_update_list.remove(&gi_probe->update_element);
				}
			} break;
			default: {
			}
		}

		instance->scenario = nullptr;
	}

	if (p_scenario.is_valid()) {

		Scenario *scenario = scenario_owner.getornull(p_scenario);
		ERR_FAIL_COND(!scenario);

		instance->scenario = scenario;

		scenario->instances.add(&instance->scenario_item);

		switch (instance->base_type) {

			case RS::INSTANCE_LIGHT: {

				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);

				if (RSG::storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
					light->D = scenario->directional_lights.push_back(instance);
				}
			} break;
			case RS::INSTANCE_GI_PROBE: {

				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
				if (!gi_probe->update_element.in_list()) {
					gi_probe_update_list.add(&gi_probe->update_element);
				}
			} break;
			default: {
			}
		}

		_instance_queue_update(instance, true, true);
	}
}
void RenderingServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	instance->layer_mask = p_mask;
}
void RenderingServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->transform == p_transform)
		return; //must be checked to avoid worst evil

#ifdef DEBUG_ENABLED

	for (int i = 0; i < 4; i++) {
		const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
		ERR_FAIL_COND(Math::is_inf(v.x));
		ERR_FAIL_COND(Math::is_nan(v.x));
		ERR_FAIL_COND(Math::is_inf(v.y));
		ERR_FAIL_COND(Math::is_nan(v.y));
		ERR_FAIL_COND(Math::is_inf(v.z));
		ERR_FAIL_COND(Math::is_nan(v.z));
	}

#endif
	instance->transform = p_transform;
	_instance_queue_update(instance, true);
}
void RenderingServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	instance->object_id = p_id;
}
void RenderingServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->update_item.in_list()) {
		_update_dirty_instance(instance);
	}

	ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
	instance->blend_values.write[p_shape] = p_weight;
}

void RenderingServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->base_type == RS::INSTANCE_MESH) {
		//may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
		instance->materials.resize(MAX(p_surface + 1, RSG::storage->mesh_get_surface_count(instance->base)));
	}

	ERR_FAIL_INDEX(p_surface, instance->materials.size());

	instance->materials.write[p_surface] = p_material;

	_instance_queue_update(instance, false, true);
}

void RenderingServerScene::instance_set_visible(RID p_instance, bool p_visible) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->visible == p_visible)
		return;

	instance->visible = p_visible;

	switch (instance->base_type) {
		case RS::INSTANCE_LIGHT: {
			if (RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHT, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
			}

		} break;
		case RS::INSTANCE_REFLECTION_PROBE: {
			if (instance->octree_id && instance->scenario) {
				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_REFLECTION_PROBE, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
			}

		} break;
		case RS::INSTANCE_LIGHTMAP_CAPTURE: {
			if (instance->octree_id && instance->scenario) {
				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHTMAP_CAPTURE, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
			}

		} break;
		case RS::INSTANCE_GI_PROBE: {
			if (instance->octree_id && instance->scenario) {
				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_GI_PROBE, p_visible ? (RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT)) : 0);
			}

		} break;
		default: {
		}
	}
}
inline bool is_geometry_instance(RenderingServer::InstanceType p_type) {
	return p_type == RS::INSTANCE_MESH || p_type == RS::INSTANCE_MULTIMESH || p_type == RS::INSTANCE_PARTICLES || p_type == RS::INSTANCE_IMMEDIATE;
}

void RenderingServerScene::instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->lightmap_capture) {
		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
		lightmap_capture->users.erase(instance);
		instance->lightmap = RID();
		instance->lightmap_capture = nullptr;
	}

	if (p_lightmap_instance.is_valid()) {
		Instance *lightmap_instance = instance_owner.getornull(p_lightmap_instance);
		ERR_FAIL_COND(!lightmap_instance);
		ERR_FAIL_COND(lightmap_instance->base_type != RS::INSTANCE_LIGHTMAP_CAPTURE);
		instance->lightmap_capture = lightmap_instance;

		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
		lightmap_capture->users.insert(instance);
		instance->lightmap = p_lightmap;
	}
}

void RenderingServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);
	ERR_FAIL_COND(!is_geometry_instance(instance->base_type));

	if (p_aabb != AABB()) {

		// Set custom AABB
		if (instance->custom_aabb == nullptr)
			instance->custom_aabb = memnew(AABB);
		*instance->custom_aabb = p_aabb;

	} else {

		// Clear custom AABB
		if (instance->custom_aabb != nullptr) {
			memdelete(instance->custom_aabb);
			instance->custom_aabb = nullptr;
		}
	}

	if (instance->scenario)
		_instance_queue_update(instance, true, false);
}

void RenderingServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	if (instance->skeleton == p_skeleton)
		return;

	instance->skeleton = p_skeleton;

	if (p_skeleton.is_valid()) {
		//update the dependency now, so if cleared, we remove it
		RSG::storage->skeleton_update_dependency(p_skeleton, instance);
	}
	_instance_queue_update(instance, true, true);
}

void RenderingServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
}

void RenderingServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	instance->extra_margin = p_margin;
	_instance_queue_update(instance, true, false);
}

Vector<ObjectID> RenderingServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {

	Vector<ObjectID> instances;
	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND_V(!scenario, instances);

	const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling

	int culled = 0;
	Instance *cull[1024];
	culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);

	for (int i = 0; i < culled; i++) {

		Instance *instance = cull[i];
		ERR_CONTINUE(!instance);
		if (instance->object_id.is_null())
			continue;

		instances.push_back(instance->object_id);
	}

	return instances;
}
Vector<ObjectID> RenderingServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {

	Vector<ObjectID> instances;
	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND_V(!scenario, instances);
	const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling

	int culled = 0;
	Instance *cull[1024];
	culled = scenario->octree.cull_segment(p_from, p_from + p_to * 10000, cull, 1024);

	for (int i = 0; i < culled; i++) {
		Instance *instance = cull[i];
		ERR_CONTINUE(!instance);
		if (instance->object_id.is_null())
			continue;

		instances.push_back(instance->object_id);
	}

	return instances;
}
Vector<ObjectID> RenderingServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {

	Vector<ObjectID> instances;
	Scenario *scenario = scenario_owner.getornull(p_scenario);
	ERR_FAIL_COND_V(!scenario, instances);
	const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling

	int culled = 0;
	Instance *cull[1024];

	culled = scenario->octree.cull_convex(p_convex, cull, 1024);

	for (int i = 0; i < culled; i++) {

		Instance *instance = cull[i];
		ERR_CONTINUE(!instance);
		if (instance->object_id.is_null())
			continue;

		instances.push_back(instance->object_id);
	}

	return instances;
}

void RenderingServerScene::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	//ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));

	switch (p_flags) {

		case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {

			instance->baked_light = p_enabled;

		} break;
		case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {

			if (p_enabled == instance->dynamic_gi) {
				//bye, redundant
				return;
			}

			if (instance->octree_id != 0) {
				//remove from octree, it needs to be re-paired
				instance->scenario->octree.erase(instance->octree_id);
				instance->octree_id = 0;
				_instance_queue_update(instance, true, true);
			}

			//once out of octree, can be changed
			instance->dynamic_gi = p_enabled;

		} break;
		case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {

			instance->redraw_if_visible = p_enabled;

		} break;
		default: {
		}
	}
}
void RenderingServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	instance->cast_shadows = p_shadow_casting_setting;
	_instance_queue_update(instance, false, true);
}
void RenderingServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {

	Instance *instance = instance_owner.getornull(p_instance);
	ERR_FAIL_COND(!instance);

	instance->material_override = p_material;
	_instance_queue_update(instance, false, true);
}

void RenderingServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
}
void RenderingServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
}

void RenderingServerScene::_update_instance(Instance *p_instance) {

	p_instance->version++;

	if (p_instance->base_type == RS::INSTANCE_LIGHT) {

		InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);

		RSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
		light->shadow_dirty = true;
	}

	if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {

		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);

		RSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
		reflection_probe->reflection_dirty = true;
	}

	if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {

		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);

		RSG::scene_render->gi_probe_instance_set_transform_to_data(gi_probe->probe_instance, p_instance->transform);
	}

	if (p_instance->base_type == RS::INSTANCE_PARTICLES) {

		RSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
	}

	if (p_instance->aabb.has_no_surface()) {
		return;
	}

	if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {

		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
		//make sure lights are updated if it casts shadow

		if (geom->can_cast_shadows) {
			for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
				InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
				light->shadow_dirty = true;
			}
		}

		if (!p_instance->lightmap_capture && geom->lightmap_captures.size()) {
			//affected by lightmap captures, must update capture info!
			_update_instance_lightmap_captures(p_instance);
		} else {
			if (!p_instance->lightmap_capture_data.empty()) {
				p_instance->lightmap_capture_data.resize(0); //not in use, clear capture data
			}
		}
	}

	p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;

	AABB new_aabb;

	new_aabb = p_instance->transform.xform(p_instance->aabb);

	p_instance->transformed_aabb = new_aabb;

	if (!p_instance->scenario) {

		return;
	}

	if (p_instance->octree_id == 0) {

		uint32_t base_type = 1 << p_instance->base_type;
		uint32_t pairable_mask = 0;
		bool pairable = false;

		if (p_instance->base_type == RS::INSTANCE_LIGHT || p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE) {

			pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK : 0;
			pairable = true;
		}

		if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
			//lights and geometries
			pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT) : 0;
			pairable = true;
		}

		// not inside octree
		p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);

	} else {

		/*
		if (new_aabb==p_instance->data.transformed_aabb)
			return;
		*/

		p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
	}
}

void RenderingServerScene::_update_instance_aabb(Instance *p_instance) {

	AABB new_aabb;

	ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());

	switch (p_instance->base_type) {
		case RenderingServer::INSTANCE_NONE: {

			// do nothing
		} break;
		case RenderingServer::INSTANCE_MESH: {

			if (p_instance->custom_aabb)
				new_aabb = *p_instance->custom_aabb;
			else
				new_aabb = RSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);

		} break;

		case RenderingServer::INSTANCE_MULTIMESH: {

			if (p_instance->custom_aabb)
				new_aabb = *p_instance->custom_aabb;
			else
				new_aabb = RSG::storage->multimesh_get_aabb(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_IMMEDIATE: {

			if (p_instance->custom_aabb)
				new_aabb = *p_instance->custom_aabb;
			else
				new_aabb = RSG::storage->immediate_get_aabb(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_PARTICLES: {

			if (p_instance->custom_aabb)
				new_aabb = *p_instance->custom_aabb;
			else
				new_aabb = RSG::storage->particles_get_aabb(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_LIGHT: {

			new_aabb = RSG::storage->light_get_aabb(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_REFLECTION_PROBE: {

			new_aabb = RSG::storage->reflection_probe_get_aabb(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_GI_PROBE: {

			new_aabb = RSG::storage->gi_probe_get_bounds(p_instance->base);

		} break;
		case RenderingServer::INSTANCE_LIGHTMAP_CAPTURE: {

			new_aabb = RSG::storage->lightmap_capture_get_bounds(p_instance->base);

		} break;
		default: {
		}
	}

	// <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
	if (p_instance->extra_margin)
		new_aabb.grow_by(p_instance->extra_margin);

	p_instance->aabb = new_aabb;
}

_FORCE_INLINE_ static void _light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree *p_octree, int p_cell_subdiv, const Vector3 &p_pos, const Vector3 &p_dir, float p_level, Vector3 &r_color, float &r_alpha) {

	static const Vector3 aniso_normal[6] = {
		Vector3(-1, 0, 0),
		Vector3(1, 0, 0),
		Vector3(0, -1, 0),
		Vector3(0, 1, 0),
		Vector3(0, 0, -1),
		Vector3(0, 0, 1)
	};

	int size = 1 << (p_cell_subdiv - 1);

	int clamp_v = size - 1;
	//first of all, clamp
	Vector3 pos;
	pos.x = CLAMP(p_pos.x, 0, clamp_v);
	pos.y = CLAMP(p_pos.y, 0, clamp_v);
	pos.z = CLAMP(p_pos.z, 0, clamp_v);

	float level = (p_cell_subdiv - 1) - p_level;

	int target_level;
	float level_filter;
	if (level <= 0.0) {
		level_filter = 0;
		target_level = 0;
	} else {
		target_level = Math::ceil(level);
		level_filter = target_level - level;
	}

	Vector3 color[2][8];
	float alpha[2][8];
	zeromem(alpha, sizeof(float) * 2 * 8);

	//find cell at given level first

	for (int c = 0; c < 2; c++) {

		int current_level = MAX(0, target_level - c);
		int level_cell_size = (1 << (p_cell_subdiv - 1)) >> current_level;

		for (int n = 0; n < 8; n++) {

			int x = int(pos.x);
			int y = int(pos.y);
			int z = int(pos.z);

			if (n & 1)
				x += level_cell_size;
			if (n & 2)
				y += level_cell_size;
			if (n & 4)
				z += level_cell_size;

			int ofs_x = 0;
			int ofs_y = 0;
			int ofs_z = 0;

			x = CLAMP(x, 0, clamp_v);
			y = CLAMP(y, 0, clamp_v);
			z = CLAMP(z, 0, clamp_v);

			int half = size / 2;
			uint32_t cell = 0;
			for (int i = 0; i < current_level; i++) {

				const RasterizerStorage::LightmapCaptureOctree *bc = &p_octree[cell];

				int child = 0;
				if (x >= ofs_x + half) {
					child |= 1;
					ofs_x += half;
				}
				if (y >= ofs_y + half) {
					child |= 2;
					ofs_y += half;
				}
				if (z >= ofs_z + half) {
					child |= 4;
					ofs_z += half;
				}

				cell = bc->children[child];
				if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY)
					break;

				half >>= 1;
			}

			if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
				alpha[c][n] = 0;
			} else {
				alpha[c][n] = p_octree[cell].alpha;

				for (int i = 0; i < 6; i++) {
					//anisotropic read light
					float amount = p_dir.dot(aniso_normal[i]);
					if (amount < 0)
						amount = 0;
					color[c][n].x += p_octree[cell].light[i][0] / 1024.0 * amount;
					color[c][n].y += p_octree[cell].light[i][1] / 1024.0 * amount;
					color[c][n].z += p_octree[cell].light[i][2] / 1024.0 * amount;
				}
			}

			//print_line("\tlev " + itos(c) + " - " + itos(n) + " alpha: " + rtos(cells[test_cell].alpha) + " col: " + color[c][n]);
		}
	}

	float target_level_size = size >> target_level;
	Vector3 pos_fract[2];

	pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
	pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
	pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;

	target_level_size = size >> MAX(0, target_level - 1);

	pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
	pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
	pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;

	float alpha_interp[2];
	Vector3 color_interp[2];

	for (int i = 0; i < 2; i++) {

		Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
		Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
		Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);

		Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
		Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
		Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);

		color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);

		float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
		float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
		float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);

		float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
		float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
		float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);

		alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
	}

	r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
	r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);

	//print_line("pos: " + p_posf + " level " + rtos(p_level) + " down to " + itos(target_level) + "." + rtos(level_filter) + " color " + r_color + " alpha " + rtos(r_alpha));
}

_FORCE_INLINE_ static Color _light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree *p_octree, const Vector3 &p_pos, const Vector3 &p_dir, float p_aperture, int p_cell_subdiv) {

	float bias = 0.0; //no need for bias here
	float max_distance = (Vector3(1, 1, 1) * (1 << (p_cell_subdiv - 1))).length();

	float dist = bias;
	float alpha = 0.0;
	Vector3 color;

	Vector3 scolor;
	float salpha;

	while (dist < max_distance && alpha < 0.95) {
		float diameter = MAX(1.0, 2.0 * p_aperture * dist);
		_light_capture_sample_octree(p_octree, p_cell_subdiv, p_pos + dist * p_dir, p_dir, log2(diameter), scolor, salpha);
		float a = (1.0 - alpha);
		color += scolor * a;
		alpha += a * salpha;
		dist += diameter * 0.5;
	}

	return Color(color.x, color.y, color.z, alpha);
}

void RenderingServerScene::_update_instance_lightmap_captures(Instance *p_instance) {

	InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);

	static const Vector3 cone_traces[12] = {
		Vector3(0, 0, 1),
		Vector3(0.866025, 0, 0.5),
		Vector3(0.267617, 0.823639, 0.5),
		Vector3(-0.700629, 0.509037, 0.5),
		Vector3(-0.700629, -0.509037, 0.5),
		Vector3(0.267617, -0.823639, 0.5),
		Vector3(0, 0, -1),
		Vector3(0.866025, 0, -0.5),
		Vector3(0.267617, 0.823639, -0.5),
		Vector3(-0.700629, 0.509037, -0.5),
		Vector3(-0.700629, -0.509037, -0.5),
		Vector3(0.267617, -0.823639, -0.5)
	};

	float cone_aperture = 0.577; // tan(angle) 60 degrees

	if (p_instance->lightmap_capture_data.empty()) {
		p_instance->lightmap_capture_data.resize(12);
	}

	//print_line("update captures for pos: " + p_instance->transform.origin);

	for (int i = 0; i < 12; i++)
		new (&p_instance->lightmap_capture_data.ptrw()[i]) Color;

	//this could use some sort of blending..
	for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
		const Vector<RasterizerStorage::LightmapCaptureOctree> *octree = RSG::storage->lightmap_capture_get_octree_ptr(E->get()->base);
		//print_line("octree size: " + itos(octree->size()));
		if (octree->size() == 0)
			continue;
		Transform to_cell_xform = RSG::storage->lightmap_capture_get_octree_cell_transform(E->get()->base);
		int cell_subdiv = RSG::storage->lightmap_capture_get_octree_cell_subdiv(E->get()->base);
		to_cell_xform = to_cell_xform * E->get()->transform.affine_inverse();

		const RasterizerStorage::LightmapCaptureOctree *octree_r = octree->ptr();

		Vector3 pos = to_cell_xform.xform(p_instance->transform.origin);

		for (int i = 0; i < 12; i++) {

			Vector3 dir = to_cell_xform.basis.xform(cone_traces[i]).normalized();
			Color capture = _light_capture_voxel_cone_trace(octree_r, pos, dir, cone_aperture, cell_subdiv);
			p_instance->lightmap_capture_data.write[i] += capture;
		}
	}
}

bool RenderingServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario) {

	InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);

	Transform light_transform = p_instance->transform;
	light_transform.orthonormalize(); //scale does not count on lights

	bool animated_material_found = false;

	switch (RSG::storage->light_get_type(p_instance->base)) {

		case RS::LIGHT_DIRECTIONAL: {

			real_t max_distance = p_cam_projection.get_z_far();
			real_t shadow_max = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
			if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
				max_distance = MIN(shadow_max, max_distance);
			}
			max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
			real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);

			RS::LightDirectionalShadowDepthRangeMode depth_range_mode = RSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);

			real_t pancake_size = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);

			if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
				//optimize min/max
				Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
				int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
				Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
				//check distance max and min

				bool found_items = false;
				real_t z_max = -1e20;
				real_t z_min = 1e20;

				for (int i = 0; i < cull_count; i++) {

					Instance *instance = instance_shadow_cull_result[i];
					if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
						continue;
					}

					if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
						animated_material_found = true;
					}

					real_t max, min;
					instance->transformed_aabb.project_range_in_plane(base, min, max);

					if (max > z_max) {
						z_max = max;
					}

					if (min < z_min) {
						z_min = min;
					}

					found_items = true;
				}

				if (found_items) {
					min_distance = MAX(min_distance, z_min);
					max_distance = MIN(max_distance, z_max);
				}
			}

			real_t range = max_distance - min_distance;

			int splits = 0;
			switch (RSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
				case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break;
				case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break;
				case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break;
			}

			real_t distances[5];

			distances[0] = min_distance;
			for (int i = 0; i < splits; i++) {
				distances[i + 1] = min_distance + RSG::storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
			};

			distances[splits] = max_distance;

			real_t texture_size = RSG::scene_render->get_directional_light_shadow_size(light->instance);

			bool overlap = RSG::storage->light_directional_get_blend_splits(p_instance->base);

			real_t first_radius = 0.0;

			real_t min_distance_bias_scale = pancake_size > 0 ? distances[1] / 10.0 : 0;

			for (int i = 0; i < splits; i++) {

				RENDER_TIMESTAMP("Culling Directional Light split" + itos(i));

				// setup a camera matrix for that range!
				CameraMatrix camera_matrix;

				real_t aspect = p_cam_projection.get_aspect();

				if (p_cam_orthogonal) {

					Vector2 vp_he = p_cam_projection.get_viewport_half_extents();

					camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
				} else {

					real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
					camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
				}

				//obtain the frustum endpoints

				Vector3 endpoints[8]; // frustum plane endpoints
				bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
				ERR_CONTINUE(!res);

				// obtain the light frustm ranges (given endpoints)

				Transform transform = light_transform; //discard scale and stabilize light

				Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
				Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
				Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
				//z_vec points agsint the camera, like in default opengl

				real_t x_min = 0.f, x_max = 0.f;
				real_t y_min = 0.f, y_max = 0.f;
				real_t z_min = 0.f, z_max = 0.f;

				// FIXME: z_max_cam is defined, computed, but not used below when setting up
				// ortho_camera. Commented out for now to fix warnings but should be investigated.
				real_t x_min_cam = 0.f, x_max_cam = 0.f;
				real_t y_min_cam = 0.f, y_max_cam = 0.f;
				real_t z_min_cam = 0.f;
				//real_t z_max_cam = 0.f;

				real_t bias_scale = 1.0;
				real_t aspect_bias_scale = 1.0;

				//used for culling

				for (int j = 0; j < 8; j++) {

					real_t d_x = x_vec.dot(endpoints[j]);
					real_t d_y = y_vec.dot(endpoints[j]);
					real_t d_z = z_vec.dot(endpoints[j]);

					if (j == 0 || d_x < x_min)
						x_min = d_x;
					if (j == 0 || d_x > x_max)
						x_max = d_x;

					if (j == 0 || d_y < y_min)
						y_min = d_y;
					if (j == 0 || d_y > y_max)
						y_max = d_y;

					if (j == 0 || d_z < z_min)
						z_min = d_z;
					if (j == 0 || d_z > z_max)
						z_max = d_z;
				}

				real_t radius = 0;
				real_t soft_shadow_expand = 0;
				Vector3 center;

				{
					//camera viewport stuff

					for (int j = 0; j < 8; j++) {

						center += endpoints[j];
					}
					center /= 8.0;

					//center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;

					for (int j = 0; j < 8; j++) {

						real_t d = center.distance_to(endpoints[j]);
						if (d > radius)
							radius = d;
					}

					radius *= texture_size / (texture_size - 2.0); //add a texel by each side

					if (i == 0) {
						first_radius = radius;
					} else {
						bias_scale = radius / first_radius;
					}

					z_min_cam = z_vec.dot(center) - radius;

					{

						float soft_shadow_angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);

						if (soft_shadow_angle > 0.0 && pancake_size > 0.0) {

							float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
							soft_shadow_expand = Math::tan(Math::deg2rad(soft_shadow_angle)) * z_range;

							x_max += soft_shadow_expand;
							y_max += soft_shadow_expand;

							x_min -= soft_shadow_expand;
							y_min -= soft_shadow_expand;
						}
					}

					x_max_cam = x_vec.dot(center) + radius + soft_shadow_expand;
					x_min_cam = x_vec.dot(center) - radius - soft_shadow_expand;
					y_max_cam = y_vec.dot(center) + radius + soft_shadow_expand;
					y_min_cam = y_vec.dot(center) - radius - soft_shadow_expand;

					if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
						//this trick here is what stabilizes the shadow (make potential jaggies to not move)
						//at the cost of some wasted resolution. Still the quality increase is very well worth it

						real_t unit = radius * 2.0 / texture_size;

						x_max_cam = Math::stepify(x_max_cam, unit);
						x_min_cam = Math::stepify(x_min_cam, unit);
						y_max_cam = Math::stepify(y_max_cam, unit);
						y_min_cam = Math::stepify(y_min_cam, unit);
					}
				}

				//now that we now all ranges, we can proceed to make the light frustum planes, for culling octree

				Vector<Plane> light_frustum_planes;
				light_frustum_planes.resize(6);

				//right/left
				light_frustum_planes.write[0] = Plane(x_vec, x_max);
				light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
				//top/bottom
				light_frustum_planes.write[2] = Plane(y_vec, y_max);
				light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
				//near/far
				light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
				light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed

				int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);

				// a pre pass will need to be needed to determine the actual z-near to be used

				Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));

				real_t cull_max = 0;
				for (int j = 0; j < cull_count; j++) {

					real_t min, max;
					Instance *instance = instance_shadow_cull_result[j];
					if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
						cull_count--;
						SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
						j--;
						continue;
					}

					instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
					instance->depth = near_plane.distance_to(instance->transform.origin);
					instance->depth_layer = 0;
					if (j == 0 || max > cull_max) {
						cull_max = max;
					}
				}

				if (cull_max > z_max) {
					z_max = cull_max;
				}

				if (pancake_size > 0) {
					z_max = z_vec.dot(center) + radius + pancake_size;
				}

				if (aspect != 1.0) {

					// if the aspect is different, then the radius will become larger.
					// if this happens, then bias needs to be adjusted too, as depth will increase
					// to do this, compare the depth of one that would have resulted from a square frustum

					CameraMatrix camera_matrix_square;
					if (p_cam_orthogonal) {

						Vector2 vp_he = camera_matrix.get_viewport_half_extents();
						if (p_cam_vaspect) {
							camera_matrix_square.set_orthogonal(vp_he.x * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
						} else {
							camera_matrix_square.set_orthogonal(vp_he.y * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
						}
					} else {
						Vector2 vp_he = camera_matrix.get_viewport_half_extents();
						if (p_cam_vaspect) {
							camera_matrix_square.set_frustum(vp_he.x * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
						} else {
							camera_matrix_square.set_frustum(vp_he.y * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
						}

						if (i == 0) {
							//print_line("prev he: " + vp_he + " new he: " + camera_matrix_square.get_viewport_half_extents());
						}
					}

					Vector3 endpoints_square[8]; // frustum plane endpoints
					res = camera_matrix_square.get_endpoints(p_cam_transform, endpoints_square);
					ERR_CONTINUE(!res);
					Vector3 center_square;
					real_t z_max_square = 0;

					for (int j = 0; j < 8; j++) {

						center_square += endpoints_square[j];

						real_t d_z = z_vec.dot(endpoints_square[j]);

						if (j == 0 || d_z > z_max_square)
							z_max_square = d_z;
					}

					if (cull_max > z_max_square) {
						z_max_square = cull_max;
					}

					center_square /= 8.0;

					real_t radius_square = 0;

					for (int j = 0; j < 8; j++) {

						real_t d = center_square.distance_to(endpoints_square[j]);
						if (d > radius_square)
							radius_square = d;
					}

					radius_square *= texture_size / (texture_size - 2.0); //add a texel by each side

					if (pancake_size > 0) {
						z_max_square = z_vec.dot(center_square) + radius_square + pancake_size;
					}

					real_t z_min_cam_square = z_vec.dot(center_square) - radius_square;

					aspect_bias_scale = (z_max - z_min_cam) / (z_max_square - z_min_cam_square);

					// this is not entirely perfect, because the cull-adjusted z-max may be different
					// but at least it's warranted that it results in a greater bias, so no acne should be present either way.
					// pancaking also helps with this.
				}

				{

					CameraMatrix ortho_camera;
					real_t half_x = (x_max_cam - x_min_cam) * 0.5;
					real_t half_y = (y_max_cam - y_min_cam) * 0.5;

					ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));

					Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));

					Transform ortho_transform;
					ortho_transform.basis = transform.basis;
					ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;

					{
						Vector3 max_in_view = p_cam_transform.affine_inverse().xform(z_vec * cull_max);
						Vector3 dir_in_view = p_cam_transform.xform_inv(z_vec).normalized();
						cull_max = dir_in_view.dot(max_in_view);
					}

					RSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, z_max - z_min_cam, distances[i + 1], i, radius * 2.0 / texture_size, bias_scale * aspect_bias_scale * min_distance_bias_scale, z_max, uv_scale);
				}

				RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
			}

		} break;
		case RS::LIGHT_OMNI: {

			RS::LightOmniShadowMode shadow_mode = RSG::storage->light_omni_get_shadow_mode(p_instance->base);

			if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !RSG::scene_render->light_instances_can_render_shadow_cube()) {

				for (int i = 0; i < 2; i++) {

					//using this one ensures that raster deferred will have it
					RENDER_TIMESTAMP("Culling Shadow Paraboloid" + itos(i));

					real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);

					real_t z = i == 0 ? -1 : 1;
					Vector<Plane> planes;
					planes.resize(5);
					planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
					planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
					planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
					planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
					planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));

					int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
					Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);

					for (int j = 0; j < cull_count; j++) {

						Instance *instance = instance_shadow_cull_result[j];
						if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
							cull_count--;
							SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
							j--;
						} else {
							if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
								animated_material_found = true;
							}

							instance->depth = near_plane.distance_to(instance->transform.origin);
							instance->depth_layer = 0;
						}
					}

					RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i, 0);
					RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
				}
			} else { //shadow cube

				real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
				CameraMatrix cm;
				cm.set_perspective(90, 1, 0.01, radius);

				for (int i = 0; i < 6; i++) {

					RENDER_TIMESTAMP("Culling Shadow Cube side" + itos(i));
					//using this one ensures that raster deferred will have it

					static const Vector3 view_normals[6] = {
						Vector3(+1, 0, 0),
						Vector3(-1, 0, 0),
						Vector3(0, -1, 0),
						Vector3(0, +1, 0),
						Vector3(0, 0, +1),
						Vector3(0, 0, -1)
					};
					static const Vector3 view_up[6] = {
						Vector3(0, -1, 0),
						Vector3(0, -1, 0),
						Vector3(0, 0, -1),
						Vector3(0, 0, +1),
						Vector3(0, -1, 0),
						Vector3(0, -1, 0)
					};

					Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);

					Vector<Plane> planes = cm.get_projection_planes(xform);

					int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);

					Plane near_plane(xform.origin, -xform.basis.get_axis(2));
					for (int j = 0; j < cull_count; j++) {

						Instance *instance = instance_shadow_cull_result[j];
						if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
							cull_count--;
							SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
							j--;
						} else {
							if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
								animated_material_found = true;
							}
							instance->depth = near_plane.distance_to(instance->transform.origin);
							instance->depth_layer = 0;
						}
					}

					RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
					RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
				}

				//restore the regular DP matrix
				RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0, 0);
			}

		} break;
		case RS::LIGHT_SPOT: {

			RENDER_TIMESTAMP("Culling Spot Light");

			real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
			real_t angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);

			CameraMatrix cm;
			cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);

			Vector<Plane> planes = cm.get_projection_planes(light_transform);
			int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);

			Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
			for (int j = 0; j < cull_count; j++) {

				Instance *instance = instance_shadow_cull_result[j];
				if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
					cull_count--;
					SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
					j--;
				} else {
					if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
						animated_material_found = true;
					}
					instance->depth = near_plane.distance_to(instance->transform.origin);
					instance->depth_layer = 0;
				}
			}

			RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
			RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);

		} break;
	}

	return animated_material_found;
}

void RenderingServerScene::render_camera(RID p_render_buffers, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
// render to mono camera
#ifndef _3D_DISABLED

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);

	/* STEP 1 - SETUP CAMERA */
	CameraMatrix camera_matrix;
	bool ortho = false;

	switch (camera->type) {
		case Camera::ORTHOGONAL: {

			camera_matrix.set_orthogonal(
					camera->size,
					p_viewport_size.width / (float)p_viewport_size.height,
					camera->znear,
					camera->zfar,
					camera->vaspect);
			ortho = true;
		} break;
		case Camera::PERSPECTIVE: {

			camera_matrix.set_perspective(
					camera->fov,
					p_viewport_size.width / (float)p_viewport_size.height,
					camera->znear,
					camera->zfar,
					camera->vaspect);
			ortho = false;

		} break;
		case Camera::FRUSTUM: {

			camera_matrix.set_frustum(
					camera->size,
					p_viewport_size.width / (float)p_viewport_size.height,
					camera->offset,
					camera->znear,
					camera->zfar,
					camera->vaspect);
			ortho = false;
		} break;
	}

	_prepare_scene(camera->transform, camera_matrix, ortho, camera->vaspect, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
	_render_scene(p_render_buffers, camera->transform, camera_matrix, ortho, camera->env, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
#endif
}

void RenderingServerScene::render_camera(RID p_render_buffers, Ref<XRInterface> &p_interface, XRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
	// render for AR/VR interface

	Camera *camera = camera_owner.getornull(p_camera);
	ERR_FAIL_COND(!camera);

	/* SETUP CAMERA, we are ignoring type and FOV here */
	float aspect = p_viewport_size.width / (float)p_viewport_size.height;
	CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);

	// We also ignore our camera position, it will have been positioned with a slightly old tracking position.
	// Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
	Transform world_origin = XRServer::get_singleton()->get_world_origin();
	Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);

	// For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
	if (p_eye == XRInterface::EYE_LEFT) {
		// Center our transform, we assume basis is equal.
		Transform mono_transform = cam_transform;
		Transform right_transform = p_interface->get_transform_for_eye(XRInterface::EYE_RIGHT, world_origin);
		mono_transform.origin += right_transform.origin;
		mono_transform.origin *= 0.5;

		// We need to combine our projection frustums for culling.
		// Ideally we should use our clipping planes for this and combine them,
		// however our shadow map logic uses our projection matrix.
		// Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.

		// - get some base values we need
		float eye_dist = (mono_transform.origin - cam_transform.origin).length();
		float z_near = camera_matrix.get_z_near(); // get our near plane
		float z_far = camera_matrix.get_z_far(); // get our far plane
		float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
		float x_shift = width * camera_matrix.matrix[2][0];
		float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
		float y_shift = height * camera_matrix.matrix[2][1];

		// printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);

		// - calculate our near plane size (horizontal only, right_near is mirrored)
		float left_near = -eye_dist - ((width - x_shift) * 0.5);

		// - calculate our far plane size (horizontal only, right_far is mirrored)
		float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
		float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
		if (left_far > left_far_right_eye) {
			// on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
			left_far = left_far_right_eye;
		}

		// - figure out required z-shift
		float slope = (left_far - left_near) / (z_far - z_near);
		float z_shift = (left_near / slope) - z_near;

		// - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
		float top_near = (height - y_shift) * 0.5;
		top_near += (top_near / z_near) * z_shift;
		float bottom_near = -(height + y_shift) * 0.5;
		bottom_near += (bottom_near / z_near) * z_shift;

		// printf("Left_near = %f, Left_far = %f, Top_near = %f, Bottom_near = %f, Z_shift = %f\n", left_near, left_far, top_near, bottom_near, z_shift);

		// - generate our frustum
		CameraMatrix combined_matrix;
		combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);

		// and finally move our camera back
		Transform apply_z_shift;
		apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
		mono_transform *= apply_z_shift;

		// now prepare our scene with our adjusted transform projection matrix
		_prepare_scene(mono_transform, combined_matrix, false, false, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
	} else if (p_eye == XRInterface::EYE_MONO) {
		// For mono render, prepare as per usual
		_prepare_scene(cam_transform, camera_matrix, false, false, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
	}

	// And render our scene...
	_render_scene(p_render_buffers, cam_transform, camera_matrix, false, camera->env, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
};

void RenderingServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_force_environment, RID p_force_camera_effects, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, bool p_using_shadows) {
	// Note, in stereo rendering:
	// - p_cam_transform will be a transform in the middle of our two eyes
	// - p_cam_projection is a wider frustrum that encompasses both eyes

	Scenario *scenario = scenario_owner.getornull(p_scenario);

	render_pass++;
	uint32_t camera_layer_mask = p_visible_layers;

	RSG::scene_render->set_scene_pass(render_pass);

	RENDER_TIMESTAMP("Frustum Culling");

	//rasterizer->set_camera(camera->transform, camera_matrix,ortho);

	Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);

	Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
	float z_far = p_cam_projection.get_z_far();

	/* STEP 2 - CULL */
	instance_cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
	light_cull_count = 0;

	reflection_probe_cull_count = 0;
	gi_probe_cull_count = 0;

	//light_samplers_culled=0;

	/*
	print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
	print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
	print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
	print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
	*/

	/* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
	//removed, will replace with culling

	/* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */

	for (int i = 0; i < instance_cull_count; i++) {

		Instance *ins = instance_cull_result[i];

		bool keep = false;

		if ((camera_layer_mask & ins->layer_mask) == 0) {
			//failure
		} else if (ins->base_type == RS::INSTANCE_LIGHT && ins->visible) {

			if (light_cull_count < MAX_LIGHTS_CULLED) {

				InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);

				if (!light->geometries.empty()) {
					//do not add this light if no geometry is affected by it..
					light_cull_result[light_cull_count] = ins;
					light_instance_cull_result[light_cull_count] = light->instance;
					if (p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(ins->base)) {
						RSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
					}

					light_cull_count++;
				}
			}
		} else if (ins->base_type == RS::INSTANCE_REFLECTION_PROBE && ins->visible) {

			if (reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {

				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);

				if (p_reflection_probe != reflection_probe->instance) {
					//avoid entering The Matrix

					if (!reflection_probe->geometries.empty()) {
						//do not add this light if no geometry is affected by it..

						if (reflection_probe->reflection_dirty || RSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
							if (!reflection_probe->update_list.in_list()) {
								reflection_probe->render_step = 0;
								reflection_probe_render_list.add_last(&reflection_probe->update_list);
							}

							reflection_probe->reflection_dirty = false;
						}

						if (RSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
							reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
							reflection_probe_cull_count++;
						}
					}
				}
			}

		} else if (ins->base_type == RS::INSTANCE_GI_PROBE && ins->visible) {

			InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
			if (!gi_probe->update_element.in_list()) {
				gi_probe_update_list.add(&gi_probe->update_element);
			}

			if (gi_probe_cull_count < MAX_GI_PROBES_CULLED) {
				gi_probe_instance_cull_result[gi_probe_cull_count] = gi_probe->probe_instance;
				gi_probe_cull_count++;
			}

		} else if (((1 << ins->base_type) & RS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {

			keep = true;

			InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);

			if (ins->redraw_if_visible) {
				RenderingServerRaster::redraw_request();
			}

			if (ins->base_type == RS::INSTANCE_PARTICLES) {
				//particles visible? process them
				if (RSG::storage->particles_is_inactive(ins->base)) {
					//but if nothing is going on, don't do it.
					keep = false;
				} else {
					RSG::storage->particles_request_process(ins->base);
					//particles visible? request redraw
					RenderingServerRaster::redraw_request();
				}
			}

			if (geom->lighting_dirty) {
				int l = 0;
				//only called when lights AABB enter/exit this geometry
				ins->light_instances.resize(geom->lighting.size());

				for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {

					InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);

					ins->light_instances.write[l++] = light->instance;
				}

				geom->lighting_dirty = false;
			}

			if (geom->reflection_dirty) {
				int l = 0;
				//only called when reflection probe AABB enter/exit this geometry
				ins->reflection_probe_instances.resize(geom->reflection_probes.size());

				for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {

					InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);

					ins->reflection_probe_instances.write[l++] = reflection_probe->instance;
				}

				geom->reflection_dirty = false;
			}

			if (geom->gi_probes_dirty) {
				int l = 0;
				//only called when reflection probe AABB enter/exit this geometry
				ins->gi_probe_instances.resize(geom->gi_probes.size());

				for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {

					InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);

					ins->gi_probe_instances.write[l++] = gi_probe->probe_instance;
				}

				geom->gi_probes_dirty = false;
			}

			ins->depth = near_plane.distance_to(ins->transform.origin);
			ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
		}

		if (!keep) {
			// remove, no reason to keep
			instance_cull_count--;
			SWAP(instance_cull_result[i], instance_cull_result[instance_cull_count]);
			i--;
			ins->last_render_pass = 0; // make invalid
		} else {

			ins->last_render_pass = render_pass;
		}
	}

	/* STEP 5 - PROCESS LIGHTS */

	RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
	directional_light_count = 0;

	// directional lights
	{

		Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
		int directional_shadow_count = 0;

		for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {

			if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
				break;
			}

			if (!E->get()->visible)
				continue;

			InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);

			//check shadow..

			if (light) {
				if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->get()->base)) {
					lights_with_shadow[directional_shadow_count++] = E->get();
				}
				//add to list
				directional_light_ptr[directional_light_count++] = light->instance;
			}
		}

		RSG::scene_render->set_directional_shadow_count(directional_shadow_count);

		for (int i = 0; i < directional_shadow_count; i++) {

			RENDER_TIMESTAMP(">Rendering Directional Light " + itos(i));

			_light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);

			RENDER_TIMESTAMP("<Rendering Directional Light " + itos(i));
		}
	}

	if (p_using_shadows) { //setup shadow maps

		//SortArray<Instance*,_InstanceLightsort> sorter;
		//sorter.sort(light_cull_result,light_cull_count);
		for (int i = 0; i < light_cull_count; i++) {

			Instance *ins = light_cull_result[i];

			if (!p_shadow_atlas.is_valid() || !RSG::storage->light_has_shadow(ins->base))
				continue;

			InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);

			float coverage = 0.f;

			{ //compute coverage

				Transform cam_xf = p_cam_transform;
				float zn = p_cam_projection.get_z_near();
				Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane

				// near plane half width and height
				Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();

				switch (RSG::storage->light_get_type(ins->base)) {

					case RS::LIGHT_OMNI: {

						float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);

						//get two points parallel to near plane
						Vector3 points[2] = {
							ins->transform.origin,
							ins->transform.origin + cam_xf.basis.get_axis(0) * radius
						};

						if (!p_cam_orthogonal) {
							//if using perspetive, map them to near plane
							for (int j = 0; j < 2; j++) {
								if (p.distance_to(points[j]) < 0) {
									points[j].z = -zn; //small hack to keep size constant when hitting the screen
								}

								p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
							}
						}

						float screen_diameter = points[0].distance_to(points[1]) * 2;
						coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
					} break;
					case RS::LIGHT_SPOT: {

						float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
						float angle = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);

						float w = radius * Math::sin(Math::deg2rad(angle));
						float d = radius * Math::cos(Math::deg2rad(angle));

						Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;

						Vector3 points[2] = {
							base,
							base + cam_xf.basis.get_axis(0) * w
						};

						if (!p_cam_orthogonal) {
							//if using perspetive, map them to near plane
							for (int j = 0; j < 2; j++) {
								if (p.distance_to(points[j]) < 0) {
									points[j].z = -zn; //small hack to keep size constant when hitting the screen
								}

								p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
							}
						}

						float screen_diameter = points[0].distance_to(points[1]) * 2;
						coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);

					} break;
					default: {
						ERR_PRINT("Invalid Light Type");
					}
				}
			}

			if (light->shadow_dirty) {
				light->last_version++;
				light->shadow_dirty = false;
			}

			bool redraw = RSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);

			if (redraw) {
				//must redraw!
				RENDER_TIMESTAMP(">Rendering Light " + itos(i));
				light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);
				RENDER_TIMESTAMP("<Rendering Light " + itos(i));
			}
		}
	}
}

void RenderingServerScene::_render_scene(RID p_render_buffers, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, RID p_force_camera_effects, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {

	Scenario *scenario = scenario_owner.getornull(p_scenario);

	/* ENVIRONMENT */

	RID environment;
	if (p_force_environment.is_valid()) //camera has more environment priority
		environment = p_force_environment;
	else if (scenario->environment.is_valid())
		environment = scenario->environment;
	else
		environment = scenario->fallback_environment;

	RID camera_effects;
	if (p_force_camera_effects.is_valid()) {
		camera_effects = p_force_camera_effects;
	} else {
		camera_effects = scenario->camera_effects;
	}
	/* PROCESS GEOMETRY AND DRAW SCENE */

	RENDER_TIMESTAMP("Render Scene ");
	RSG::scene_render->render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, instance_cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, gi_probe_instance_cull_result, gi_probe_cull_count, environment, camera_effects, p_shadow_atlas, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
}

void RenderingServerScene::render_empty_scene(RID p_render_buffers, RID p_scenario, RID p_shadow_atlas) {

#ifndef _3D_DISABLED

	Scenario *scenario = scenario_owner.getornull(p_scenario);

	RID environment;
	if (scenario->environment.is_valid())
		environment = scenario->environment;
	else
		environment = scenario->fallback_environment;
	RENDER_TIMESTAMP("Render Empty Scene ");
	RSG::scene_render->render_scene(p_render_buffers, Transform(), CameraMatrix(), true, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, environment, RID(), p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
#endif
}

bool RenderingServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {

	InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
	Scenario *scenario = p_instance->scenario;
	ERR_FAIL_COND_V(!scenario, true);

	RenderingServerRaster::redraw_request(); //update, so it updates in editor

	if (p_step == 0) {

		if (!RSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
			return true; //all full
		}
	}

	if (p_step >= 0 && p_step < 6) {

		static const Vector3 view_normals[6] = {
			Vector3(+1, 0, 0),
			Vector3(-1, 0, 0),
			Vector3(0, +1, 0),
			Vector3(0, -1, 0),
			Vector3(0, 0, +1),
			Vector3(0, 0, -1)
		};
		static const Vector3 view_up[6] = {
			Vector3(0, -1, 0),
			Vector3(0, -1, 0),
			Vector3(0, 0, +1),
			Vector3(0, 0, -1),
			Vector3(0, -1, 0),
			Vector3(0, -1, 0)
		};

		Vector3 extents = RSG::storage->reflection_probe_get_extents(p_instance->base);
		Vector3 origin_offset = RSG::storage->reflection_probe_get_origin_offset(p_instance->base);
		float max_distance = RSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);

		Vector3 edge = view_normals[p_step] * extents;
		float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit

		max_distance = MAX(max_distance, distance);

		//render cubemap side
		CameraMatrix cm;
		cm.set_perspective(90, 1, 0.01, max_distance);

		Transform local_view;
		local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);

		Transform xform = p_instance->transform * local_view;

		RID shadow_atlas;

		bool use_shadows = RSG::storage->reflection_probe_renders_shadows(p_instance->base);
		if (use_shadows) {

			shadow_atlas = scenario->reflection_probe_shadow_atlas;
		}

		RENDER_TIMESTAMP("Render Reflection Probe, Step " + itos(p_step));
		_prepare_scene(xform, cm, false, false, RID(), RID(), RSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, use_shadows);
		_render_scene(RID(), xform, cm, false, RID(), RID(), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);

	} else {
		//do roughness postprocess step until it believes it's done
		RENDER_TIMESTAMP("Post-Process Reflection Probe, Step " + itos(p_step));
		return RSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
	}

	return false;
}

void RenderingServerScene::render_probes() {

	/* REFLECTION PROBES */

	SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();

	bool busy = false;

	while (ref_probe) {

		SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
		RID base = ref_probe->self()->owner->base;

		switch (RSG::storage->reflection_probe_get_update_mode(base)) {

			case RS::REFLECTION_PROBE_UPDATE_ONCE: {
				if (busy) //already rendering something
					break;

				bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
				if (done) {
					reflection_probe_render_list.remove(ref_probe);
				} else {
					ref_probe->self()->render_step++;
				}

				busy = true; //do not render another one of this kind
			} break;
			case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {

				int step = 0;
				bool done = false;
				while (!done) {
					done = _render_reflection_probe_step(ref_probe->self()->owner, step);
					step++;
				}

				reflection_probe_render_list.remove(ref_probe);
			} break;
		}

		ref_probe = next;
	}

	/* GI PROBES */

	SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();

	if (gi_probe) {
		RENDER_TIMESTAMP("Render GI Probes");
	}

	while (gi_probe) {

		SelfList<InstanceGIProbeData> *next = gi_probe->next();

		InstanceGIProbeData *probe = gi_probe->self();
		//Instance *instance_probe = probe->owner;

		//check if probe must be setup, but don't do if on the lighting thread

		bool cache_dirty = false;
		int cache_count = 0;
		{

			int light_cache_size = probe->light_cache.size();
			const InstanceGIProbeData::LightCache *caches = probe->light_cache.ptr();
			const RID *instance_caches = probe->light_instances.ptr();

			int idx = 0; //must count visible lights
			for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
				Instance *instance = E->get();
				InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
				if (!instance->visible) {
					continue;
				}
				if (cache_dirty) {
					//do nothing, since idx must count all visible lights anyway
				} else if (idx >= light_cache_size) {
					cache_dirty = true;
				} else {

					const InstanceGIProbeData::LightCache *cache = &caches[idx];

					if (
							instance_caches[idx] != instance_light->instance ||
							cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
							cache->type != RSG::storage->light_get_type(instance->base) ||
							cache->transform != instance->transform ||
							cache->color != RSG::storage->light_get_color(instance->base) ||
							cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
							cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
							cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
							cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
							cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
							cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
						cache_dirty = true;
					}
				}

				idx++;
			}

			for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {

				Instance *instance = E->get();
				InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
				if (!instance->visible) {
					continue;
				}
				if (cache_dirty) {
					//do nothing, since idx must count all visible lights anyway
				} else if (idx >= light_cache_size) {
					cache_dirty = true;
				} else {

					const InstanceGIProbeData::LightCache *cache = &caches[idx];

					if (
							instance_caches[idx] != instance_light->instance ||
							cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
							cache->type != RSG::storage->light_get_type(instance->base) ||
							cache->transform != instance->transform ||
							cache->color != RSG::storage->light_get_color(instance->base) ||
							cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
							cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
							cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
							cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
							cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
							cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
						cache_dirty = true;
					}
				}

				idx++;
			}

			if (idx != light_cache_size) {
				cache_dirty = true;
			}

			cache_count = idx;
		}

		bool update_lights = RSG::scene_render->gi_probe_needs_update(probe->probe_instance);

		if (cache_dirty) {
			probe->light_cache.resize(cache_count);
			probe->light_instances.resize(cache_count);

			if (cache_count) {
				InstanceGIProbeData::LightCache *caches = probe->light_cache.ptrw();
				RID *instance_caches = probe->light_instances.ptrw();

				int idx = 0; //must count visible lights
				for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
					Instance *instance = E->get();
					InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
					if (!instance->visible) {
						continue;
					}

					InstanceGIProbeData::LightCache *cache = &caches[idx];

					instance_caches[idx] = instance_light->instance;
					cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
					cache->type = RSG::storage->light_get_type(instance->base);
					cache->transform = instance->transform;
					cache->color = RSG::storage->light_get_color(instance->base);
					cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
					cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
					cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
					cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
					cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
					cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);

					idx++;
				}
				for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
					Instance *instance = E->get();
					InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
					if (!instance->visible) {
						continue;
					}

					InstanceGIProbeData::LightCache *cache = &caches[idx];

					instance_caches[idx] = instance_light->instance;
					cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
					cache->type = RSG::storage->light_get_type(instance->base);
					cache->transform = instance->transform;
					cache->color = RSG::storage->light_get_color(instance->base);
					cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
					cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
					cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
					cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
					cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
					cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);

					idx++;
				}
			}

			update_lights = true;
		}

		instance_cull_count = 0;
		for (List<InstanceGIProbeData::PairInfo>::Element *E = probe->dynamic_geometries.front(); E; E = E->next()) {
			if (instance_cull_count < MAX_INSTANCE_CULL) {
				Instance *ins = E->get().geometry;
				if (!ins->visible) {
					continue;
				}
				InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;

				if (geom->gi_probes_dirty) {
					//giprobes may be dirty, so update
					int l = 0;
					//only called when reflection probe AABB enter/exit this geometry
					ins->gi_probe_instances.resize(geom->gi_probes.size());

					for (List<Instance *>::Element *F = geom->gi_probes.front(); F; F = F->next()) {

						InstanceGIProbeData *gi_probe2 = static_cast<InstanceGIProbeData *>(F->get()->base_data);

						ins->gi_probe_instances.write[l++] = gi_probe2->probe_instance;
					}

					geom->gi_probes_dirty = false;
				}

				instance_cull_result[instance_cull_count++] = E->get().geometry;
			}
		}

		RSG::scene_render->gi_probe_update(probe->probe_instance, update_lights, probe->light_instances, instance_cull_count, (RasterizerScene::InstanceBase **)instance_cull_result);

		gi_probe_update_list.remove(gi_probe);

		gi_probe = next;
	}
}

void RenderingServerScene::_update_dirty_instance(Instance *p_instance) {

	if (p_instance->update_aabb) {
		_update_instance_aabb(p_instance);
	}

	if (p_instance->update_dependencies) {

		p_instance->instance_increase_version();

		if (p_instance->base.is_valid()) {
			RSG::storage->base_update_dependency(p_instance->base, p_instance);
		}

		if (p_instance->material_override.is_valid()) {
			RSG::storage->material_update_dependency(p_instance->material_override, p_instance);
		}

		if (p_instance->base_type == RS::INSTANCE_MESH) {
			//remove materials no longer used and un-own them

			int new_mat_count = RSG::storage->mesh_get_surface_count(p_instance->base);
			p_instance->materials.resize(new_mat_count);

			int new_blend_shape_count = RSG::storage->mesh_get_blend_shape_count(p_instance->base);
			if (new_blend_shape_count != p_instance->blend_values.size()) {
				p_instance->blend_values.resize(new_blend_shape_count);
				for (int i = 0; i < new_blend_shape_count; i++) {
					p_instance->blend_values.write[i] = 0;
				}
			}
		}

		if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {

			InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);

			bool can_cast_shadows = true;
			bool is_animated = false;

			if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
				can_cast_shadows = false;
			} else if (p_instance->material_override.is_valid()) {
				can_cast_shadows = RSG::storage->material_casts_shadows(p_instance->material_override);
				is_animated = RSG::storage->material_is_animated(p_instance->material_override);
			} else {

				if (p_instance->base_type == RS::INSTANCE_MESH) {
					RID mesh = p_instance->base;

					if (mesh.is_valid()) {
						bool cast_shadows = false;

						for (int i = 0; i < p_instance->materials.size(); i++) {

							RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::storage->mesh_surface_get_material(mesh, i);

							if (!mat.is_valid()) {
								cast_shadows = true;
							} else {

								if (RSG::storage->material_casts_shadows(mat)) {
									cast_shadows = true;
								}

								if (RSG::storage->material_is_animated(mat)) {
									is_animated = true;
								}

								RSG::storage->material_update_dependency(mat, p_instance);
							}
						}

						if (!cast_shadows) {
							can_cast_shadows = false;
						}
					}

				} else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
					RID mesh = RSG::storage->multimesh_get_mesh(p_instance->base);
					if (mesh.is_valid()) {

						bool cast_shadows = false;

						int sc = RSG::storage->mesh_get_surface_count(mesh);
						for (int i = 0; i < sc; i++) {

							RID mat = RSG::storage->mesh_surface_get_material(mesh, i);

							if (!mat.is_valid()) {
								cast_shadows = true;

							} else {

								if (RSG::storage->material_casts_shadows(mat)) {
									cast_shadows = true;
								}
								if (RSG::storage->material_is_animated(mat)) {
									is_animated = true;
								}

								RSG::storage->material_update_dependency(mat, p_instance);
							}
						}

						if (!cast_shadows) {
							can_cast_shadows = false;
						}

						RSG::storage->base_update_dependency(mesh, p_instance);
					}
				} else if (p_instance->base_type == RS::INSTANCE_IMMEDIATE) {

					RID mat = RSG::storage->immediate_get_material(p_instance->base);

					can_cast_shadows = !mat.is_valid() || RSG::storage->material_casts_shadows(mat);

					if (mat.is_valid() && RSG::storage->material_is_animated(mat)) {
						is_animated = true;
					}

					if (mat.is_valid()) {
						RSG::storage->material_update_dependency(mat, p_instance);
					}

				} else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {

					bool cast_shadows = false;

					int dp = RSG::storage->particles_get_draw_passes(p_instance->base);

					for (int i = 0; i < dp; i++) {

						RID mesh = RSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
						if (!mesh.is_valid())
							continue;

						int sc = RSG::storage->mesh_get_surface_count(mesh);
						for (int j = 0; j < sc; j++) {

							RID mat = RSG::storage->mesh_surface_get_material(mesh, j);

							if (!mat.is_valid()) {
								cast_shadows = true;
							} else {

								if (RSG::storage->material_casts_shadows(mat)) {
									cast_shadows = true;
								}

								if (RSG::storage->material_is_animated(mat)) {
									is_animated = true;
								}

								RSG::storage->material_update_dependency(mat, p_instance);
							}
						}
					}

					if (!cast_shadows) {
						can_cast_shadows = false;
					}
				}
			}

			if (can_cast_shadows != geom->can_cast_shadows) {
				//ability to cast shadows change, let lights now
				for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
					InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
					light->shadow_dirty = true;
				}

				geom->can_cast_shadows = can_cast_shadows;
			}

			geom->material_is_animated = is_animated;
		}

		if (p_instance->skeleton.is_valid()) {
			RSG::storage->skeleton_update_dependency(p_instance->skeleton, p_instance);
		}

		p_instance->clean_up_dependencies();
	}

	_instance_update_list.remove(&p_instance->update_item);

	_update_instance(p_instance);

	p_instance->update_aabb = false;
	p_instance->update_dependencies = false;
}

void RenderingServerScene::update_dirty_instances() {

	RSG::storage->update_dirty_resources();

	while (_instance_update_list.first()) {

		_update_dirty_instance(_instance_update_list.first()->self());
	}
}

bool RenderingServerScene::free(RID p_rid) {

	if (camera_owner.owns(p_rid)) {

		Camera *camera = camera_owner.getornull(p_rid);

		camera_owner.free(p_rid);
		memdelete(camera);

	} else if (scenario_owner.owns(p_rid)) {

		Scenario *scenario = scenario_owner.getornull(p_rid);

		while (scenario->instances.first()) {
			instance_set_scenario(scenario->instances.first()->self()->self, RID());
		}
		RSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
		RSG::scene_render->free(scenario->reflection_atlas);
		scenario_owner.free(p_rid);
		memdelete(scenario);

	} else if (instance_owner.owns(p_rid)) {
		// delete the instance

		update_dirty_instances();

		Instance *instance = instance_owner.getornull(p_rid);

		instance_set_use_lightmap(p_rid, RID(), RID());
		instance_set_scenario(p_rid, RID());
		instance_set_base(p_rid, RID());
		instance_geometry_set_material_override(p_rid, RID());
		instance_attach_skeleton(p_rid, RID());

		update_dirty_instances(); //in case something changed this

		instance_owner.free(p_rid);
		memdelete(instance);
	} else {
		return false;
	}

	return true;
}

RenderingServerScene *RenderingServerScene::singleton = nullptr;

RenderingServerScene::RenderingServerScene() {

	render_pass = 1;
	singleton = this;
}

RenderingServerScene::~RenderingServerScene() {
}