File: starfield.cpp

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



#include "globalincs/pstypes.h"
#include <climits>
#include <string>

#include "freespace.h"
#include "cmdline/cmdline.h"
#include "debugconsole/console.h"
#include "graphics/matrix.h"
#include "graphics/paths/PathRenderer.h"
#include "hud/hud.h"
#include "hud/hudtarget.h"
#include "io/timer.h"
#include "lighting/lighting.h"
#include "math/vecmat.h"
#include "mission/missionparse.h"
#include "model/modelrender.h"
#include "nebula/neb.h"
#include "options/Option.h"
#include "osapi/dialogs.h"
#include "parse/parselo.h"
#include "render/3d.h"
#include "render/batching.h"
#include "starfield/nebula.h"
#include "starfield/starfield.h"
#include "starfield/supernova.h"
#include "tracing/tracing.h"
#include "utils/Random.h"

#define DEBRIS_ROT_MIN				10000
#define DEBRIS_ROT_RANGE			8
#define DEBRIS_ROT_RANGE_SCALER		10000
#define RND_MAX_MASK				0x3fff
#define HALF_RND_MAX				0x2000
#define MAX_MOTION_DEBRIS			300

typedef struct {
	vec3d pos;
	int vclip;
	float size;
} motion_debris_instance;

const float MAX_DIST_RANGE = 80.0f;
const float MIN_DIST_RANGE = 14.0f;
const float BASE_SIZE = 0.04f;
const float BASE_SIZE_NEB = 0.15f;

static int Subspace_model_inner = -1;
static int Subspace_model_outer = -1;
static int Rendering_to_env = 0;

int Num_stars = 500;

// A timestamp for animated skyboxes -MageKing17
TIMESTAMP Skybox_timestamp;

#define MAX_FLARE_COUNT 10
#define MAX_FLARE_BMP 6

typedef struct flare_info {
	float pos;
	float scale;
	int tex_num;
} flare_info;

typedef struct flare_bitmap {
	char filename[MAX_FILENAME_LEN];
	int bitmap_id;
} flare_bitmap;


// global info (not individual instances)
typedef struct starfield_bitmap {
	char filename[MAX_FILENAME_LEN];				// bitmap filename
	char glow_filename[MAX_FILENAME_LEN];			// only for suns
	int bitmap_id;									// bitmap handle
	int n_frames;
	int fps;
	int glow_bitmap;								// only for suns
	int glow_n_frames;
	int glow_fps;
	int xparent;
	float r, g, b, i;		// only for suns
	int glare;										// only for suns
	int flare;										// Is there a lens-flare for this sun?
	flare_info flare_infos[MAX_FLARE_COUNT];		// each flare can use a texture in flare_bmp, with different scale
	flare_bitmap flare_bitmaps[MAX_FLARE_BMP];		// bitmaps for different lens flares (can be re-used)
	int n_flares;									// number of flares actually used
	int n_flare_bitmaps;							// number of flare bitmaps available
	int used_this_level;
	int preload;
} starfield_bitmap;

// starfield bitmap instance
typedef struct starfield_bitmap_instance {
	float scale_x, scale_y;							// x and y scale
	int div_x, div_y;								// # of x and y divisions
	angles ang;										// angles from FRED
	int star_bitmap_index;							// index into starfield_bitmap array
	int n_verts;
	vertex *verts;

	starfield_bitmap_instance() : scale_x(1.0f), scale_y(1.0f), div_x(1), div_y(1), star_bitmap_index(0), n_verts(0), verts(NULL) {
		ang.p = 0.0f;
		ang.b = 0.0f;
		ang.h = 0.0f;
    }
} starfield_bitmap_instance;

// for drawing cool stuff on the background - comes from a table
static SCP_vector<starfield_bitmap> Starfield_bitmaps;
static SCP_vector<starfield_bitmap_instance> Starfield_bitmap_instances;

// sun bitmaps and sun glow bitmaps
static SCP_vector<starfield_bitmap> Sun_bitmaps;
static SCP_vector<starfield_bitmap_instance> Suns;

// Goober5000
int Cur_background = -1;
SCP_vector<background_t> Backgrounds;

SCP_vector<int> Preload_background_indexes;
void stars_preload_background(int background_idx);

int last_stars_filled = 0;
color star_colors[8];
color star_aacolors[8];

typedef struct vDist {
	int x;
	int y;
} vDist;

std::unique_ptr<star[]> Stars = make_unique<star[]>(MAX_STARS);

motion_debris_instance Motion_debris[MAX_MOTION_DEBRIS];

SCP_vector<motion_debris_types> Motion_debris_info;
motion_debris_bitmaps* Motion_debris_ptr = nullptr;

// background data
int Stars_background_inited = 0;			// if we're inited
int Nmodel_num = -1;							// model num
int Nmodel_instance_num = -1;					// model instance num
matrix Nmodel_orient = IDENTITY_MATRIX;			// model orientation
int Nmodel_flags = DEFAULT_NMODEL_FLAGS;		// model flags
int Nmodel_bitmap = -1;						// model texture

bool Dynamic_environment = false;

bool Motion_debris_override = false;
bool Motion_debris_enabled = true;

auto MotionDebrisOption = options::OptionBuilder<bool>("Graphics.MotionDebris",
                     std::pair<const char*, int>{"Motion Debris", 1713},
                     std::pair<const char*, int>{"Enable or disable visible motion debris", 1714})
                     .category("Graphics")
                     .bind_to_once(&Motion_debris_enabled)
                     .default_val(true)
                     .level(options::ExpertLevel::Advanced)
                     .importance(67)
                     .finish();

static int Default_env_map = -1;
static int Mission_env_map = -1;
static bool Env_cubemap_drawn = false;
static bool Irr_cubemap_drawn = false;

int get_motion_debris_by_name(const SCP_string &name) {
	for (int i = 0; i < (int)Motion_debris_info.size(); i++) {
		if (lcase_equal(Motion_debris_info[i].name, name)) {
			return i;
		}
	}

	return -1;
}

void stars_release_motion_debris(motion_debris_bitmaps* vclips)
{

	if (vclips == nullptr)
		return;

	for (int i = 0; i < MAX_MOTION_DEBRIS_BITMAPS; i++) {
		if ( (vclips[i].bm >= 0) && bm_release(vclips[i].bm) ) {
			vclips[i].bm = -1;
			vclips[i].nframes = -1;
		}
	}
}

void stars_load_motion_debris(motion_debris_bitmaps* vclips)
{

	Assertion(vclips != nullptr, "Motion debris not loaded!");

	for (int i = 0; i < MAX_MOTION_DEBRIS_BITMAPS; i++) {
		vclips[i].bm = bm_load_animation( vclips[i].name, &vclips[i].nframes, nullptr, nullptr, nullptr, true );

		if ( vclips[i].bm < 0 ) {
			// try loading it as a single bitmap
			vclips[i].bm = bm_load(Motion_debris_ptr[i].name);
			vclips[i].nframes = 1;

			if (vclips[i].bm <= 0) {
				Error( LOCATION, "Couldn't load animation/bitmap '%s'\n", vclips[i].name );
			}
		}
	}
}

void stars_load_debris(int fullneb, const SCP_string &custom_name)
{
	if (!Motion_debris_enabled || ((int)Motion_debris_info.size() == 0)) {
		return;
	}

	SCP_string debris_name = "";
	
	if (!custom_name.empty()) {
		debris_name = custom_name;
	}

	// if not using custom the load the default type for the mission
	if (fullneb && debris_name.empty()) { // if we're in nebula mode
		debris_name = "nebula";
	} else if (debris_name.empty()) {
		debris_name = "default";
	}

	int debris_index = get_motion_debris_by_name(debris_name);

	//If we can't find the motion debris that's been called for then warn and
	//set debris override to prevent downstream errors. Then abort.
	if (debris_index < 0) {
		Warning(LOCATION, "Motion debris '%s' not found in stars.tbl!\n", debris_name.c_str());
		Motion_debris_override = true;
		Motion_debris_ptr = nullptr;
		return;
	}

	stars_release_motion_debris(Motion_debris_ptr);
	stars_load_motion_debris(Motion_debris_info[debris_index].bitmaps);
	Motion_debris_ptr = Motion_debris_info[debris_index].bitmaps;
}

const int MAX_PERSPECTIVE_DIVISIONS = 5;
const float p_phi = 10.0f, p_theta = 10.0f;

extern void stars_project_2d_onto_sphere( vec3d *pnt, float rho, float phi, float theta );

static void starfield_create_bitmap_buffer(const int si_idx)
{
	vec3d s_points[MAX_PERSPECTIVE_DIVISIONS+1][MAX_PERSPECTIVE_DIVISIONS+1];

	vertex v[4];
	matrix m;
	int idx, s_idx;
	float ui, vi;

	starfield_bitmap_instance *sbi = &Starfield_bitmap_instances[si_idx];

	angles *a = &sbi->ang;
	float scale_x = sbi->scale_x;
	float scale_y = sbi->scale_y;
	int div_x = sbi->div_x;
	int div_y = sbi->div_y;

	// cap division values
//	div_x = div_x > MAX_PERSPECTIVE_DIVISIONS ? MAX_PERSPECTIVE_DIVISIONS : div_x;
	div_x = 1;
	div_y = div_y > MAX_PERSPECTIVE_DIVISIONS ? MAX_PERSPECTIVE_DIVISIONS : div_y;

	if (sbi->verts != NULL) {
		delete [] sbi->verts;
	}

	sbi->verts = new(std::nothrow) vertex[div_x * div_y * 6];

	if (sbi->verts == NULL) {
		sbi->star_bitmap_index = -1;
		return;
	}

	sbi->n_verts = div_x * div_y * 6;

	// texture increment values
	ui = 1.0f / (float)div_x;
	vi = 1.0f / (float)div_y;	

	// adjust for aspect ratio
	//scale_x *= (gr_screen.clip_aspect + 0.55f); // fudge factor
	//scale_x *= (gr_screen.clip_aspect + (0.7333333f/gr_screen.clip_aspect)); // fudge factor
	scale_x *= 1.883333f; //fudge factor

	float s_phi = 0.5f + (((p_phi * scale_x) / 360.0f) / 2.0f);
	float s_theta = (((p_theta * scale_y) / 360.0f) / 2.0f);
	float d_phi = -(((p_phi * scale_x) / 360.0f) / (float)(div_x));
	float d_theta = -(((p_theta * scale_y) / 360.0f) / (float)(div_y));

	// bank matrix
	vm_angles_2_matrix(&m, a);

	// generate the bitmap points
	for(idx=0; idx<=div_x; idx++) {
		for(s_idx=0; s_idx<=div_y; s_idx++) {
			// get world spherical coords
			stars_project_2d_onto_sphere(&s_points[idx][s_idx], 1000.0f, s_phi + ((float)idx*d_phi), s_theta + ((float)s_idx*d_theta));

			// (un)rotate on the sphere
			vm_vec_unrotate(&s_points[idx][s_idx], &s_points[idx][s_idx], &m);
		}
	}

	memset(v, 0, sizeof(vertex) * 4);

	int j = 0;

	vertex *verts = sbi->verts;

	for (idx = 0; idx < div_x; idx++) {
		for (s_idx = 0; s_idx < div_y; s_idx++) {
			// stuff texture coords
			v[0].texture_position.u = ui * float(idx);
			v[0].texture_position.v = vi * float(s_idx);

			v[1].texture_position.u = ui * float(idx+1);
			v[1].texture_position.v = vi * float(s_idx);

			v[2].texture_position.u = ui * float(idx+1);
			v[2].texture_position.v = vi * float(s_idx+1);

			v[3].texture_position.u = ui * float(idx);
			v[3].texture_position.v = vi * float(s_idx+1);

			g3_transfer_vertex(&v[0], &s_points[idx][s_idx]);
			g3_transfer_vertex(&v[1], &s_points[idx+1][s_idx]);
			g3_transfer_vertex(&v[2], &s_points[idx+1][s_idx+1]);
			g3_transfer_vertex(&v[3], &s_points[idx][s_idx+1]);

			// poly 1
			verts[j++] = v[0];
			verts[j++] = v[1];
			verts[j++] = v[2];
			// poly 2
			verts[j++] = v[0];
			verts[j++] = v[2];
			verts[j++] = v[3];
		}
	}

	Assert( j == sbi->n_verts );
}

// take the Starfield_bitmap_instances[] and make all the vertex buffers that you'll need to draw it 
static void starfield_generate_bitmap_buffers()
{
	int idx;

	int sb_instances = (int)Starfield_bitmap_instances.size();

	for (idx = 0; idx < sb_instances; idx++) {
		if (Starfield_bitmap_instances[idx].star_bitmap_index < 0) {
			continue;
		}

		starfield_create_bitmap_buffer(idx);
	}
}

static void starfield_bitmap_entry_init(starfield_bitmap *sbm)
{
	int i;

	Assert( sbm != NULL );

	memset( sbm, 0, sizeof(starfield_bitmap) );

	sbm->bitmap_id = -1;
	sbm->glow_bitmap = -1;
	sbm->glow_n_frames = 1;

	for (i = 0; i < MAX_FLARE_BMP; i++) {
		sbm->flare_bitmaps[i].bitmap_id = -1;
	}

	for (i = 0; i < MAX_FLARE_COUNT; i++) {
		sbm->flare_infos[i].tex_num = -1;
	}
}

#define CHECK_END() {	\
	if (in_check) {	\
		required_string("#end");	\
		in_check = false;	\
		run_count = 0;	\
	}	\
}

void parse_startbl(const char *filename)
{
	char name[MAX_FILENAME_LEN], tempf[16];
	starfield_bitmap sbm;
	int idx;
	bool in_check = false;
	int rc = -1;
	int run_count = 0;

	try
	{
		read_file_text(filename, CF_TYPE_TABLES);
		reset_parse();

		// freaky! ;)
		while (!check_for_eof()) {
			
			optional_string("#Background Bitmaps");

			while ((rc = optional_string_either("$Bitmap:", "$BitmapX:")) != -1) {
				in_check = true;

				starfield_bitmap_entry_init(&sbm);

				stuff_string(sbm.filename, F_NAME, MAX_FILENAME_LEN);
				sbm.xparent = rc;  // 0 == intensity alpha bitmap,  1 == green xparency bitmap

				if ((idx = stars_find_bitmap(sbm.filename)) >= 0) {
					if (sbm.xparent == Starfield_bitmaps[idx].xparent) {
						if (!Parsing_modular_table)
							Warning(LOCATION, "Starfield bitmap '%s' listed more than once!!  Only using the first entry!", sbm.filename);
					}
					else {
						Warning(LOCATION, "Starfield bitmap '%s' already listed as a %s bitmap!!  Only using the xparent version!",
							sbm.filename, (rc) ? "xparent" : "non-xparent");
					}
				}
				else {
					Starfield_bitmaps.push_back(sbm);
				}
			}

			CHECK_END();

			optional_string("#Stars");

			while (optional_string("$Sun:")) {
				in_check = true;

				starfield_bitmap_entry_init(&sbm);

				stuff_string(sbm.filename, F_NAME, MAX_FILENAME_LEN);

				// associated glow
				required_string("$Sunglow:");
				stuff_string(sbm.glow_filename, F_NAME, MAX_FILENAME_LEN);

				// associated lighting values
				required_string("$SunRGBI:");
				stuff_float(&sbm.r);
				stuff_float(&sbm.g);
				stuff_float(&sbm.b);
				stuff_float(&sbm.i);

				if (optional_string("$SunSpecularRGB:")) {
					SCP_string warning;
					sprintf(warning, "Sun %s tried to set SunSpecularRGB. This feature has been deprecated and will be ignored.", sbm.filename);

					float spec_r, spec_g, spec_b;
					stuff_float(&spec_r);
					stuff_float(&spec_g);
					stuff_float(&spec_b);

					if (fl_equal(sbm.r, spec_r) && fl_equal(sbm.g, spec_g) && fl_equal(sbm.b, spec_b))
						mprintf(("%s\n", warning.c_str()));				// default case is not significant
					else
						Warning(LOCATION, "%s", warning.c_str());		// customized case is significant
				}

				// lens flare stuff
				if (optional_string("$Flare:")) {
					sbm.flare = 1;

					required_string("+FlareCount:");
					stuff_int(&sbm.n_flares);

					// if there's a flare, it has to have at least one texture
					required_string("$FlareTexture1:");
					stuff_string(sbm.flare_bitmaps[0].filename, F_NAME, MAX_FILENAME_LEN);

					sbm.n_flare_bitmaps = 1;

					for (idx = 1; idx < MAX_FLARE_BMP; idx++) {
						// allow 9999 textures (theoretically speaking, that is)
						sprintf(tempf, "$FlareTexture%d:", idx + 1);

						if (optional_string(tempf)) {
							sbm.n_flare_bitmaps++;
							stuff_string(sbm.flare_bitmaps[idx].filename, F_NAME, MAX_FILENAME_LEN);
						}
						//	else break; //don't allow flaretexture1 and then 3, etc.
					}

					required_string("$FlareGlow1:");

					required_string("+FlareTexture:");
					stuff_int(&sbm.flare_infos[0].tex_num);

					required_string("+FlarePos:");
					stuff_float(&sbm.flare_infos[0].pos);

					required_string("+FlareScale:");
					stuff_float(&sbm.flare_infos[0].scale);

					sbm.n_flares = 1;

					for (idx = 1; idx < MAX_FLARE_COUNT; idx++) {
						// allow a lot of glows
						sprintf(tempf, "$FlareGlow%d:", idx + 1);

						if (optional_string(tempf)) {
							sbm.n_flares++;

							required_string("+FlareTexture:");
							stuff_int(&sbm.flare_infos[idx].tex_num);

							required_string("+FlarePos:");
							stuff_float(&sbm.flare_infos[idx].pos);

							required_string("+FlareScale:");
							stuff_float(&sbm.flare_infos[idx].scale);
						}
						//	else break; //don't allow "flare 1" and then "flare 3"
					}
				}

				sbm.glare = !optional_string("$NoGlare:");

				sbm.xparent = 1;

				if ((idx = stars_find_sun(sbm.filename)) >= 0) {
					if (Parsing_modular_table)
						Sun_bitmaps[idx] = sbm;
					else
						Warning(LOCATION, "Sun bitmap '%s' listed more than once!!  Only using the first entry!", sbm.filename);
				}
				else {
					Sun_bitmaps.push_back(sbm);
				}
			}

			CHECK_END();

			optional_string("#Motion Debris");

			// normal debris pieces
			// leaving this for retail - Mjn
			if (check_for_string("$Debris:")) {

				mprintf(("Using deprecated motion debris parsing for Default motion debris!\n"));
				motion_debris_types this_debris;
				this_debris.name = "Default";

				int count = 0;

				while (optional_string("$Debris:")) {
				in_check = true;

					stuff_string(name, F_NAME, MAX_FILENAME_LEN);

					if (count < MAX_MOTION_DEBRIS_BITMAPS) {
						strcpy_s(this_debris.bitmaps[count++].name, name);
					} else {
						Warning(LOCATION, "Could not load normal motion debris '%s'; maximum of %d exceeded.", name, MAX_MOTION_DEBRIS_BITMAPS);
					}
				}
				if (count == MAX_MOTION_DEBRIS_BITMAPS) {
					Motion_debris_info.push_back(this_debris);
				} else {
					error_display(0, "Not enough bitmaps defined for motion debris '%s'. Skipping!\n", this_debris.name.c_str());
				}
			}

			CHECK_END();

			// nebula debris pieces
			// leaving this for retail - Mjn
			if (check_for_string("$DebrisNeb:")) {

				mprintf(("Using deprecated motion debris parsing for Nebula motion debris!\n"));
				motion_debris_types this_debris;
				this_debris.name = "Nebula";

				int count = 0;

				while (optional_string("$DebrisNeb:")) {
				in_check = true;

					stuff_string(name, F_NAME, MAX_FILENAME_LEN);

					if (count < MAX_MOTION_DEBRIS_BITMAPS) {
						strcpy_s(this_debris.bitmaps[count++].name, name);
					} else {
						Warning(LOCATION, "Could not load nebula motion debris '%s'; maximum of %d exceeded.", name, MAX_MOTION_DEBRIS_BITMAPS);
					}
				}
				if (count == MAX_MOTION_DEBRIS_BITMAPS) {
					Motion_debris_info.push_back(this_debris);
				} else {
					error_display(0, "Not enough bitmaps defined for motion debris '%s'. Skipping!\n", this_debris.name.c_str());
				}
			}

			CHECK_END();

			// custom debris pieces
			while (optional_string("$Motion Debris Name:")) {
				in_check = true;

				stuff_string(name, F_NAME, MAX_NAME_LEN);

				motion_debris_types this_debris;
				this_debris.name = name;

				// check if we will replace an existing entry
				int check = get_motion_debris_by_name(name);

				motion_debris_types* debris_ptr;

				//If we're going to create a new motion debris then set it up
				if (check == -1) {

					// initialize all the names as empty strings for later checking
					for (int i = 0; i < MAX_MOTION_DEBRIS_BITMAPS; i++) {
						this_debris.bitmaps[i].name[0] = '\0';
					}

					Motion_debris_info.push_back(this_debris);
					check = (int)Motion_debris_info.size() - 1;
				}

				debris_ptr = &Motion_debris_info[check];

				int count = 0;

				while (count < MAX_MOTION_DEBRIS_BITMAPS){
					
					required_string("+Bitmap:");
					stuff_string(name, F_NAME, MAX_FILENAME_LEN);

					strcpy_s(debris_ptr->bitmaps[count++].name, name);

				}

				for (int i = 0; i < MAX_MOTION_DEBRIS_BITMAPS; i++) {
					if(debris_ptr->bitmaps[i].name[0] == '\0'){
						error_display(0, "Not enough bitmaps defined for motion debris '%s'. Removing!\n", this_debris.name.c_str());
						Motion_debris_info.erase(Motion_debris_info.begin() + check);
						break;
					}
				}

			}

			CHECK_END();

			// since it's possible for some idiot to have a tbl screwed up enough
			// that this ends up in an endless loop, give an opportunity to advance
			// through the file no matter what, because even the retail tbl has an
			// extra "#end" line in it.
			if (optional_string("#end") || (run_count++ > 5)) {
				run_count = 0;
				advance_to_eoln(NULL);
			}
		}
	}
	catch (const parse::ParseException& e)
	{
		mprintf(("TABLES: Unable to parse '%s'!  Error message = %s.\n", filename, e.what()));
		return;
	}
}

void stars_load_all_bitmaps()
{
	int idx, i;
	starfield_bitmap *sb = NULL;
	static int Star_bitmaps_loaded = 0;

	if (Star_bitmaps_loaded)
		return;

	// pre-load all starfield bitmaps.  ONLY SHOULD DO THIS FOR FRED!!
	// this can get nasty when a lot of bitmaps are in use so spare it for
	// the normal game and only do this in FRED
	int mprintf_count = 0;
	for (idx = 0; idx < (int)Starfield_bitmaps.size(); idx++) {
		sb = &Starfield_bitmaps[idx];

		if (sb->bitmap_id < 0) {
			sb->bitmap_id = bm_load(sb->filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

				if (sb->bitmap_id < 0) {
					mprintf(("Unable to load starfield bitmap: '%s'!\n", sb->filename));
					mprintf_count++;
				}
			}
		}
	}
	if (mprintf_count > 0) {
		Warning(LOCATION, "Unable to load %d starfield bitmap(s)!\n", mprintf_count);
	}

	for (idx = 0; idx < (int)Sun_bitmaps.size(); idx++) {
		sb = &Sun_bitmaps[idx];

		// normal bitmap
		if (sb->bitmap_id < 0) {
			sb->bitmap_id = bm_load(sb->filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

				if (sb->bitmap_id < 0) {
					Warning(LOCATION, "Unable to load sun bitmap: '%s'!\n", sb->filename);
				}
			}
		}

		// glow bitmap
		if (sb->glow_bitmap < 0) {
			sb->glow_bitmap = bm_load(sb->glow_filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->glow_bitmap < 0) {
				sb->glow_bitmap = bm_load_animation(sb->glow_filename, &sb->glow_n_frames, &sb->glow_fps, nullptr, nullptr, true);

				if (sb->glow_bitmap < 0) {
					Warning(LOCATION, "Unable to load sun glow bitmap: '%s'!\n", sb->glow_filename);
				}
			}
		}

		if (sb->flare) {
			for (i = 0; i < MAX_FLARE_BMP; i++) {
				if ( !strlen(sb->flare_bitmaps[i].filename) )
					continue;

				if (sb->flare_bitmaps[i].bitmap_id < 0) {
					sb->flare_bitmaps[i].bitmap_id = bm_load(sb->flare_bitmaps[i].filename);

					if (sb->flare_bitmaps[i].bitmap_id < 0) {
						Warning(LOCATION, "Unable to load sun flare bitmap: '%s'!\n", sb->flare_bitmaps[i].filename);
						continue;
					}
				}
			}
		}
	}

	Star_bitmaps_loaded = 1;
}

void stars_clear_instances()
{
	for (uint i = 0; i < Starfield_bitmap_instances.size(); i++) {
		delete [] Starfield_bitmap_instances[i].verts;
		Starfield_bitmap_instances[i].verts = NULL;
	}

	Starfield_bitmap_instances.clear();
	Suns.clear();
}

// call on game startup
void stars_init()
{

	// parse stars.tbl
	parse_startbl("stars.tbl");

	parse_modular_table("*-str.tbm", parse_startbl);

	// Warn if we can't find the two retail motion debris types.
	if (get_motion_debris_by_name("Default") < 0)
		Warning(LOCATION, "Motion debris 'Default' not found in stars.tbl. Motion debris will be disabled!\n");

	if (get_motion_debris_by_name("Nebula") < 0)
		Warning(LOCATION, "Motion debris 'Nebula' not found in stars.tbl. Motion debris will be disabled!\n");

	if (Cmdline_env) {
		ENVMAP = Default_env_map = bm_load("cubemap");
	}
}

// call only from game_shutdown()!!
void stars_close()
{
	stars_clear_instances();

	// any other code goes here
}

// called before mission parse so we can clear out all of the old stuff
void stars_pre_level_init(bool clear_backgrounds)
{
	uint idx, i;
	starfield_bitmap *sb = NULL;

	Num_stars = 500;

	// we used to clear all the array entries, but now we can just wipe the vector
	if (clear_backgrounds)
		Backgrounds.clear();

	stars_clear_instances();

	stars_set_background_model(NULL, NULL);
	stars_set_background_orientation();

	// mark all starfield and sun bitmaps as unused for this mission and release any current bitmaps
	// NOTE: that because of how we have to load the bitmaps it's important to release all of
	//       them first thing rather than after we have marked and loaded only what's needed
	// NOTE2: there is a reason that we don't check for release before setting the handle to -1 so
	//        be aware that this is NOT a bug. also, bmpman should NEVER return 0 as a valid handle!
	if ( !Fred_running ) {
		for (idx = 0; idx < Starfield_bitmaps.size(); idx++) {
			sb = &Starfield_bitmaps[idx];

			if (sb->bitmap_id > 0) {
				bm_release(sb->bitmap_id);
				sb->bitmap_id = -1;
			}

			sb->used_this_level = 0;
			sb->preload = 0;
		}

		for (idx = 0; idx < Sun_bitmaps.size(); idx++) {
			sb = &Sun_bitmaps[idx];

			if (sb->bitmap_id > 0) {
				bm_release(sb->bitmap_id);
				sb->bitmap_id = -1;
			}

			if (sb->glow_bitmap > 0) {
				bm_release(sb->glow_bitmap);
				sb->glow_bitmap = -1;
			}

			for (i = 0; i < MAX_FLARE_BMP; i++) {
				if (sb->flare_bitmaps[i].bitmap_id > 0) {
					bm_release(sb->flare_bitmaps[i].bitmap_id);
					sb->flare_bitmaps[i].bitmap_id = -1;
				}
			}

			sb->used_this_level = 0;
			sb->preload = 0;
		}
	}

	// also clear the preload indexes
	Preload_background_indexes.clear();

	Dynamic_environment = false;
	Motion_debris_override = false;

	Env_cubemap_drawn = false;
	Irr_cubemap_drawn = false;

	// reset the skybox timestamp, used for animated textures
	Skybox_timestamp = _timestamp();
}

// setup the render target ready for this mission's environment map
static void environment_map_gen()
{
	const int size = 512;
	int gen_flags = (BMP_FLAG_RENDER_TARGET_STATIC | BMP_FLAG_CUBEMAP | BMP_FLAG_RENDER_TARGET_MIPMAP);

	if ( !Cmdline_env ) {
		return;
	}

	if (gr_screen.envmap_render_target >= 0) {
		if ( !bm_release(gr_screen.envmap_render_target, 1) ) {
			Warning(LOCATION, "Unable to release environment map render target.");
		}

		gr_screen.envmap_render_target = -1;
	}

	if ( Dynamic_environment || (The_mission.flags[Mission::Mission_Flags::Subspace]) ) {
		Dynamic_environment = true;
		gen_flags &= ~BMP_FLAG_RENDER_TARGET_STATIC;
		gen_flags |= BMP_FLAG_RENDER_TARGET_DYNAMIC;
	}
		// bail if we are going to be static, and have an envmap specified already
	else if ( strlen(The_mission.envmap_name) ) {
		// Load the mission map so we can use it later
		Mission_env_map = bm_load(The_mission.envmap_name);
		return;
	}

	gr_screen.envmap_render_target = bm_make_render_target(size, size, gen_flags);
}

// setup the render target ready for this mission's environment map
static void irradiance_map_gen()
{
	const int irr_size = 16;
	int gen_flags = (BMP_FLAG_RENDER_TARGET_STATIC | BMP_FLAG_CUBEMAP | BMP_FLAG_RENDER_TARGET_MIPMAP);

	if (!Cmdline_env) {
		return;
	}

	if (gr_screen.irrmap_render_target >= 0) {
		if (!bm_release(gr_screen.irrmap_render_target, 1)) {
			Warning(LOCATION, "Unable to release environment map render target.");
		}

		gr_screen.irrmap_render_target = -1;
		IRRMAP = -1;
	}

	if (Dynamic_environment || (The_mission.flags[Mission::Mission_Flags::Subspace])) {
		Dynamic_environment = true;
		gen_flags &= ~BMP_FLAG_RENDER_TARGET_STATIC;
		gen_flags |= BMP_FLAG_RENDER_TARGET_DYNAMIC;
	}

	gr_screen.irrmap_render_target = bm_make_render_target(irr_size, irr_size, gen_flags);
	IRRMAP = gr_screen.irrmap_render_target;
}

// call this in game_post_level_init() so we know whether we're running in full nebula mode or not
void stars_post_level_init()
{
	int i;
	vec3d v;
	float dist, dist_max;
	ubyte red,green,blue,alpha;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	// in FRED, make sure we always have at least one background
	if (Fred_running)
	{
		if (Backgrounds.empty())
			stars_add_blank_background(true);
	}
	// in FSO, see if we have any backgrounds to preload
	// (since the backgrounds aren't parsed at the time we parse the sexps)
	else
	{
		for (int idx : Preload_background_indexes)
			stars_preload_background(idx);
	}

	stars_set_background_model(The_mission.skybox_model, NULL, The_mission.skybox_flags);
	stars_set_background_orientation(&The_mission.skybox_orientation);

	stars_load_debris( ((The_mission.flags[Mission::Mission_Flags::Fullneb]) || Nebula_sexp_used) );

// following code randomly distributes star points within a sphere volume, which
// avoids there being denser areas along the edges and in corners that we had in the
// old rectangular distribution scheme.
	dist_max = (float) (HALF_RND_MAX * HALF_RND_MAX);
	for (i=0; i<MAX_STARS; i++) {
		dist = dist_max;
		while (dist >= dist_max) {
			v.xyz.x = (float) ((Random::next() & RND_MAX_MASK) - HALF_RND_MAX);
			v.xyz.y = (float) ((Random::next() & RND_MAX_MASK) - HALF_RND_MAX);
			v.xyz.z = (float) ((Random::next() & RND_MAX_MASK) - HALF_RND_MAX);

			dist = v.xyz.x * v.xyz.x + v.xyz.y * v.xyz.y + v.xyz.z * v.xyz.z;
		}
		vm_vec_copy_normalize(&Stars[i].pos, &v);

		{
			red = (ubyte)Random::next(192, 255);
			green = (ubyte)Random::next(192, 255);
			blue = (ubyte)Random::next(192, 255);
			alpha = (ubyte)Random::next(24, 216);

			gr_init_alphacolor(&Stars[i].col, red, green, blue, alpha, AC_TYPE_BLEND);
		}

	}

	memset( &Motion_debris, 0, sizeof(motion_debris_instance) * MAX_MOTION_DEBRIS );

	
	for (i=0; i<8; i++ ) {
		ubyte intensity = (ubyte)((i + 1) * 24);
		gr_init_alphacolor(&star_aacolors[i], 255, 255, 255, intensity, AC_TYPE_BLEND );
		gr_init_color(&star_colors[i], intensity, intensity, intensity );
	}

	last_stars_filled = 0;

	// if we have no sun instances, create one
	if ( !Suns.size() ) {
		if ( !strlen(Sun_bitmaps[0].filename) ) {
			mprintf(("Trying to add default sun but no default exists!!\n"));
		} else {
			mprintf(("Adding default sun.\n"));

			starfield_bitmap_instance def_sun;

			// stuff some values
			def_sun.ang.h = fl_radians(-60.0f);

			Suns.push_back(def_sun);
		}
	}

	// FRED doesn't do normal page_in stuff so we need to load up the bitmaps here instead
	if (Fred_running) {
		stars_load_all_bitmaps();

		// see whether we are missing any suns or bitmaps
		for (i = 0; i < (int)Backgrounds.size(); ++i) {
			SCP_string failed_suns;
			for (auto &sun : Backgrounds[i].suns) {
				if (stars_find_sun(sun.filename) < 0) {
					failed_suns += sun.filename;
					failed_suns += "\n";
				}
			}

			SCP_string failed_bitmaps;
			for (auto &bitmap : Backgrounds[i].bitmaps) {
				if (stars_find_bitmap(bitmap.filename) < 0) {
					failed_bitmaps += bitmap.filename;
					failed_bitmaps += "\n";
				}
			}

			if (!failed_suns.empty()) {
				Warning(LOCATION, "In Background %d, failed to load the following suns:\n%s", (i + 1), failed_suns.c_str());
			}
			if (!failed_bitmaps.empty()) {
				Warning(LOCATION, "In Background %d, failed to load the following bitmaps:\n%s", (i + 1), failed_bitmaps.c_str());
			}
		}
	}

	starfield_generate_bitmap_buffers();

	environment_map_gen();
}

void stars_level_close() {
	if (gr_screen.envmap_render_target >= 0) {
		if ( bm_release(gr_screen.envmap_render_target, 1) ) {
			gr_screen.envmap_render_target = -1;
		}
	}

	if (Mission_env_map >= 0) {
		bm_release(Mission_env_map);
		Mission_env_map = -1;
	}

	ENVMAP = Default_env_map;
}


extern object * Player_obj;

#define STAR_AMOUNT_DEFAULT 0.75f
#define STAR_DIM_DEFAULT 7800.0f
#define STAR_CAP_DEFAULT 75.0f
#define STAR_MAX_LENGTH_DEFAULT 0.04f		// 312

float Star_amount = STAR_AMOUNT_DEFAULT;
float Star_dim = STAR_DIM_DEFAULT;
float Star_cap = STAR_CAP_DEFAULT;
float Star_max_length = STAR_MAX_LENGTH_DEFAULT;

#define STAR_FLAG_TAIL			(1<<0)	// Draw a tail when moving
#define STAR_FLAG_DIM			(1<<1)	// Dim as you move
#define STAR_FLAG_ANTIALIAS		(1<<2)	// Draw the star using antialiased lines
#define STAR_FLAG_DEFAULT		(STAR_FLAG_TAIL | STAR_FLAG_DIM)

uint Star_flags = STAR_FLAG_DEFAULT;

//XSTR:OFF
DCF(stars,"Set parameters for starfield")
{
	SCP_string arg;
	float val_f;
	int val_i;

	if (dc_optional_string_either("help", "--help")) {
		dc_printf( "Usage: stars keyword\nWhere keyword can be in the following forms:\n" );
		dc_printf( "stars default   Resets stars to all default values\n" );
		dc_printf( "stars num X     Sets number of stars to X.  Between 0 and %d.\n", MAX_STARS );
		dc_printf( "stars tail X    Where X is the percent of 'tail' between 0 and 1.0\n" );
		dc_printf( "stars dim X     Where X is the amount stars dim between 0 and 255.0\n" );
		dc_printf( "stars cap X     Where X is the cap of dimming between 0 and 255.\n" );
		dc_printf( "stars len X     Where X is the cap of length.\n" );
		dc_printf( "stars m0        Macro0. Old 'pixel type' crappy stars. flags=none\n" );
		dc_printf( "stars m1        Macro1. (default) tail=.75, dim=20.0, cap=75.0, flags=dim,tail\n" );
		dc_printf( "stars m2        Macro2. tail=.75, dim=20.0, cap=75.0, flags=dim,tail,aa\n" );
		dc_printf( "stars flag X    Toggles flag X, where X is tail or dim or aa (aa=antialias)\n" );
		dc_printf( "\nHINT: set cap to 0 to get dim rate and tail down, then use\n" );
		dc_printf( "cap to keep the lines from going away when moving too fast.\n" );
		dc_printf( "\nUse '? stars' to see current values.\n" );
		return;	// don't print status if help is printed.  Too messy.
	}

	if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
		dc_printf( "Num_stars: %d\n", Num_stars );
		dc_printf( "Tail: %.2f\n", Star_amount );
		dc_printf( "Dim : %.2f\n", Star_dim );
		dc_printf( "Cap : %.2f\n", Star_cap );
		dc_printf( "Max length: %.2f\n", Star_max_length );
		dc_printf( "Flags:\n" );
		dc_printf( "  Tail : %s\n", (Star_flags&STAR_FLAG_TAIL?"On":"Off") );
		dc_printf( "  Dim  : %s\n", (Star_flags&STAR_FLAG_DIM?"On":"Off") );
		dc_printf( "  Antialias: %s\n", (Star_flags&STAR_FLAG_ANTIALIAS?"On":"Off") );
		dc_printf( "\nTHESE AREN'T SAVED TO DISK, SO IF YOU TWEAK\n" );
		dc_printf( "THESE AND LIKE THEM, WRITE THEM DOWN!!\n" );
		return;
	}

	dc_stuff_string_white(arg);
	// "stars default" is handled by "stars m1"
	if (arg == "num") {
		dc_stuff_int(&val_i);

		CLAMP(val_i, 0, MAX_STARS);
		Num_stars = val_i;

		dc_printf("Num_stars set to %i\n", Num_stars);
	
	} else if (arg == "tail") {
		dc_stuff_float(&val_f);
		CLAMP(val_f, 0.0, 1.0);
		Star_amount = val_f;
		
		dc_printf("Star_amount set to %f\n", Star_amount);

	} else if (arg == "dim") {
		dc_stuff_float(&val_f);

		if (val_f > 0.0f ) {
			Star_dim = val_f;
			dc_printf("Star_dim set to %f\n", Star_dim);
		
		} else {
			dc_printf("Error: Star_dim value must be non-negative\n");
		}
	
	} else if (arg == "cap") {
		dc_stuff_float(&val_f);
		CLAMP(val_f, 0.0, 255);
		Star_cap = val_f;
		
		dc_printf("Star_cap set to %f\n", Star_cap);
	
	} else if (arg == "len") {
		dc_stuff_float(&Star_max_length);

		dc_printf("Star_max_length set to %f\n", Star_max_length);

	} else if (arg == "m0") {
		Star_amount = 0.0f;
		Star_dim = 0.0f;
		Star_cap = 0.0f;
		Star_flags = 0;
		Star_max_length = STAR_MAX_LENGTH_DEFAULT;

		dc_printf("Starfield set: Old 'pixel type' crappy stars. flags=none\n");
	
	} else if ((arg == "m1") || (arg == "default")) {
		Star_amount = STAR_AMOUNT_DEFAULT;
		Star_dim = STAR_DIM_DEFAULT;
		Star_cap = STAR_CAP_DEFAULT;
		Star_flags = STAR_FLAG_DEFAULT;
		Star_max_length = STAR_MAX_LENGTH_DEFAULT;

		dc_printf("Starfield set: (default) tail=.75, dim=20.0, cap=75.0, flags=dim,tail\n");

	} else if (arg == "m2") {
		Star_amount = 0.75f;
		Star_dim = 20.0f;
		Star_cap = 75.0f;
		Star_flags = STAR_FLAG_TAIL|STAR_FLAG_DIM|STAR_FLAG_ANTIALIAS;
		Star_max_length = STAR_MAX_LENGTH_DEFAULT;

		dc_printf("Starfield set: tail=.75, dim=20.0, cap=75.0, flags=dim,tail,aa\n");

	} else if (arg == "flag") {
		dc_stuff_string_white(arg);
		if (arg == "tail") {
			Star_flags ^= STAR_FLAG_TAIL;
		} else if (arg == "dim" ) {
			Star_flags ^= STAR_FLAG_DIM;
		} else if (arg == "aa" ) {
			Star_flags ^= STAR_FLAG_ANTIALIAS;
		} else {
			dc_printf("Error: unknown flag argument '%s'\n", arg.c_str());
		}

	} else {
		dc_printf("Error: Unknown argument '%s'", arg.c_str());
	}
}
//XSTR:ON

bool refresh_motion_debris = true; // If set to true, then regenerate the positions of motion debris
// Call this if camera "cuts" or moves long distances
// so blur effect doesn't draw lines all over the screen.
void stars_camera_cut()
{
	last_stars_filled = 0;
	refresh_motion_debris = true;
}

//#define TIME_STAR_CODE		// enable to time star code

extern int Sun_drew;

// get the world coords of the sun pos on the unit sphere.
void stars_get_sun_pos(int sun_n, vec3d *pos)
{
	vec3d temp;
	matrix rot;

	// sanity
	Assert( sun_n < (int)Suns.size() );

	if ( (sun_n >= (int)Suns.size()) || (sun_n < 0) ) {
		return;
	}

	// rotate the sun properly
	temp = vmd_zero_vector;
	temp.xyz.z = 1.0f;
	
	// rotation matrix
	vm_angles_2_matrix(&rot, &Suns[sun_n].ang);
	vm_vec_unrotate(pos, &temp, &rot);
}

// draw sun
void stars_draw_sun(int show_sun)
{	
	GR_DEBUG_SCOPE("Draw Suns");
	TRACE_SCOPE(tracing::DrawSuns);

	int idx;
	vec3d sun_pos;
	vec3d sun_dir;
	vertex sun_vex;
	starfield_bitmap *bm;
	float local_scale;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	// should we even be here?
	if (!show_sun)
		return;

	// no suns drew yet
	Sun_drew = 0;

	// draw all suns
	int num_suns = (int)Suns.size();

	for (idx = 0; idx < num_suns; idx++) {
		// get the instance
		if (Suns[idx].star_bitmap_index < 0)
			return;

		bm = &Sun_bitmaps[Suns[idx].star_bitmap_index];

		// if no bitmap then bail...
		if (bm->bitmap_id < 0)
			continue;

		memset( &sun_vex, 0, sizeof(vertex) );

		// get sun pos
		sun_pos = vmd_zero_vector;
		sun_pos.xyz.y = 1.0f;
		stars_get_sun_pos(idx, &sun_pos);
		
		// get the direction
		sun_dir = sun_pos;
		vm_vec_normalize(&sun_dir);

		// add the light source corresponding to the sun, except when rendering to an envmap
		if ( !Rendering_to_env )
			light_add_directional(&sun_dir, bm->i, bm->r, bm->g, bm->b);

		// if supernova
		if ( supernova_active() && (idx == 0) )
			local_scale = 1.0f + (SUPERNOVA_SUN_SCALE * supernova_pct_complete());
		else
			local_scale = 1.0f;

		// draw the sun itself, keep track of how many we drew
		int bitmap_id = -1;
		if (bm->fps) {
			bitmap_id = bm->bitmap_id + ((timestamp() * bm->fps / MILLISECONDS_PER_SECOND) % bm->n_frames);
		} else {
			bitmap_id = bm->bitmap_id;
		}

		g3_rotate_faraway_vertex(&sun_vex, &sun_pos);

		if ( sun_vex.codes & (CC_BEHIND|CC_OFF_USER) ) {
			continue;
		}

		if ( !(sun_vex.flags & PF_PROJECTED) ) {
			g3_project_vertex(&sun_vex);
		}

		if ( sun_vex.flags & PF_OVERFLOW ) {
			continue;
		}

		material mat_params;
		material_set_unlit(&mat_params, bitmap_id, 0.999f, true, false);
		g3_render_rect_screen_aligned_2d(&mat_params, &sun_vex, 0, 0.05f * Suns[idx].scale_x * local_scale);
		Sun_drew++;

// 		if ( !g3_draw_bitmap(&sun_vex, 0, 0.05f * Suns[idx].scale_x * local_scale, TMAP_FLAG_TEXTURED) )
// 			Sun_drew++;
	}
}

// draw a star's lens-flare
void stars_draw_lens_flare(vertex *sun_vex, int sun_n)
{
	starfield_bitmap *bm;
	int i,j;
	float dx,dy;
	vertex flare_vex = *sun_vex; //copy over to flare_vex to get all sorts of properties

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	Assert( sun_n < (int)Suns.size() );

	if ( (sun_n >= (int)Suns.size()) || (sun_n < 0) ) {
		return;
	}

	// get the instance
	if (Suns[sun_n].star_bitmap_index < 0) {
		return;
	} else {
		bm = &Sun_bitmaps[Suns[sun_n].star_bitmap_index];
	}

	if (!bm->flare)
		return;
	
	/* (dx,dy) is a 2d vector equal to two times the vector from the sun's
	position to the center fo the screen meaning it is the vector to the 
	opposite position on the screen. */
	dx = 2.0f*(i2fl(gr_screen.clip_right-gr_screen.clip_left)*0.5f - sun_vex->screen.xyw.x);
	dy = 2.0f*(i2fl(gr_screen.clip_bottom-gr_screen.clip_top)*0.5f - sun_vex->screen.xyw.y);

	for (j = 0; j < bm->n_flare_bitmaps; j++)
	{
		// if no bitmap then bail...
		if (bm->flare_bitmaps[j].bitmap_id < 0)
			continue;

		//gr_set_bitmap(bm->flare_bitmaps[j].bitmap_id, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, 0.999f);

		for (i = 0; i < bm->n_flares; i++) {
			// draw sorted by texture, to minimize texture changes. not the most efficient way, but better than non-sorted
			if (bm->flare_infos[i].tex_num == j) {
				flare_vex.screen.xyw.x = sun_vex->screen.xyw.x + dx * bm->flare_infos[i].pos;
				flare_vex.screen.xyw.y = sun_vex->screen.xyw.y + dy * bm->flare_infos[i].pos;
				//g3_draw_bitmap(&flare_vex, 0, 0.05f * bm->flare_infos[i].scale, TMAP_FLAG_TEXTURED);
				material mat_params;
				material_set_unlit(&mat_params, bm->flare_bitmaps[j].bitmap_id, 0.999f, true, false);
				g3_render_rect_screen_aligned_2d(&mat_params, &flare_vex, 0, 0.05f * bm->flare_infos[i].scale);
			}
		}
	}
}

// draw the corresponding glow for sun_n
void stars_draw_sun_glow(int sun_n)
{
	starfield_bitmap *bm;
	vec3d sun_pos, sun_dir;
	vertex sun_vex;	
	float local_scale;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	// sanity
	//WMC - Dunno why this is getting hit...
	//Assert( sun_n < (int)Suns.size() );

	if ( (sun_n >= (int)Suns.size()) || (sun_n < 0) ) {
		return;
	}

	// get the instance
	if (Suns[sun_n].star_bitmap_index < 0)
		return;

	bm = &Sun_bitmaps[Suns[sun_n].star_bitmap_index];

	// if no bitmap then bail...
	if (bm->glow_bitmap < 0)
		return;

	memset( &sun_vex, 0, sizeof(vertex) );

	// get sun pos
	sun_pos = vmd_zero_vector;
	sun_pos.xyz.y = 1.0f;
	stars_get_sun_pos(sun_n, &sun_pos);	

	// get the direction
	sun_dir = sun_pos;
	vm_vec_normalize(&sun_dir);

	// if supernova
	if ( supernova_active() && (sun_n == 0) )
		local_scale = 1.0f + (SUPERNOVA_SUN_SCALE * supernova_pct_complete());
	else
		local_scale = 1.0f;

	// draw the sun itself, keep track of how many we drew
	int bitmap_id = -1;
	if (bm->glow_fps) {
		bitmap_id = bm->glow_bitmap + ((timestamp() * bm->glow_fps / MILLISECONDS_PER_SECOND) % bm->glow_n_frames);
	} else {
		bitmap_id = bm->glow_bitmap;
	}

	g3_rotate_faraway_vertex(&sun_vex, &sun_pos);
	//int zbuff = gr_zbuffer_set(GR_ZBUFF_NONE);
	//g3_draw_bitmap(&sun_vex, 0, 0.10f * Suns[sun_n].scale_x * local_scale, TMAP_FLAG_TEXTURED);
	material mat_params;
	material_set_unlit(&mat_params, bitmap_id, 0.5f, true, false);
	g3_render_rect_screen_aligned_2d(&mat_params, &sun_vex, 0, 0.10f * Suns[sun_n].scale_x * local_scale);

	if (bm->flare) {
		vec3d light_dir;
		vec3d local_light_dir;
		light_get_global_dir(&light_dir, sun_n);
		vm_vec_rotate(&local_light_dir, &light_dir, &Eye_matrix);
		float dot=vm_vec_dot( &light_dir, &Eye_matrix.vec.fvec );
		if (dot > 0.7f) // Only render the flares if the sun is reasonably near the center of the screen
			stars_draw_lens_flare(&sun_vex, sun_n);
	}

	//gr_zbuffer_set(zbuff);
}

void stars_draw_bitmaps(int show_bitmaps)
{
	GR_DEBUG_SCOPE("Draw Bitmaps");
	TRACE_SCOPE(tracing::DrawBitmaps);

	int idx;
	int star_index;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	// should we even be here?
	if ( !show_bitmaps )
		return;

	// if we're in the nebula, don't render any backgrounds
	if (The_mission.flags[Mission::Mission_Flags::Fullneb] && !The_mission.flags[Mission::Mission_Flags::Fullneb_background_bitmaps])
		return;

	// detail settings
	if ( !Detail.planets_suns )
		return;

	gr_start_instance_matrix(&Eye_position, &vmd_identity_matrix);

	int sb_instances = (int)Starfield_bitmap_instances.size();

	for (idx = 0; idx < sb_instances; idx++) {
		// lookup the info index
		star_index = Starfield_bitmap_instances[idx].star_bitmap_index;

		if (star_index < 0) {
			continue;
		}

		// if no bitmap then bail...
		if (Starfield_bitmaps[star_index].bitmap_id < 0) {
			continue;
		}

		int bitmap_id;
		bool blending = false;
		float alpha = 1.0f;

		if (Starfield_bitmaps[star_index].xparent) {
			if (Starfield_bitmaps[star_index].fps) {
				bitmap_id = Starfield_bitmaps[star_index].bitmap_id + (((timestamp() * Starfield_bitmaps[star_index].fps) / MILLISECONDS_PER_SECOND) % Starfield_bitmaps[star_index].n_frames);
			} else {
				bitmap_id = Starfield_bitmaps[star_index].bitmap_id;
			}
		} else {
			if (Starfield_bitmaps[star_index].fps) {
				bitmap_id = Starfield_bitmaps[star_index].bitmap_id + (((timestamp() * Starfield_bitmaps[star_index].fps) / MILLISECONDS_PER_SECOND) % Starfield_bitmaps[star_index].n_frames);
				blending = true;
				alpha = 0.9999f;
			} else {
				bitmap_id = Starfield_bitmaps[star_index].bitmap_id;	
				blending = true;
				alpha = 0.9999f;
			}
		}

		material material_params;
		material_set_unlit(&material_params, bitmap_id, alpha, blending, false);
		g3_render_primitives_textured(&material_params, Starfield_bitmap_instances[idx].verts, Starfield_bitmap_instances[idx].n_verts, PRIM_TYPE_TRIS, false);
	}
	
	gr_end_instance_matrix();
}

extern int Interp_subspace;
extern float Interp_subspace_offset_u;
extern float Interp_subspace_offset_u;
extern float Interp_subspace_offset_v;

float subspace_offset_u = 0.0f;
float subspace_offset_u_inner = 0.0f;
float subspace_offset_v = 0.0f;

float subspace_u_speed = 0.07f;			// how fast u changes
float subspace_v_speed = 0.05f;			// how fast v changes

int Subspace_glow_bitmap = -1;

float Subspace_glow_frame = 0.0f;
float Subspace_glow_rate = 1.0f;


//XSTR:OFF
DCF(subspace_set,"Set parameters for subspace effect")
{
	SCP_string arg;
	float value;

	if (dc_optional_string_either("help", "--help")) {
		dc_printf( "Usage: subspace [--status] <axis> <speed>\n");
		dc_printf("[--status] -- Displays the current speeds for both axes\n");
		dc_printf("<axis>  -- May be either 'u' or 'v', and corresponds to the texture axis\n");
		dc_printf("<speed> -- is the speed along the axis that the texture is moved\n");
		return;
	}

	if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
		dc_printf( "u: %.2f\n", subspace_u_speed );
		dc_printf( "v: %.2f\n", subspace_v_speed );
		return;
	}

	dc_stuff_string_white(arg);
	if (arg == "u") {
		dc_stuff_float(&value);

		if ( value < 0.0f ) {
			dc_printf("Error: speed must be non-negative");
			return;
		}
		subspace_u_speed = value;

	} else if (arg == "v") {
		dc_stuff_float(&value);

		if (value < 0.0f) {
			dc_printf("Error: speed must be non-negative");
			return;
		}
		subspace_v_speed = value;

	} else {
		dc_printf("Error: Unknown axis '%s'", arg.c_str());
	}
}
//XSTR:ON

void subspace_render()
{
	int framenum = 0;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if ( Subspace_model_inner < 0 )	{
		Subspace_model_inner = model_load( "subspace_small.pof", 0, nullptr );
		Assert(Subspace_model_inner >= 0);
	}

	if ( Subspace_model_outer < 0 )	{
		Subspace_model_outer = model_load( "subspace_big.pof", 0, nullptr );
		Assert(Subspace_model_outer >= 0);
	}

	if ( Subspace_glow_bitmap < 0 )	{
		Subspace_glow_bitmap = bm_load( NOX("SunGlow01"));
		Assert(Subspace_glow_bitmap >= 0);
	}

	if ( !Rendering_to_env ) {
		Subspace_glow_frame += flFrametime * 1.0f;

		float total_time = i2fl(NOISE_NUM_FRAMES) / 15.0f;

		// Sanity checks
		if ( Subspace_glow_frame < 0.0f )
			Subspace_glow_frame = 0.0f;
		if ( Subspace_glow_frame > 100.0f )
			Subspace_glow_frame = 0.0f;

		while ( Subspace_glow_frame > total_time ) {
			Subspace_glow_frame -= total_time;
		}

		framenum = fl2i( (Subspace_glow_frame*NOISE_NUM_FRAMES) / total_time );

		if ( framenum < 0 )
			framenum = 0;
		if ( framenum >= NOISE_NUM_FRAMES )
			framenum = NOISE_NUM_FRAMES-1;

		subspace_offset_u += flFrametime*subspace_u_speed;
		if (subspace_offset_u > 1.0f ) {
			subspace_offset_u -= 1.0f;
		}

		subspace_offset_u_inner += flFrametime*subspace_u_speed*3.0f;
		if (subspace_offset_u > 1.0f ) {
			subspace_offset_u -= 1.0f;
		}

		subspace_offset_v += flFrametime*subspace_v_speed;
		if (subspace_offset_v > 1.0f ) {
			subspace_offset_v -= 1.0f;
		}
	}


	matrix tmp;
	angles angs = vmd_zero_angles;

	angs.b = subspace_offset_v * PI2;

	vm_angles_2_matrix(&tmp,&angs);

	int saved_gr_zbuffering = gr_zbuffer_get();

	gr_zbuffer_set(GR_ZBUFF_NONE);

	int render_flags = MR_NO_LIGHTING | MR_ALL_XPARENT;

	Interp_subspace = 1;
	Interp_subspace_offset_u = 1.0f - subspace_offset_u;
	Interp_subspace_offset_v = 0.0f;

	model_render_params render_info;
	render_info.set_alpha(1.0f);
	render_info.set_flags(render_flags);

	gr_set_texture_panning(Interp_subspace_offset_v, Interp_subspace_offset_u, true);

	model_render_immediate( &render_info, Subspace_model_outer, &tmp, &Eye_position);	//MR_NO_CORRECT|MR_SHOW_OUTLINE

	gr_set_texture_panning(0, 0, false);

	Interp_subspace = 1;
	Interp_subspace_offset_u = 1.0f - subspace_offset_u_inner;
	Interp_subspace_offset_v = 0.0f;

	angs.b = -subspace_offset_v * PI2;

	vm_angles_2_matrix(&tmp,&angs);

	render_info.set_color(255, 255, 255);
	render_info.set_alpha(1.0f);
	render_info.set_flags(render_flags);

	gr_set_texture_panning(Interp_subspace_offset_v, Interp_subspace_offset_u, true);

	model_render_immediate( &render_info, Subspace_model_inner, &tmp, &Eye_position );	//MR_NO_CORRECT|MR_SHOW_OUTLINE

	gr_set_texture_panning(0, 0, false);

	//Render subspace glows here and not as thrusters - Valathil 
	vec3d glow_pos;
	vertex glow_vex;	

	glow_pos.xyz.x = 0.0f;
	glow_pos.xyz.y = 0.0f;
	glow_pos.xyz.z = 100.0f;

	//gr_set_bitmap(Subspace_glow_bitmap, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, 1.0f);
	material mat_params;
	material_set_unlit(&mat_params, Subspace_glow_bitmap, 1.0f, true, false);

	g3_rotate_faraway_vertex(&glow_vex, &glow_pos);
	//g3_draw_bitmap(&glow_vex, 0, 17.0f + 0.5f * Noise[framenum], TMAP_FLAG_TEXTURED);
	g3_render_rect_screen_aligned_2d(&mat_params, &glow_vex, 0, 17.0f + 0.5f * Noise[framenum]);

	glow_pos.xyz.z = -100.0f;

	g3_rotate_faraway_vertex(&glow_vex, &glow_pos);
	//g3_draw_bitmap(&glow_vex, 0, 17.0f + 0.5f * Noise[framenum], TMAP_FLAG_TEXTURED);
	g3_render_rect_screen_aligned_2d(&mat_params, &glow_vex, 0, 17.0f + 0.5f * Noise[framenum]);

	Interp_subspace = 0;
	gr_zbuffer_set(saved_gr_zbuffering);
}

void stars_draw_stars()
{
	GR_DEBUG_SCOPE("Draw Starfield");
	TRACE_SCOPE(tracing::DrawStarfield);

	int i;
	star *sp;
	float dist = 0.0f;
	float ratio;
	vDist vDst;
	vertex p1, p2;
	int can_draw = 1;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if ( !last_stars_filled ) {
		for (i = 0; i < Num_stars; i++) {
			g3_rotate_faraway_vertex(&p2, &Stars[i].pos);
			Stars[i].last_star_pos = p2.world;
		}
	}

	int tmp_num_stars = 0;

	tmp_num_stars = (Detail.num_stars * Num_stars) / MAX_DETAIL_LEVEL;
	CLAMP(tmp_num_stars, 0, Num_stars);

	auto path = graphics::paths::PathRenderer::instance();

	path->saveState();
	path->resetState();

	path->beginFrame();

	for (i = 0; i < tmp_num_stars; i++) {
		sp = &Stars[i];

		can_draw = 1;
		memset(&p1, 0, sizeof(vertex));
		memset(&p2, 0, sizeof(vertex));

		// This makes a star look "proper" by not translating the
		// point around the viewer's eye before rotation.  In other
		// words, when the ship translates, the stars do not change.

		g3_rotate_faraway_vertex(&p2, &sp->pos);
		if ( p2.codes )	{
			can_draw = 0;
		} else {
			g3_project_vertex(&p2);
			if ( p2.flags & PF_OVERFLOW ) {
				can_draw = 0;
			}
		}

		if ( can_draw && (Star_flags & (STAR_FLAG_TAIL|STAR_FLAG_DIM)) ) {
			dist = vm_vec_dist_quick( &sp->last_star_pos, &p2.world );

			if ( dist > Star_max_length ) {
 				ratio = Star_max_length / dist;
				dist = Star_max_length;
			} else {
				ratio = 1.0f;
			}
			
			ratio *= Star_amount;

			vm_vec_sub(&p1.world, &sp->last_star_pos, &p2.world);
			vm_vec_scale(&p1.world, ratio);
			vm_vec_add2(&p1.world, &p2.world);

			p1.flags = 0;	// not projected
			g3_code_vertex( &p1 );

			if ( p1.codes )	{
				can_draw = 0;
			} else {
				g3_project_vertex(&p1);
				if ( p1.flags & PF_OVERFLOW ) {
					can_draw = 0;
				}
			}
		}

		sp->last_star_pos = p2.world;

		if ( !can_draw )
			continue;

		vDst.x = fl2i(p1.screen.xyw.x) - fl2i(p2.screen.xyw.x);
		vDst.y = fl2i(p1.screen.xyw.y) - fl2i(p2.screen.xyw.y);

		float len = sqrtf((float)((vDst.x * vDst.x) + (vDst.y * vDst.y)));

		color col = sp->col;
		if (len <= 2.0f ) {
			p1.screen.xyw.x = p2.screen.xyw.x + 1.0f;
			p1.screen.xyw.y = p2.screen.xyw.y;
		} else {
			// gamma correction
			col.red = (ubyte)((float)col.red / powf(len, 1.0f / 2.2f));
			col.green = (ubyte)((float)col.green / powf(len, 1.0f / 2.2f));
			col.blue = (ubyte)((float)col.blue / powf(len, 1.0f / 2.2f));
			col.alpha = (ubyte)((float)col.alpha  / powf(len, 1.0f / 2.2f));
		}
		path->beginPath();

		path->moveTo(p1.screen.xyw.x, p1.screen.xyw.y);
		path->lineTo(p2.screen.xyw.x, p2.screen.xyw.y);

		path->setStrokeColor(&col);
		path->stroke();
	}
	path->endFrame();
	
	path->restoreState();
}

void stars_draw_motion_debris()
{
	GR_DEBUG_SCOPE("Draw motion debris");
	TRACE_SCOPE(tracing::DrawMotionDebris);

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if (Motion_debris_override)
		return;

	if (!Motion_debris_enabled || ((int)Motion_debris_info.size() == 0)) {
		return;
	}

	for (motion_debris_instance &mdebris : Motion_debris) {
		float vdist = vm_vec_dist(&mdebris.pos, &Eye_position);

		if ((vdist < MIN_DIST_RANGE) || (vdist > MAX_DIST_RANGE)) {
			// if we just had a camera "cut" and should refresh the debris then generate in the sphere, else just on its surface
			vm_vec_random_in_sphere(&mdebris.pos, &Eye_position, MAX_DIST_RANGE, !refresh_motion_debris);
			vdist = vm_vec_dist(&mdebris.pos, &Eye_position);

			mdebris.vclip = Random::next(MAX_MOTION_DEBRIS_BITMAPS); // rand()

			// if we're in full neb mode
			const float size_multiplier = i2fl(Random::next(4));
			if((The_mission.flags[Mission::Mission_Flags::Fullneb]) && (Neb2_render_mode != NEB2_RENDER_NONE)) {
				mdebris.size = size_multiplier * BASE_SIZE_NEB;
			} else {
				mdebris.size = size_multiplier * BASE_SIZE;
			}
		}

		vertex pnt;
		g3_rotate_vertex(&pnt, &mdebris.pos);

		if (pnt.codes == 0) {
			int frame = Missiontime / (DEBRIS_ROT_MIN + (1 % DEBRIS_ROT_RANGE) * DEBRIS_ROT_RANGE_SCALER);
			frame %= Motion_debris_ptr[mdebris.vclip].nframes;

			float alpha;

			if ( (The_mission.flags[Mission::Mission_Flags::Fullneb]) && (Neb2_render_mode != NEB2_RENDER_NONE) ) {
				alpha = 0.3f;
			} else {
				alpha = 1.0f;
			}

			// scale alpha from 0 at max range to full at 60% range
			alpha *= (vdist - MAX_DIST_RANGE) / -(MAX_DIST_RANGE * 0.6f);

			g3_transfer_vertex(&pnt, &mdebris.pos);

			batching_add_bitmap(Motion_debris_ptr[mdebris.vclip].bm + frame, &pnt, 0, mdebris.size, alpha);
		}
	}

	if (refresh_motion_debris)
		refresh_motion_debris = false;
}

void stars_draw(int show_stars, int show_suns, int  /*show_nebulas*/, int show_subspace, int env, bool in_mission)
{
	GR_DEBUG_SCOPE("Draw Stars");
	TRACE_SCOPE(tracing::DrawStars);

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	int gr_zbuffering_save = gr_zbuffer_get();
	gr_zbuffer_set(GR_ZBUFF_NONE);

	Rendering_to_env = env;

	if (show_subspace)
		subspace_render();

	if (Num_stars >= MAX_STARS)
		Num_stars = MAX_STARS;

#ifdef TIME_STAR_CODE
	fix xt1, xt2;
	xt1 = timer_get_fixed_seconds();
#endif
	
	// draw background stuff
	if ( show_stars ) {
		// semi-hack, do we don't fog the background
		int neb_save = Neb2_render_mode;
		Neb2_render_mode = NEB2_RENDER_NONE;
		stars_draw_background();
		Neb2_render_mode = neb_save;
	}
	else if ( !show_subspace ) // don't render the background pof when rendering subspace
	{
		stars_draw_background();
	}

	if ( !env && show_stars && (Nmodel_num < 0) && (Game_detail_flags & DETAIL_FLAG_STARS) && !(The_mission.flags[Mission::Mission_Flags::Fullneb]) && (supernova_stage() < SUPERNOVA_STAGE::TOOLTIME) ) {
		stars_draw_stars();
	}

	last_stars_filled = 1;

#ifdef TIME_STAR_CODE
	xt2 = timer_get_fixed_seconds();
	mprintf(( "Stars: %d\n", xt2-xt1 ));
#endif

	if ( !Rendering_to_env && (Game_detail_flags & DETAIL_FLAG_MOTION) && (!Fred_running) && (supernova_stage() < SUPERNOVA_STAGE::TOOLTIME) && in_mission)	{
		stars_draw_motion_debris();
	}

	//if we're not drawing them, quit here
	if (show_suns) {
		stars_draw_sun( show_suns );
		stars_draw_bitmaps( show_suns );
	}

	gr_zbuffer_set( gr_zbuffering_save );
	Rendering_to_env = 0;
}

void stars_preload_background(const char *token)
{
	if (!token)
		return;

	// we can only preload raw numbers, but that's probably sufficient
	if (!can_construe_as_integer(token))
		return;

	int background_idx = atoi(token);

	// human/computer offset
	background_idx--;

	// store it for now
	Preload_background_indexes.push_back(background_idx);
}

void stars_preload_background(int background_idx)
{
	// range check
	if (background_idx < 0 || background_idx >= (int)Backgrounds.size())
		return;

	// preload all the stuff for this background
	for (auto &bgsun : Backgrounds[background_idx].suns)
		stars_preload_sun_bitmap(bgsun.filename);
	for (auto &bitmap : Backgrounds[background_idx].bitmaps)
		stars_preload_background_bitmap(bitmap.filename);
}

void stars_preload_sun_bitmap(const char *fname)
{
	int idx;

	if (fname == NULL)
		return;

	idx = stars_find_sun(fname);

	if (idx == -1) {
		return;
	}

	Sun_bitmaps[idx].preload = 1;
}

void stars_preload_background_bitmap(const char *fname)
{
	int idx;

	if (fname == NULL)
		return;

	idx = stars_find_bitmap(fname);

	if (idx == -1) {
		return;
	}

	Starfield_bitmaps[idx].preload = 1;
}

void stars_page_in()
{
	int idx, i;
	starfield_bitmap_instance *sbi;
	starfield_bitmap *sb;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	// Initialize the subspace stuff

	if (Game_subspace_effect || (The_mission.flags[Mission::Mission_Flags::Preload_subspace])) {
		Subspace_model_inner = model_load("subspace_small.pof", 0, nullptr);
		Assert(Subspace_model_inner >= 0);

		Subspace_model_outer = model_load("subspace_big.pof", 0, nullptr);
		Assert(Subspace_model_outer >= 0);

		polymodel *pm;
		
		pm = model_get(Subspace_model_inner);
		
		nprintf(( "Paging", "Paging in textures for inner subspace effect.\n" ));

		for (idx = 0; idx < pm->n_textures; idx++) {
			pm->maps[idx].PageIn();
		}

		pm = model_get(Subspace_model_outer);
		
		nprintf(( "Paging", "Paging in textures for outer subspace effect.\n" ));

		for (idx = 0; idx < pm->n_textures; idx++) {
			pm->maps[idx].PageIn();
		}

		if (Subspace_glow_bitmap < 0) {
			Subspace_glow_bitmap = bm_load( NOX("SunGlow01"));
		}

		bm_page_in_xparent_texture(Subspace_glow_bitmap);
	} else {
		Subspace_model_inner = -1;
		Subspace_model_outer = -1;

		if (Subspace_glow_bitmap > 0) {
			bm_release(Subspace_glow_bitmap);
			Subspace_glow_bitmap = -1;
		}
	}

	// extra SEXP related checks to preload anything that might get used from there
	for (idx = 0; idx < (int)Starfield_bitmaps.size(); idx++) {
		sb = &Starfield_bitmaps[idx];

		if (sb->used_this_level)
			continue;

		if (sb->preload) {
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load(sb->filename);

				// maybe didn't load a static image so try for an animated one
				if (sb->bitmap_id < 0) {
					sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

					if (sb->bitmap_id < 0) {
						Warning(LOCATION, "Unable to load starfield bitmap: '%s'!\n", sb->filename);
					}
				}
			}

			// this happens whether it loaded properly or not, no harm should come from it
			if (sb->xparent) {
				bm_page_in_xparent_texture(sb->bitmap_id);
			} else {
				bm_page_in_texture(sb->bitmap_id);
			}

			sb->used_this_level++;
		}
	}

	for (idx = 0; idx < (int)Sun_bitmaps.size(); idx++) {
		sb = &Sun_bitmaps[idx];

		if (sb->used_this_level)
			continue;

		if (sb->preload) {
			// normal bitmap
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load(sb->filename);

				// maybe didn't load a static image so try for an animated one
				if (sb->bitmap_id < 0) {
					sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

					if (sb->bitmap_id < 0) {
						Warning(LOCATION, "Unable to load sun bitmap: '%s'!\n", sb->filename);
					}
				}
			}

			// glow bitmap
			if (sb->glow_bitmap < 0) {
				sb->glow_bitmap = bm_load(sb->glow_filename);

				// maybe didn't load a static image so try for an animated one
				if (sb->glow_bitmap < 0) {
					sb->glow_bitmap = bm_load_animation(sb->glow_filename, &sb->glow_n_frames, &sb->glow_fps, nullptr, nullptr, true);

					if (sb->glow_bitmap < 0) {
						Warning(LOCATION, "Unable to load sun glow bitmap: '%s'!\n", sb->glow_filename);
					}
				}
			}

			if (sb->flare) {
				for (i = 0; i < MAX_FLARE_BMP; i++) {
					if ( !strlen(sb->flare_bitmaps[i].filename) )
						continue;

					if (sb->flare_bitmaps[i].bitmap_id < 0) {
						sb->flare_bitmaps[i].bitmap_id = bm_load(sb->flare_bitmaps[i].filename);

						if (sb->flare_bitmaps[i].bitmap_id < 0) {
							Warning(LOCATION, "Unable to load sun flare bitmap: '%s'!\n", sb->flare_bitmaps[i].filename);
							continue;
						}
					}

					bm_page_in_texture(sb->flare_bitmaps[i].bitmap_id);
				}
			}

			bm_page_in_texture(sb->bitmap_id);
			bm_page_in_texture(sb->glow_bitmap);

			sb->used_this_level++;
		}
	}

	// load and page in needed starfield bitmaps
	for (idx = 0; idx < (int)Starfield_bitmap_instances.size(); idx++) {
		sbi = &Starfield_bitmap_instances[idx];

		if (sbi->star_bitmap_index < 0)
			continue;

		sb = &Starfield_bitmaps[sbi->star_bitmap_index];

		if (sb->used_this_level)
			continue;

		if (sb->bitmap_id < 0 ) {
			sb->bitmap_id = bm_load(sb->filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

				if (sb->bitmap_id < 0) {
					Warning(LOCATION, "Unable to load starfield bitmap: '%s'!\n", sb->filename);
				}
			}
		}

		// this happens whether it loaded properly or not, no harm should come from it
		if (sb->xparent) {
			bm_page_in_xparent_texture(sb->bitmap_id);
		} else {
			bm_page_in_texture(sb->bitmap_id);
		}

		sb->used_this_level++;
	}

	// now for sun bitmaps and glows
	for (idx = 0; idx < (int)Suns.size(); idx++) {
		sbi = &Suns[idx];

		if (sbi->star_bitmap_index < 0)
			continue;

		sb = &Sun_bitmaps[sbi->star_bitmap_index];

		if (sb->used_this_level)
			continue;

		// normal bitmap
		if (sb->bitmap_id < 0) {
			sb->bitmap_id = bm_load(sb->filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->bitmap_id < 0) {
				sb->bitmap_id = bm_load_animation(sb->filename, &sb->n_frames, &sb->fps, nullptr, nullptr, true);

				if (sb->bitmap_id < 0) {
					Warning(LOCATION, "Unable to load sun bitmap: '%s'!\n", sb->filename);
				}
			}
		}

		// glow bitmap
		if (sb->glow_bitmap < 0) {
			sb->glow_bitmap = bm_load(sb->glow_filename);

			// maybe didn't load a static image so try for an animated one
			if (sb->glow_bitmap < 0) {
				sb->glow_bitmap = bm_load_animation(sb->glow_filename, &sb->glow_n_frames, &sb->glow_fps, nullptr, nullptr, true);

				if (sb->glow_bitmap < 0) {
					Warning(LOCATION, "Unable to load sun glow bitmap: '%s'!\n", sb->glow_filename);
				}
			}
		}

		if (sb->flare) {
			for (i = 0; i < MAX_FLARE_BMP; i++) {
				if ( !strlen(sb->flare_bitmaps[i].filename) )
					continue;

				if (sb->flare_bitmaps[i].bitmap_id < 0) {
					sb->flare_bitmaps[i].bitmap_id = bm_load(sb->flare_bitmaps[i].filename);

					if (sb->flare_bitmaps[i].bitmap_id < 0) {
						Warning(LOCATION, "Unable to load sun flare bitmap: '%s'!\n", sb->flare_bitmaps[i].filename);
						continue;
					}
				}

				bm_page_in_texture(sb->flare_bitmaps[i].bitmap_id);
			}
		}

		bm_page_in_texture(sb->bitmap_id);
		bm_page_in_texture(sb->glow_bitmap);

		sb->used_this_level++;
	}


	if (!Motion_debris_enabled || Motion_debris_override)
		return;

	for (idx = 0; idx < MAX_MOTION_DEBRIS_BITMAPS; idx++) {
		bm_page_in_xparent_texture(Motion_debris_ptr[idx].bm, Motion_debris_ptr[idx].nframes);
	}	
}

// background nebula models and planets
void stars_draw_background()
{	
	GR_DEBUG_SCOPE("Draw Background");
	TRACE_SCOPE(tracing::DrawBackground);

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if (Nmodel_num < 0)
		return;

	model_render_params render_info;

	if (Nmodel_bitmap >= 0) {
		render_info.set_forced_bitmap(Nmodel_bitmap);
	}

	// draw the model at the player's eye with no z-buffering
	render_info.set_alpha(1.0f);
	render_info.set_flags(Nmodel_flags | MR_SKYBOX);

	model_render_immediate(&render_info, Nmodel_num, Nmodel_instance_num, &Nmodel_orient, &Eye_position, MODEL_RENDER_ALL, false);
}

// call this to set a specific model as the background model
void stars_set_background_model(const char *model_name, const char *texture_name, int flags)
{
	int new_model = -1;
	int new_bitmap = -1;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if (model_name != nullptr && *model_name != '\0' && stricmp(model_name, "none") != 0) {
		new_model = model_load(model_name, 0, nullptr, -1);

		if (texture_name != nullptr && *texture_name != '\0') {
			new_bitmap = bm_load(texture_name);
		}
	}

	// see if we are actually changing anything
	if (Nmodel_num == new_model && Nmodel_bitmap == new_bitmap && Nmodel_flags == flags) {
		return;
	}

	if (Nmodel_bitmap >= 0) {
		bm_unload(Nmodel_bitmap);
		Nmodel_bitmap = -1;
	}
	
	if (Nmodel_num >= 0) {
		model_unload(Nmodel_num);
		Nmodel_num = -1;
	}

	if (Nmodel_instance_num >= 0) {
		model_delete_instance(Nmodel_instance_num);
		Nmodel_instance_num = -1;
	}

	Nmodel_flags = flags;
	Nmodel_num = new_model;
	Nmodel_bitmap = new_bitmap;

	if (Nmodel_num >= 0) {
		model_page_in_textures(Nmodel_num);

		Nmodel_instance_num = model_create_instance(-1, Nmodel_num);
		The_mission.skybox_model_animations.initializeMoveables(model_get_instance(Nmodel_instance_num));
	}

	// Since we have a new skybox we need to rerender the environment map
	stars_invalidate_environment_map();
}

// call this to set a specific orientation for the background
void stars_set_background_orientation(const matrix *orient)
{
	if (orient == NULL) {
		vm_set_identity(&Nmodel_orient);
	} else {
		Nmodel_orient = *orient;
	}
}

// lookup a starfield bitmap, return index or -1 on fail
int stars_find_bitmap(const char *name)
{
	int idx;

	if (name == NULL)
		return -1;

	// lookup
	for (idx = 0; idx < (int)Starfield_bitmaps.size(); idx++) {
		if ( !stricmp(name, Starfield_bitmaps[idx].filename) ) {
			return idx;
		}
	}

	// not found 
	return -1;
}

// lookup a sun by bitmap filename, return index or -1 on fail
int stars_find_sun(const char *name)
{
	int idx;

	if (name == NULL)
		return -1;

	// lookup
	for (idx = 0; idx < (int)Sun_bitmaps.size(); idx++) {
		if ( !stricmp(name, Sun_bitmaps[idx].filename) ) {
			return idx;
		}
	}

	// not found 
	return -1;
}

// add an instance for a sun (something actually used in a mission)
// NOTE that we assume a duplicate is ok here
int stars_add_sun_entry(starfield_list_entry *sun_ptr)
{
	int idx, i;
	starfield_bitmap_instance sbi;

	Assert(sun_ptr != NULL);

	// copy information
	sbi.ang.p = sun_ptr->ang.p;
	sbi.ang.b = sun_ptr->ang.b;
	sbi.ang.h = sun_ptr->ang.h;
	sbi.scale_x = sun_ptr->scale_x;
	sbi.scale_y = sun_ptr->scale_y;
	sbi.div_x = sun_ptr->div_x;
	sbi.div_y = sun_ptr->div_y;

	idx = stars_find_sun(sun_ptr->filename);

	if (idx == -1) {
		if (!Fred_running) {
			Warning(LOCATION, "Trying to add a sun '%s' that does not exist in stars.tbl!", sun_ptr->filename);
		}
		return -1;
	}

	sbi.star_bitmap_index = idx;

	// make sure any needed bitmaps are loaded
	if (Sun_bitmaps[idx].bitmap_id < 0) {
		// normal bitmap
		Sun_bitmaps[idx].bitmap_id = bm_load(Sun_bitmaps[idx].filename);

			// maybe didn't load a static image so try for an animated one
		if (Sun_bitmaps[idx].bitmap_id < 0) {
			Sun_bitmaps[idx].bitmap_id = bm_load_animation(Sun_bitmaps[idx].filename, &Sun_bitmaps[idx].n_frames, &Sun_bitmaps[idx].fps, nullptr, nullptr, true);

			if (Sun_bitmaps[idx].bitmap_id < 0) {
				// failed
				return -1;
			}
		}

		// glow bitmap
		if (Sun_bitmaps[idx].glow_bitmap < 0) {
			Sun_bitmaps[idx].glow_bitmap = bm_load(Sun_bitmaps[idx].glow_filename);

			// maybe didn't load a static image so try for an animated one
			if (Sun_bitmaps[idx].glow_bitmap < 0) {
				Sun_bitmaps[idx].glow_bitmap = bm_load_animation(Sun_bitmaps[idx].glow_filename, &Sun_bitmaps[idx].glow_n_frames, &Sun_bitmaps[idx].glow_fps, nullptr, nullptr, true);

				if (Sun_bitmaps[idx].glow_bitmap < 0) {
					Warning(LOCATION, "Unable to load sun glow bitmap: '%s'!\n", Sun_bitmaps[idx].glow_filename);
				}
			}
		}

		if (Sun_bitmaps[idx].flare) {
			for (i = 0; i < MAX_FLARE_BMP; i++) {
				flare_bitmap* fbp = &Sun_bitmaps[idx].flare_bitmaps[i];
				if ( !strlen(fbp->filename) )
					continue;

				if (fbp->bitmap_id < 0) {
					fbp->bitmap_id = bm_load(fbp->filename);

					if (fbp->bitmap_id < 0) {
						Warning(LOCATION, "Unable to load sun flare bitmap: '%s'!\n", Sun_bitmaps[idx].flare_bitmaps[i].filename);
						continue;
					}
				}
			}
		}
	}

	// The background changed so we need to invalidate the environment map
	stars_invalidate_environment_map();

	// now check if we can make use of a previously discarded instance entry
	// this should never happen with FRED
	if ( !Fred_running ) {
		for (i = 0; i < (int)Suns.size(); i++) {
			if ( Suns[i].star_bitmap_index < 0 ) {
				Suns[i] = sbi;
				return i;
			}
		}
	}

	// ... or add a new one 
	Suns.push_back(sbi);

	return (int)(Suns.size() - 1);
}

// add an instance for a starfield bitmap (something actually used in a mission)
// NOTE that we assume a duplicate is ok here
int stars_add_bitmap_entry(starfield_list_entry *sle)
{
	int idx;
	starfield_bitmap_instance sbi;

	Assert(sle != NULL);

	// copy information
	sbi.ang.p = sle->ang.p;
	sbi.ang.b = sle->ang.b;
	sbi.ang.h = sle->ang.h;
	sbi.scale_x = sle->scale_x;
	sbi.scale_y = sle->scale_y;
	sbi.div_x = sle->div_x;
	sbi.div_y = sle->div_y;

	idx = stars_find_bitmap(sle->filename);

	if (idx == -1) {
		if (!Fred_running) {
			Warning(LOCATION, "Trying to add a bitmap '%s' that does not exist in stars.tbl!", sle->filename);
		}
		return -1;
	}

	sbi.star_bitmap_index = idx;

	// make sure any needed bitmaps are loaded
	if (Starfield_bitmaps[idx].bitmap_id < 0) {
		Starfield_bitmaps[idx].bitmap_id = bm_load(Starfield_bitmaps[idx].filename);

		// maybe didn't load a static image so try for an animated one
		if (Starfield_bitmaps[idx].bitmap_id < 0) {
			Starfield_bitmaps[idx].bitmap_id = bm_load_animation(Starfield_bitmaps[idx].filename, &Starfield_bitmaps[idx].n_frames, &Starfield_bitmaps[idx].fps, nullptr, nullptr, true);

			if (Starfield_bitmaps[idx].bitmap_id < 0) {
				// failed
				return -1;
			}
		}
	}

	// The background changed so we need to invalidate the environment map
	stars_invalidate_environment_map();

	// now check if we can make use of a previously discarded instance entry
	for (int i = 0; i < (int)Starfield_bitmap_instances.size(); i++) {
		if ( Starfield_bitmap_instances[i].star_bitmap_index < 0 ) {
			// starfield_update_index_buffers(i, 0);
			Starfield_bitmap_instances[i] = sbi;
			starfield_create_bitmap_buffer(i);
			return i;
		}
	}

	// ... or add a new one
	Starfield_bitmap_instances.push_back(sbi);
	starfield_create_bitmap_buffer((int)(Starfield_bitmap_instances.size() - 1));

	return (int)(Starfield_bitmap_instances.size() - 1);
}

void stars_correct_background_sun_angles(angles* angs_to_correct)
{
	matrix mat;
	vm_angles_2_matrix(&mat, angs_to_correct);
	vm_transpose(&mat);
	vm_extract_angles_matrix(angs_to_correct, &mat);
	angs_to_correct->p = fmod(angs_to_correct->p + PI2, PI2);
	angs_to_correct->b = fmod(angs_to_correct->b + PI2, PI2);
	angs_to_correct->h = fmod(angs_to_correct->h + PI2, PI2);
}

void stars_uncorrect_background_sun_angles(angles* angs_to_uncorrect)
{
	// the actual operation is an inversion so 'correcting' and 'uncorrecting' are the same
	stars_correct_background_sun_angles(angs_to_uncorrect);
}

void stars_correct_background_bitmap_angles(angles *angs_to_correct)
{
	matrix mat1, mat2;
	angles ang1 = vm_angles_new(0.0, angs_to_correct->b, 0.0);
	angles ang2 = vm_angles_new(angs_to_correct->p, 0.0, angs_to_correct->h);
	vm_angles_2_matrix(&mat1, &ang1);
	vm_angles_2_matrix(&mat2, &ang2);
	matrix mat3 = mat2 * mat1;
	vm_transpose(&mat3);
	vm_extract_angles_matrix(angs_to_correct, &mat3);
	angs_to_correct->p = fmod(angs_to_correct->p + PI2, PI2);
	angs_to_correct->b = fmod(angs_to_correct->b + PI2, PI2);
	angs_to_correct->h = fmod(angs_to_correct->h + PI2, PI2);
}

void stars_uncorrect_background_bitmap_angles(angles *angs_to_uncorrect)
{
	matrix mat;
	vm_angles_2_matrix(&mat, angs_to_uncorrect);
	// transpose and {2,3,1} permute rows and cols
	matrix mat_permuted = vm_matrix_new(
		mat.vec.uvec.xyz.y, mat.vec.fvec.xyz.y, mat.vec.rvec.xyz.y,
		mat.vec.uvec.xyz.z, mat.vec.fvec.xyz.z, mat.vec.rvec.xyz.z,
		mat.vec.uvec.xyz.x, mat.vec.fvec.xyz.x, mat.vec.rvec.xyz.x
	);
	angles angs_permuted;
	vm_extract_angles_matrix(&angs_permuted, &mat_permuted);
	// {2,3,1} unpermute p,b,h
	angs_to_uncorrect->p = angs_permuted.b;
	angs_to_uncorrect->h = angs_permuted.p;
	angs_to_uncorrect->b = angs_permuted.h;
}

// get the number of entries that each vector contains
// "is_a_sun" will get sun instance counts, otherwise it gets normal starfield bitmap instance counts
// "bitmap_count" will get number of starfield_bitmap entries rather than starfield_bitmap_instance entries
int stars_get_num_entries(bool is_a_sun, bool bitmap_count)
{
	// try for instance counts first
	if (!bitmap_count) {
		if (is_a_sun) {
			return (int)Suns.size();
		} else {
			return (int)Starfield_bitmap_instances.size();
		}
	}
	// looks like we want bitmap counts (probably only FRED uses this)
	else {
		if (is_a_sun) {
			return (int)Sun_bitmaps.size();
		} else {
			return (int)Starfield_bitmaps.size();
		}
	}
}


// get a starfield_bitmap entry providing only an instance
starfield_bitmap *stars_get_bitmap_entry(int index, bool is_a_sun)
{
	int max_index = (is_a_sun) ? (int)Suns.size() : (int)Starfield_bitmap_instances.size();

	//WMC - Commented out because it keeps happening, and I don't know what this means.
	//Assert( (index >= 0) && (index < max_index) );

	if ( (index < 0) || (index >= max_index) )
		return NULL;

	if (is_a_sun && (Suns[index].star_bitmap_index >= 0)) {
		return &Sun_bitmaps[Suns[index].star_bitmap_index];
	} else if (!is_a_sun && (Starfield_bitmap_instances[index].star_bitmap_index >= 0)) {
		return &Starfield_bitmaps[Starfield_bitmap_instances[index].star_bitmap_index];
	}

	return NULL;
}

bool stars_sun_has_glare(int index)
{
	starfield_bitmap *sb = stars_get_bitmap_entry(index, true);
	return (sb && sb->glare);
}

// set an instace to not render
void stars_mark_instance_unused(int index, bool is_a_sun)
{
	int max_index = (is_a_sun) ? (int)Suns.size() : (int)Starfield_bitmap_instances.size();

	Assert( (index >= 0) && (index < max_index) );

	if ( (index < 0) || (index >= max_index) )
		return;

	if (is_a_sun) {
		Suns[index].star_bitmap_index =  -1;
	} else {
		Starfield_bitmap_instances[index].star_bitmap_index = -1;
	}

	if ( !is_a_sun ) {
		delete [] Starfield_bitmap_instances[index].verts;
		Starfield_bitmap_instances[index].verts = NULL;
	}

	// The background changed so we need to invalidate the environment map
	stars_invalidate_environment_map();
}

// retrieves the name from starfield_bitmap for the instance index
// NOTE: it's unsafe to return NULL here so use <none> for invalid entries
const char *stars_get_name_from_instance(int index, bool is_a_sun)
{
	int max_index = (is_a_sun) ? (int)Suns.size() : (int)Starfield_bitmap_instances.size();

	Assert( (index >= 0) && (index < max_index) );

	if ( (index < 0) || (index >= max_index) )
		return NOX("<none>");

	if (is_a_sun && (Suns[index].star_bitmap_index >= 0)) {
		return Sun_bitmaps[Suns[index].star_bitmap_index].filename;
	} else if (!is_a_sun && (Starfield_bitmap_instances[index].star_bitmap_index >= 0)) {
		return Starfield_bitmaps[Starfield_bitmap_instances[index].star_bitmap_index].filename;
	}

	return NOX("<none>");
}

// WMC/Goober5000
void stars_set_nebula(bool activate, float range)
{
    The_mission.flags.set(Mission::Mission_Flags::Fullneb, activate);
	
    if (activate)
	{
		Toggle_text_alpha = TOGGLE_TEXT_NEBULA_ALPHA;
		HUD_contrast = 1;

		Neb2_render_mode = NEB2_RENDER_HTL;
		Neb2_awacs = range;
		if (Neb2_awacs < 0.1f)
			Neb2_awacs = 3000.0f;	// this is also the default in the background editor

		// this function is not currently called in FRED, but this would be needed for FRED support
		if (Fred_running)
		{
			Neb2_render_mode = NEB2_RENDER_POF;
			stars_set_background_model(BACKGROUND_MODEL_FILENAME, Neb2_texture_name);
			stars_set_background_orientation();
		}
	}
	else
	{
		Toggle_text_alpha = TOGGLE_TEXT_NORMAL_ALPHA;
		HUD_contrast = 0;

		Neb2_render_mode = NEB2_RENDER_NONE;
		Neb2_awacs = -1.0f;
	}

	// (DahBlount)
	// This needs to be done regardless of whether we're in nebula or not
	// Should ensure that we're actually loading the needed anims into BMPMan
	stars_load_debris(static_cast<int>(activate));

	// We need to reload the environment map now
	stars_invalidate_environment_map();
}

// retrieves the name from starfield_bitmap, really only used by FRED2
// NOTE: it is unsafe to return NULL here, but because that's bad anyway it really shouldn't happen, so we do return NULL.
const char *stars_get_name_FRED(int index, bool is_a_sun)
{
	if (!Fred_running)
		return NULL;

	int max_index = (is_a_sun) ? (int)Sun_bitmaps.size() : (int)Starfield_bitmaps.size();

	Assert( (index >= 0) && (index < max_index) );

	if ( (index < 0) || (index >= max_index) )
		return NULL;

	if (is_a_sun) {
		return Sun_bitmaps[index].filename;
	} else {
		return Starfield_bitmaps[index].filename;
	}
}

// modify an existing starfield bitmap instance, or add a new one if needed
void stars_modify_entry_FRED(int index, const char *name, starfield_list_entry *sbi_new, bool is_a_sun)
{
	if (!Fred_running)
		return;

	starfield_bitmap_instance sbi;
	int idx;
	int add_new = index > ((is_a_sun) ? (int)Sun_bitmaps.size() : (int)Starfield_bitmaps.size());

	Assert( index >= 0 );
	Assert( sbi_new != NULL );

    // copy information
    sbi.ang.p = sbi_new->ang.p;
	sbi.ang.b = sbi_new->ang.b;
	sbi.ang.h = sbi_new->ang.h;
	sbi.scale_x = sbi_new->scale_x;
	sbi.scale_y = sbi_new->scale_y;
	sbi.div_x = sbi_new->div_x;
	sbi.div_y = sbi_new->div_y;

	if (is_a_sun) {
		idx = stars_find_sun((char*)name);
	} else {
		idx = stars_find_bitmap((char*)name);
	}

	// this shouldn't ever happen from FRED since you select the name from a list of those available
	if (idx == -1)
		return;

	sbi.star_bitmap_index = idx;

	if (add_new) {
		if (is_a_sun) {
			Suns.push_back( sbi );
		} else {
			Starfield_bitmap_instances.push_back( sbi );
		}
	} else {
		if (is_a_sun) {
			Suns[index] = sbi;
		} else {
			Starfield_bitmap_instances[index] = sbi;
		}
	}

	if ( !is_a_sun ) {
		starfield_create_bitmap_buffer(index);
	}
}

// erase an instance, note that this is very slow so it should only be done in FRED
void stars_delete_entry_FRED(int index, bool is_a_sun)
{
	if (!Fred_running)
		return;

	int max_index = (is_a_sun) ? (int)Suns.size() : (int)Starfield_bitmap_instances.size();

	Assert( (index >= 0) && (index < max_index) );

	if ( (index < 0) || (index >= max_index) )
		return;

	if (is_a_sun) {
		Suns.erase( Suns.begin() + index );
	} else {
		Starfield_bitmap_instances.erase( Starfield_bitmap_instances.begin() + index );
	}
}

// Goober5000
void stars_add_blank_background(bool creating_in_fred)
{
	Backgrounds.emplace_back();

	// any background that is created will have correct angles, so be sure to set the flag
	if (creating_in_fred)
		Backgrounds.back().flags.set(Starfield::Background_Flags::Corrected_angles_in_mission_file);
}

// Goober5000
void stars_load_first_valid_background()
{
	int background_idx = stars_get_first_valid_background();
	stars_load_background(background_idx);
}

// Goober5000
int stars_get_first_valid_background()
{
	uint i, j;

	if (Backgrounds.empty())
		return -1;

	// scan every background except the last and return the first one that has all its suns and bitmaps present
	for (i = 0; i < Backgrounds.size() - 1; i++)
	{
		bool valid = true;
		background_t *background = &Backgrounds[i];

		for (j = 0; j < background->suns.size(); j++)
		{
			if (stars_find_sun(background->suns[j].filename) < 0)
			{
				mprintf(("Failed to load sun %s for background %d, falling back to background %d\n",
					background->suns[j].filename, i + 1, i + 2));
				valid = false;
				break;
			}
		}

		if (valid)
		{
			for (j = 0; j < background->bitmaps.size(); j++)
			{
				if (stars_find_bitmap(background->bitmaps[j].filename) < 0)
				{
					mprintf(("Failed to load bitmap %s for background %d, falling back to background %d\n",
						background->bitmaps[j].filename, i + 1, i + 2));
					valid = false;
					break;
				}
			}
		}

		if (valid)
			return i;
	}

	// didn't find a valid background yet, so return the last one
	return (int)Backgrounds.size() - 1;
}

// Goober5000
void stars_load_background(int background_idx)
{
	uint j;

	stars_clear_instances();
	Cur_background = background_idx;

	if (Cur_background >= 0)
	{
		background_t *background = &Backgrounds[Cur_background];

		int failed_suns = 0;
		for (j = 0; j < background->suns.size(); j++)
		{
			if ((stars_add_sun_entry(&background->suns[j]) < 0) && !Fred_running)
			{
				nprintf(("General", "Failed to add sun '%s' to the mission!", background->suns[j].filename));
				failed_suns++;
			}
		}
		if (failed_suns > 0)
			Warning(LOCATION, "Failed to add %d sun bitmaps to the mission!", failed_suns);

		int failed_stars = 0;
		for (j = 0; j < background->bitmaps.size(); j++)
		{
			if ((stars_add_bitmap_entry(&background->bitmaps[j]) < 0) && !Fred_running)
			{
				nprintf(("General", "Failed to add starfield bitmap '%s' to the mission!", background->bitmaps[j].filename));
				failed_stars++;
			}
		}
		if (failed_stars > 0)
			Warning(LOCATION, "Failed to add %d starfield bitmaps to the mission!", failed_stars);
	}
}

// Goober5000
void stars_copy_background(background_t *dest, background_t *src)
{
	dest->flags = src->flags;
	dest->suns.assign(src->suns.begin(), src->suns.end());
	dest->bitmaps.assign(src->bitmaps.begin(), src->bitmaps.end());
}

// Goober5000
void stars_swap_backgrounds(int idx1, int idx2)
{
	background_t temp;
	stars_copy_background(&temp, &Backgrounds[idx1]);
	stars_copy_background(&Backgrounds[idx1], &Backgrounds[idx2]);
	stars_copy_background(&Backgrounds[idx2], &temp);
}

// Goober5000
bool stars_background_empty(const background_t &bg)
{
	return (bg.suns.empty() && bg.bitmaps.empty());
}

// Goober5000
void stars_pack_backgrounds()
{
	size_t remove_count = 0;

	// remove all empty backgrounds, with a caveat:
	// in FRED, make sure we always have at least one background
	// (note: older code removed all blank backgrounds and re-added one if necessary; but that method caused flag changes to be lost)
	Backgrounds.erase(
		std::remove_if(Backgrounds.begin(), Backgrounds.end(), [&](const background_t& bg) {
			if (stars_background_empty(bg)) {
				if (Fred_running && ++remove_count == Backgrounds.size())
					return false;	// cancel the last removal if FRED is running and if the last removal would result in all backgrounds being removed (i.e. all were blank)
				return true;
			}
			return false;
		}), Backgrounds.end());
}

static void render_environment(int i, vec3d *eye_pos, matrix *new_orient, fov_t new_zoom)
{
	bm_set_render_target(gr_screen.envmap_render_target, i);

	gr_clear();

	g3_set_view_matrix( eye_pos, new_orient, new_zoom );

	gr_set_proj_matrix( new_zoom * PI_2, 1.0f, Min_draw_distance, Max_draw_distance);
	gr_set_view_matrix( &Eye_position, &Eye_matrix );

	if ( Game_subspace_effect ) {
		stars_draw(0, 0, 0, 1, 1);
	} else {
		stars_draw(0, 1, 1, 0, 1);
	}

	gr_end_view_matrix();
	gr_end_proj_matrix();
}

void stars_setup_environment_mapping(camid cid) {
	matrix new_orient = IDENTITY_MATRIX;

	extern fov_t View_zoom;
	fov_t old_zoom = View_zoom, new_zoom = 1.0f;//0.925f;

	if (gr_screen.mode == GR_STUB) {
		return;
	}

	if(!cid.isValid())
		return;

	vec3d cam_pos;
	matrix cam_orient;
	cid.getCamera()->get_info(&cam_pos, &cam_orient);

	bool renderEnv = true;

	// prefer the mission specified envmap over the static-generated envmap, but
	// the dynamic envmap should always get preference if in a subspace mission
	if (!Dynamic_environment && Mission_env_map >= 0) {
		ENVMAP = Mission_env_map;
		renderEnv = false;
	} else if (gr_screen.envmap_render_target < 0) {
		if (ENVMAP >= 0) {
			renderEnv = false;
		} else if (Mission_env_map >= 0) {
			ENVMAP = Mission_env_map;
		} else {
			ENVMAP = Default_env_map;
		}
		renderEnv = false;
	} else if (Env_cubemap_drawn) {
		// Nothing to do here anymore
		renderEnv = false;
	}

			/*
	 * Envmap matrix setup -- left-handed
	 * -------------------------------------------------
	 * Face --	Forward		Up		Right
	 * px		+X			+Y		-Z
	 * nx		-X			+Y		+Z
	 * py		+Y			-Z		+X
	 * ny		-Y			+Z		+X
	 * pz		+Z 			+Y		+X
	 * nz		-Z			+Y		-X
	 */
	// NOTE: OpenGL needs up/down reversed

	// Save the previous render target so we can reset it once we are done here
	auto previous_target = gr_screen.rendering_to_texture;
	// Encode above table into directions and values.
	// 0 = X, 1 = Y, 2 = Z
	int f_dir[6] = {0, 0, 1, 1, 2, 2};
	int u_dir[6] = {1, 1, 2, 2, 1, 1};
	int r_dir[6] = {2, 2, 0, 0, 0, 0};
	float f_val[6] = {1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f};
	float u_val[6] = {1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f};
	float r_val[6] = {-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f};

	if (renderEnv) {

		GR_DEBUG_SCOPE("Environment Mapping");
		TRACE_SCOPE(tracing::EnvironmentMapping);

		ENVMAP = gr_screen.envmap_render_target;

		for (int i = 0; i < 6; i++) {
			memset(&new_orient, 0, sizeof(matrix));
			new_orient.vec.fvec.a1d[f_dir[i]] = f_val[i];
			new_orient.vec.uvec.a1d[u_dir[i]] = u_val[i];
			new_orient.vec.rvec.a1d[r_dir[i]] = r_val[i];
			render_environment(i, &cam_pos, &new_orient, new_zoom);
		}

		// we're done, so now reset
		bm_set_render_target(previous_target);
		g3_set_view_matrix(&cam_pos, &cam_orient, old_zoom);
	}
	// Draw irr map if we've just updated the envmap 
	// or otherwise invalidated the irradiance map (i.e. custom/default envmap)
	if ((!Irr_cubemap_drawn || renderEnv) && (ENVMAP >= 0)) {
		// Generate irradiance map.
		if (gr_screen.irrmap_render_target < 0) {
			irradiance_map_gen();
			IRRMAP = gr_screen.irrmap_render_target;
		}
		gr_screen.gf_calculate_irrmap();
	}

	if ( !Dynamic_environment ) {
		Env_cubemap_drawn = true;
		Irr_cubemap_drawn = true;
	}
}
void stars_set_dynamic_environment(bool dynamic) {
	Dynamic_environment = dynamic;
	stars_invalidate_environment_map();
}
void stars_invalidate_environment_map() {
	// This will cause a redraw in the next frame
	Env_cubemap_drawn = false;
	Irr_cubemap_drawn = false;
}