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
// std
use std::cell::Cell;
use std::f32::consts::PI;
use std::sync::Arc;
// pbrt
use crate::blockqueue::BlockQueue;
use crate::core::camera::{Camera, CameraSample};
use crate::core::geometry::{
    nrm_abs_dot_vec3f, pnt2_inside_exclusivei, pnt3_offset_ray_origin, vec3_abs_dot_nrmf,
    vec3_dot_nrmf,
};
use crate::core::geometry::{
    Bounds2i, Bounds3f, Normal3f, Point2f, Point2i, Point3f, Ray, Vector2i, Vector3f,
};
use crate::core::interaction::{
    Interaction, InteractionCommon, MediumInteraction, SurfaceInteraction,
};
use crate::core::light::is_delta_light;
use crate::core::light::{Light, LightFlags, VisibilityTester};
use crate::core::lightdistrib::create_light_sample_distribution;
use crate::core::material::TransportMode;
use crate::core::medium::{HenyeyGreenstein, Medium, MediumInterface};
use crate::core::pbrt::{Float, Spectrum};
use crate::core::reflection::Bsdf;
use crate::core::reflection::BxdfType;
use crate::core::sampler::Sampler;
use crate::core::sampling::Distribution1D;
use crate::core::scene::Scene;

// see bdpt.h

#[derive(Default)]
pub struct EndpointInteraction<'a> {
    // Interaction Public Data
    pub common: InteractionCommon,
    // EndpointInteraction Public Data
    pub camera: Option<&'a Arc<Camera>>,
    pub light: Option<&'a Arc<Light>>,
}

impl<'a> EndpointInteraction<'a> {
    pub fn new(p: &Point3f, time: Float) -> Self {
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = *p;
        common.time = time;
        EndpointInteraction {
            common,
            ..Default::default()
        }
    }
    pub fn new_interaction_from_camera(it: &InteractionCommon, camera: &'a Arc<Camera>) -> Self {
        let mut ei: EndpointInteraction = EndpointInteraction::new(&it.p, it.time);
        {
            ei.common.p_error = it.p_error;
            ei.common.wo = it.wo;
            ei.common.n = it.n;
        }
        ei.camera = Some(camera);
        ei
    }
    pub fn new_camera(camera: &'a Arc<Camera>, ray: &Ray) -> Self {
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = ray.o;
        common.time = ray.time;
        let mut ei: EndpointInteraction = EndpointInteraction {
            common,
            camera: Some(camera),
            ..Default::default()
        };
        if let Some(ref medium_arc) = ray.medium {
            let inside: Option<Arc<Medium>> = Some(medium_arc.clone());
            let outside: Option<Arc<Medium>> = Some(medium_arc.clone());
            {
                ei.common.medium_interface = Some(Arc::new(MediumInterface::new(inside, outside)));
            }
        }
        ei
    }
    pub fn new_light(light: &'a Arc<Light>, ray: &Ray, nl: &Normal3f) -> Self {
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = ray.o;
        common.time = ray.time;
        let mut ei: EndpointInteraction = EndpointInteraction {
            common,
            light: Some(light),
            ..Default::default()
        };
        if let Some(ref medium_arc) = ray.medium {
            let inside: Option<Arc<Medium>> = Some(medium_arc.clone());
            let outside: Option<Arc<Medium>> = Some(medium_arc.clone());
            {
                ei.common.medium_interface = Some(Arc::new(MediumInterface::new(inside, outside)));
            }
        }
        {
            ei.common.n = *nl;
        }
        ei
    }
    pub fn new_interaction_from_light(it: &InteractionCommon, light: &'a Arc<Light>) -> Self {
        let mut ei: EndpointInteraction = EndpointInteraction::default();
        {
            ei.common.p = it.p;
            ei.common.time = it.time;
            ei.common.p_error = it.p_error;
            ei.common.wo = it.wo;
            ei.common.n = it.n;
            if let Some(ref medium_interface_arc) = it.medium_interface {
                ei.common.medium_interface = Some(medium_interface_arc.clone());
            }
        }
        ei.light = Some(light);
        ei
    }
    pub fn new_ray(ray: &Ray) -> Self {
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = ray.position(1.0 as Float);
        common.time = ray.time;
        let mut ei: EndpointInteraction = EndpointInteraction {
            common,
            ..Default::default()
        };
        {
            ei.common.n = Normal3f::from(-ray.d);
            if let Some(ref medium_arc) = ray.medium {
                let inside: Option<Arc<Medium>> = Some(medium_arc.clone());
                let outside: Option<Arc<Medium>> = Some(medium_arc.clone());
                ei.common.medium_interface = Some(Arc::new(MediumInterface::new(inside, outside)));
            }
        }
        ei
    }
    pub fn get_medium(&self, w: &Vector3f) -> Option<Arc<Medium>> {
        if vec3_dot_nrmf(w, &self.common.n) > 0.0 as Float {
            if let Some(ref medium_interface) = self.common.medium_interface {
                medium_interface.outside.clone()
            } else {
                None
            }
        } else if let Some(ref medium_interface) = self.common.medium_interface {
            medium_interface.inside.clone()
        } else {
            None
        }
    }
}

impl<'a> Interaction for EndpointInteraction<'a> {
    fn is_surface_interaction(&self) -> bool {
        self.common.n != Normal3f::default()
    }
    fn is_medium_interaction(&self) -> bool {
        !self.is_surface_interaction()
    }
    fn spawn_ray(&self, d: &Vector3f) -> Ray {
        let o: Point3f =
            pnt3_offset_ray_origin(&self.common.p, &self.common.p_error, &self.common.n, d);
        Ray {
            o,
            d: *d,
            t_max: Cell::new(std::f32::INFINITY),
            time: self.common.time,
            differential: None,
            medium: self.get_medium(d),
        }
    }
    fn get_common(&self) -> &InteractionCommon {
        &self.common
    }
    fn get_p(&self) -> &Point3f {
        &self.common.p
    }
    fn get_time(&self) -> Float {
        self.common.time
    }
    fn get_p_error(&self) -> &Vector3f {
        &self.common.p_error
    }
    fn get_wo(&self) -> &Vector3f {
        &self.common.wo
    }
    fn get_n(&self) -> &Normal3f {
        &self.common.n
    }
    fn get_medium_interface(&self) -> Option<Arc<MediumInterface>> {
        if let Some(ref medium_interface) = self.common.medium_interface {
            Some(medium_interface.clone())
        } else {
            None
        }
    }
    fn get_bsdf(&self) -> Option<&Bsdf> {
        None
    }
    fn get_shading_n(&self) -> Option<&Normal3f> {
        None
    }
    fn get_phase(&self) -> Option<Arc<HenyeyGreenstein>> {
        None
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum VertexType {
    Camera,
    Light,
    Surface,
    Medium,
}

pub struct Vertex<'a> {
    vertex_type: VertexType,
    beta: Spectrum,
    ei: Option<EndpointInteraction<'a>>,
    mi: Option<MediumInteraction>,
    si: Option<SurfaceInteraction<'a>>,
    delta: bool,
    pdf_fwd: Float,
    pdf_rev: Float,
}

impl<'a> Vertex<'a> {
    pub fn new(vertex_type: VertexType, ei: EndpointInteraction<'a>, beta: &Spectrum) -> Self {
        Vertex {
            vertex_type,
            beta: *beta,
            ei: Some(ei),
            mi: None,
            si: None,
            delta: false,
            pdf_fwd: 0.0 as Float,
            pdf_rev: 0.0 as Float,
        }
    }
    pub fn create_camera_from_ray(
        camera: &'a Arc<Camera>,
        ray: &Ray,
        beta: &Spectrum,
    ) -> Vertex<'a> {
        Vertex::new(
            VertexType::Camera,
            EndpointInteraction::new_camera(camera, ray),
            beta,
        )
    }
    pub fn create_camera_from_interaction(
        camera: &'a Arc<Camera>,
        it: &InteractionCommon,
        beta: &Spectrum,
    ) -> Vertex<'a> {
        Vertex::new(
            VertexType::Camera,
            EndpointInteraction::new_interaction_from_camera(it, camera),
            beta,
        )
    }
    pub fn create_surface_interaction(
        si: SurfaceInteraction<'a>,
        beta: &Spectrum,
        pdf: Float,
        prev: &Vertex,
    ) -> Vertex<'a> {
        let mut v: Vertex = Vertex {
            vertex_type: VertexType::Surface,
            beta: *beta,
            ei: None,
            mi: None,
            si: Some(si),
            delta: false,
            pdf_fwd: 0.0 as Float,
            pdf_rev: 0.0 as Float,
        };
        v.pdf_fwd = prev.convert_density(pdf, &v);
        v
    }
    pub fn create_medium_interaction(
        mi: MediumInteraction,
        beta: &Spectrum,
        pdf: Float,
        prev: &Vertex,
    ) -> Vertex<'a> {
        let mut v: Vertex = Vertex {
            vertex_type: VertexType::Medium,
            beta: *beta,
            ei: None,
            mi: Some(mi),
            si: None,
            delta: false,
            pdf_fwd: 0.0 as Float,
            pdf_rev: 0.0 as Float,
        };
        v.pdf_fwd = prev.convert_density(pdf, &v);
        v
    }
    pub fn create_light_interaction(
        ei: EndpointInteraction<'a>,
        beta: &Spectrum,
        pdf: Float,
    ) -> Vertex<'a> {
        let mut v: Vertex = Vertex::new(VertexType::Light, ei, beta);
        v.pdf_fwd = pdf;
        v
    }
    pub fn create_light(
        light: &'a Arc<Light>,
        ray: &Ray,
        nl: &Normal3f,
        le: &Spectrum,
        pdf: Float,
    ) -> Vertex<'a> {
        let mut v = Vertex::new(
            VertexType::Light,
            EndpointInteraction::new_light(light, ray, nl),
            le,
        );
        v.pdf_fwd = pdf;
        v
    }
    pub fn p(&self) -> Point3f {
        match self.vertex_type {
            VertexType::Medium => {
                if let Some(ref mi) = self.mi {
                    mi.common.p
                } else {
                    Point3f::default()
                }
            }
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    si.common.p
                } else {
                    Point3f::default()
                }
            }
            _ => {
                if let Some(ref ei) = self.ei {
                    ei.common.p
                } else {
                    Point3f::default()
                }
            }
        }
    }
    pub fn time(&self) -> Float {
        match self.vertex_type {
            VertexType::Medium => {
                if let Some(ref mi) = self.mi {
                    mi.common.time
                } else {
                    Float::default()
                }
            }
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    si.common.time
                } else {
                    Float::default()
                }
            }
            _ => {
                if let Some(ref ei) = self.ei {
                    ei.common.time
                } else {
                    Float::default()
                }
            }
        }
    }
    pub fn ng(&self) -> Normal3f {
        match self.vertex_type {
            VertexType::Medium => {
                if let Some(ref mi) = self.mi {
                    mi.common.n
                } else {
                    Normal3f::default()
                }
            }
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    si.common.n
                } else {
                    Normal3f::default()
                }
            }
            _ => {
                if let Some(ref ei) = self.ei {
                    ei.common.n
                } else {
                    Normal3f::default()
                }
            }
        }
    }
    pub fn ns(&self) -> Normal3f {
        match self.vertex_type {
            VertexType::Medium => {
                if let Some(ref mi) = self.mi {
                    mi.common.n
                } else {
                    Normal3f::default()
                }
            }
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    si.shading.n
                } else {
                    Normal3f::default()
                }
            }
            VertexType::Light => {
                if let Some(ref ei) = self.ei {
                    ei.common.n
                } else {
                    Normal3f::default()
                }
            }
            _ => Normal3f::default(),
        }
    }
    pub fn is_on_surface(&self) -> bool {
        self.ng() != Normal3f::default()
    }
    pub fn f(&self, next: &Vertex, mode: TransportMode) -> Spectrum {
        let mut wi: Vector3f = next.p() - self.p();
        if wi.length_squared() == 0.0 as Float {
            return Spectrum::default();
        }
        wi = wi.normalize();
        match self.vertex_type {
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    if let Some(ref bsdf) = si.bsdf {
                        let bsdf_flags: u8 = BxdfType::BsdfAll as u8;
                        bsdf.f(&si.common.wo, &wi, bsdf_flags)
                            * correct_shading_normal(si, &si.common.wo, &wi, mode)
                    } else {
                        Spectrum::default()
                    }
                } else {
                    Spectrum::default()
                }
            }
            VertexType::Medium => {
                if let Some(ref mi) = self.mi {
                    if let Some(phase) = mi.get_phase() {
                        Spectrum::new(phase.p(&mi.common.wo, &wi))
                    } else {
                        Spectrum::default()
                    }
                } else {
                    Spectrum::default()
                }
            }
            _ => Spectrum::default(),
        }
    }
    pub fn is_connectible(&self) -> bool {
        match self.vertex_type {
            VertexType::Medium => true,
            VertexType::Light => {
                if let Some(ref ei) = self.ei {
                    if let Some(ref light) = ei.light {
                        let check: u8 = light.get_flags() & LightFlags::DeltaDirection as u8;
                        check == 0 as u8
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            VertexType::Camera => true,
            VertexType::Surface => {
                if let Some(ref si) = self.si {
                    if let Some(ref bsdf) = si.bsdf {
                        let bsdf_flags: u8 = BxdfType::BsdfDiffuse as u8
                            | BxdfType::BsdfGlossy as u8
                            | BxdfType::BsdfReflection as u8
                            | BxdfType::BsdfTransmission as u8;
                        bsdf.num_components(bsdf_flags) > 0
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
        }
    }
    pub fn is_light(&self) -> bool {
        if self.vertex_type == VertexType::Light {
            return true;
        } else if self.vertex_type == VertexType::Surface {
            if let Some(ref si) = self.si {
                if let Some(primitive_raw) = si.primitive {
                    let primitive = unsafe { &*primitive_raw };
                    if let Some(_area_light) = primitive.get_area_light() {
                        return true;
                    }
                }
            }
        }
        false
    }
    pub fn is_delta_light(&self) -> bool {
        if self.vertex_type != VertexType::Light {
            return false;
        } else if let Some(ref ei) = self.ei {
            if let Some(ref light) = ei.light {
                let check: u8 = light.get_flags();
                return is_delta_light(check);
            }
        }
        false
    }
    pub fn is_infinite_light(&self) -> bool {
        if self.vertex_type != VertexType::Light {
            return false;
        } else if let Some(ref ei) = self.ei {
            if let Some(ref light) = ei.light {
                let check: u8 = light.get_flags() & LightFlags::Infinite as u8;
                if check == LightFlags::Infinite as u8 {
                    return true;
                }
                let check: u8 = light.get_flags() & LightFlags::DeltaDirection as u8;
                if check == LightFlags::DeltaDirection as u8 {
                    return true;
                }
            } else {
                // !ei.light
                return true;
            }
        }
        false
    }
    pub fn le(&self, scene: &Scene, v: &Vertex) -> Spectrum {
        if !self.is_light() {
            return Spectrum::default();
        }
        let mut w: Vector3f = v.p() - self.p();
        if w.length_squared() == 0.0 as Float {
            return Spectrum::default();
        }
        w = w.normalize();
        if self.is_infinite_light() {
            // return emitted radiance for infinite light sources
            let mut le: Spectrum = Spectrum::default();
            for light in &scene.infinite_lights {
                let mut ray: Ray = Ray {
                    o: self.p(),
                    d: -w,
                    t_max: Cell::new(Float::default()),
                    time: Float::default(),
                    differential: None,
                    medium: None,
                };
                le += light.le(&mut ray);
            }
            return le;
        } else if let Some(ref si) = self.si {
            if let Some(primitive_raw) = si.primitive {
                let primitive = unsafe { &*primitive_raw };
                if let Some(light) = primitive.get_area_light() {
                    let mut iref: InteractionCommon = InteractionCommon::default();
                    iref.p = si.common.p;
                    iref.time = si.common.time;
                    iref.p_error = si.common.p_error;
                    iref.wo = si.common.wo;
                    iref.n = si.common.n;
                    return light.l(&iref, &w);
                }
            }
        }
        Spectrum::default()
    }
    pub fn convert_density(&self, pdf: Float, next: &Vertex) -> Float {
        // return solid angle density if _next_ is an infinite area light
        if next.is_infinite_light() {
            return pdf;
        }
        let w: Vector3f = next.p() - self.p();
        if w.length_squared() == 0.0 as Float {
            return 0.0 as Float;
        }
        let inv_dist_2: Float = 1.0 as Float / w.length_squared();
        let mut pdf: Float = pdf; // shadow
        if next.is_on_surface() {
            pdf *= nrm_abs_dot_vec3f(&next.ng(), &(w * inv_dist_2.sqrt()));
        }
        pdf * inv_dist_2
    }
    pub fn pdf(&self, scene: &Scene, prev: Option<&Vertex>, next: &Vertex) -> Float {
        // if (type == VertexType::Light) return PdfLight(scene, next);
        if self.vertex_type == VertexType::Light {
            return self.pdf_light(scene, next);
        }
        // compute directions to preceding and next vertex
        let mut wn: Vector3f = next.p() - self.p();
        if wn.length_squared() == 0.0 as Float {
            return 0.0 as Float;
        }
        wn = wn.normalize();
        let mut wp: Vector3f = Vector3f::default();
        if let Some(prev) = prev {
            wp = prev.p() - self.p();
            if wp.length_squared() == 0.0 as Float {
                return 0.0 as Float;
            }
            wp = wp.normalize();
        } else {
            assert!(
                self.vertex_type == VertexType::Camera,
                "VertexType::Camera expected, VertexType::{:?} found",
                self.vertex_type
            );
        }
        // compute directional density depending on the vertex types
        let mut pdf_flt: Float = 0.0;
        let mut _unused: Float = 0.0;
        if self.vertex_type == VertexType::Camera {
            if let Some(ref ei) = self.ei {
                if let Some(ref camera) = ei.camera {
                    let (_unused, pdf_flt_local) = camera.pdf_we(&ei.spawn_ray(&wn));
                    pdf_flt = pdf_flt_local;
                }
            }
        } else if self.vertex_type == VertexType::Surface {
            if let Some(ref si) = self.si {
                if let Some(ref bsdf) = si.bsdf {
                    let bsdf_flags: u8 = BxdfType::BsdfAll as u8;
                    pdf_flt = bsdf.pdf(&wp, &wn, bsdf_flags);
                }
            }
        } else if self.vertex_type == VertexType::Medium {
            if let Some(ref mi) = self.mi {
                if let Some(ref phase) = mi.phase {
                    pdf_flt = phase.p(&wp, &wn);
                }
            }
        }
        // return probability per unit area at vertex _next_
        self.convert_density(pdf_flt, next)
    }
    pub fn pdf_light(&self, scene: &Scene, v: &Vertex) -> Float {
        let mut w: Vector3f = v.p() - self.p();
        let inv_dist2: Float = 1.0 as Float / w.length_squared();
        w *= inv_dist2.sqrt();
        let mut pdf: Float = 0.0;
        if self.is_infinite_light() {
            // compute planar sampling density for infinite light sources
            let mut world_center: Point3f = Point3f::default();
            let mut world_radius: Float = 0.0;
            Bounds3f::bounding_sphere(&scene.world_bound(), &mut world_center, &mut world_radius);
            pdf = 1.0 as Float / (PI * world_radius * world_radius);
        } else {
            assert!(self.is_light());
            if self.vertex_type == VertexType::Light {
                if let Some(ref ei) = self.ei {
                    if let Some(ref light_ref) = ei.light {
                        // compute sampling density for non-infinite
                        // light sources
                        let mut pdf_pos: Float = 0.0;
                        let mut pdf_dir: Float = 0.0;
                        light_ref.pdf_le(
                            &Ray {
                                o: self.p(),
                                d: w,
                                t_max: Cell::new(std::f32::INFINITY),
                                time: self.time(),
                                differential: None,
                                medium: None,
                            },
                            &self.ng(),
                            &mut pdf_pos,
                            &mut pdf_dir,
                        );
                        pdf = pdf_dir * inv_dist2;
                    }
                }
            } else if let Some(ref si) = self.si {
                if let Some(primitive_raw) = si.primitive {
                    let primitive = unsafe { &*primitive_raw };
                    if let Some(area_light) = primitive.get_area_light() {
                        // compute sampling density for
                        // non-infinite light sources
                        let mut pdf_pos: Float = 0.0;
                        let mut pdf_dir: Float = 0.0;
                        area_light.pdf_le(
                            &Ray {
                                o: self.p(),
                                d: w,
                                t_max: Cell::new(std::f32::INFINITY),
                                time: self.time(),
                                differential: None,
                                medium: None,
                            },
                            &self.ng(),
                            &mut pdf_pos,
                            &mut pdf_dir,
                        );
                        pdf = pdf_dir * inv_dist2;
                    }
                }
            }
        }
        if v.is_on_surface() {
            pdf *= nrm_abs_dot_vec3f(&v.ng(), &w);
        }
        pdf
    }
    pub fn pdf_light_origin(
        &self,
        scene: &Scene,
        v: &Vertex,
        light_distr: Arc<Distribution1D>,
    ) -> Float {
        let mut w: Vector3f = v.p() - self.p();
        if w.length_squared() == 0.0 as Float {
            return 0.0 as Float;
        }
        w = w.normalize();
        if self.is_infinite_light() {
            // return solid angle density for infinite light sources
            return infinite_light_density(scene, light_distr, &w);
        } else {
            // return solid angle density for non-infinite light sources
            //         Float pdf_pos, pdf_dir, pdf_choice = 0;
            let mut pdf_pos: Float = 0.0;
            let mut pdf_dir: Float = 0.0;
            let mut pdf_choice: Float = 0.0;
            // get pointer _light_ to the light source at the vertex
            assert!(self.is_light());
            if self.vertex_type == VertexType::Light {
                // a real light source (not geometry emitting light)
                if let Some(ref ei) = self.ei {
                    if let Some(ref light_ref) = ei.light {
                        // find light in light vector
                        for i in 0..scene.lights.len() {
                            let light = &scene.lights[i];
                            // use ** (alloc::arc::Arc<Light> **)
                            let pr = &**light_ref as *const _ as *const usize;
                            let pl = &*light as *const _ as *const usize;
                            if pr == pl {
                                // compute the discrete probability of
                                // sampling _light_, _pdf_choice_
                                pdf_choice = light_distr.discrete_pdf(i);
                                light.pdf_le(
                                    &Ray {
                                        o: self.p(),
                                        d: w,
                                        t_max: Cell::new(std::f32::INFINITY),
                                        time: self.time(),
                                        differential: None,
                                        medium: None,
                                    },
                                    &self.ng(),
                                    &mut pdf_pos,
                                    &mut pdf_dir,
                                );
                                break;
                            }
                        }
                        return pdf_pos * pdf_choice;
                    }
                }
            } else {
                // area light from primitive
                if let Some(ref si) = self.si {
                    if let Some(primitive_raw) = si.primitive {
                        let primitive = unsafe { &*primitive_raw };
                        if let Some(area_light) = primitive.get_area_light() {
                            // find area light in light vector
                            for i in 0..scene.lights.len() {
                                let light = &scene.lights[i];
                                let pa = &*area_light as *const _ as *const usize;
                                let pl = &**light as *const _ as *const usize;
                                if pa == pl {
                                    // compute the discrete
                                    // probability of sampling
                                    // _light_, _pdf_choice_
                                    pdf_choice = light_distr.discrete_pdf(i);
                                    light.pdf_le(
                                        &Ray {
                                            o: self.p(),
                                            d: w,
                                            t_max: Cell::new(std::f32::INFINITY),
                                            time: self.time(),
                                            differential: None,
                                            medium: None,
                                        },
                                        &self.ng(),
                                        &mut pdf_pos,
                                        &mut pdf_dir,
                                    );
                                    break;
                                }
                            }
                            return pdf_pos * pdf_choice;
                        }
                    }
                }
            }
        }
        0.0 as Float
    }
}

/// Bidirectional Path Tracing (Global Illumination)
pub struct BDPTIntegrator {
    pub camera: Arc<Camera>,
    pub sampler: Box<Sampler>,
    pub pixel_bounds: Bounds2i,
    // see bdpt.h
    pub max_depth: u32,
    // visualize_strategies: bool,
    // visualize_weights: bool,
    pub light_sample_strategy: String, // "power"
}

impl BDPTIntegrator {
    pub fn new(
        camera: Arc<Camera>,
        sampler: Box<Sampler>,
        pixel_bounds: Bounds2i,
        max_depth: u32,
        // visualize_strategies: bool,
        // visualize_weights: bool,
        light_sample_strategy: String,
    ) -> Self {
        BDPTIntegrator {
            camera,
            sampler,
            pixel_bounds,
            max_depth,
            // visualize_strategies,
            // visualize_weights,
            light_sample_strategy,
        }
    }
    pub fn get_light_sample_strategy(&self) -> String {
        self.light_sample_strategy.clone()
    }
    pub fn render(&self, scene: &Scene, num_threads: u8) {
        // TODO
        // Compute a reverse mapping from light pointers to offsets into
        // the scene lights vector (and, equivalently, offsets into
        // lightDistr). Added after book text was finalized; this is
        // critical to reasonable performance with 100s+ of light sources.
        // let mut light_to_index = HashMap::new();
        // for li in 0..scene.lights.len() {
        //     let ref light = scene.lights[li];
        //     light_to_index.insert(light, li);
        // }
        // partition the image into tiles
        let film = self.get_camera().get_film();
        let sample_bounds: Bounds2i = film.get_sample_bounds();
        let sample_extent: Vector2i = sample_bounds.diagonal();
        let tile_size: i32 = 16;
        let n_x_tiles: i32 = (sample_extent.x + tile_size - 1) / tile_size;
        let n_y_tiles: i32 = (sample_extent.y + tile_size - 1) / tile_size;
        // TODO: ProgressReporter reporter(nXTiles * nYTiles, "Rendering");
        // TODO: Allocate buffers for debug visualization
        // ...
        // render and write the output image to disk
        if !scene.lights.is_empty() {
            let samples_per_pixel: i64 = self.sampler.get_samples_per_pixel();
            let num_cores = if num_threads == 0_u8 {
                num_cpus::get()
            } else {
                num_threads as usize
            };
            println!("Rendering with {:?} thread(s) ...", num_cores);
            {
                let block_queue = BlockQueue::new(
                    (
                        (n_x_tiles * tile_size) as u32,
                        (n_y_tiles * tile_size) as u32,
                    ),
                    (tile_size as u32, tile_size as u32),
                    (0, 0),
                );
                let bq = &block_queue;
                let integrator = &self;
                let sampler = &self.get_sampler();
                let camera = &self.get_camera();
                let film = &film;
                // let pixel_bounds = integrator.get_pixel_bounds().clone();
                crossbeam::scope(|scope| {
                    let (pixel_tx, pixel_rx) = crossbeam_channel::bounded(num_cores);
                    // spawn worker threads
                    for _ in 0..num_cores {
                        let pixel_tx = pixel_tx.clone();
                        scope.spawn(move |_| {
                            while let Some((x, y)) = bq.next() {
                                let tile: Point2i = Point2i {
                                    x: x as i32,
                                    y: y as i32,
                                };
                                let seed: i32 = tile.y * n_x_tiles + tile.x;
                                let mut tile_sampler: Box<Sampler> =
                                    sampler.clone_with_seed(seed as u64);
                                let x0: i32 = sample_bounds.p_min.x + tile.x * tile_size;
                                let x1: i32 = std::cmp::min(x0 + tile_size, sample_bounds.p_max.x);
                                let y0: i32 = sample_bounds.p_min.y + tile.y * tile_size;
                                let y1: i32 = std::cmp::min(y0 + tile_size, sample_bounds.p_max.y);
                                let tile_bounds: Bounds2i = Bounds2i::new(
                                    Point2i { x: x0, y: y0 },
                                    Point2i { x: x1, y: y1 },
                                );
                                // println!("Starting image tile {:?}", tile_bounds);
                                let mut film_tile = film.get_film_tile(&tile_bounds);
                                for p_pixel in &tile_bounds {
                                    tile_sampler.start_pixel(p_pixel);
                                    if !pnt2_inside_exclusivei(p_pixel, &integrator.pixel_bounds) {
                                        continue;
                                    }
                                    let mut done: bool = false;
                                    while !done {
                                        // Get a distribution for sampling
                                        // the light at the start of the
                                        // light subpath. Because the
                                        // light path follows multiple
                                        // bounces, basing the sampling
                                        // distribution on any of the
                                        // vertices of the camera path is
                                        // unlikely to be a good
                                        // strategy. We use the
                                        // PowerLightDistribution by
                                        // default here, which doesn't use
                                        // the point passed to it. Now
                                        // trace the light subpath
                                        if let Some(light_distribution) =
                                            create_light_sample_distribution(
                                                integrator.get_light_sample_strategy(),
                                                scene,
                                            )
                                        {
                                            // generate a single sample using BDPT
                                            let p_film: Point2f = Point2f {
                                                x: p_pixel.x as Float,
                                                y: p_pixel.y as Float,
                                            } + tile_sampler.get_2d();
                                            // trace the camera subpath
                                            let mut camera_vertices: Vec<Vertex> =
                                                Vec::with_capacity(
                                                    (integrator.max_depth + 2) as usize,
                                                );
                                            let n_camera;
                                            let p;
                                            let time;
                                            {
                                                let (n_camera_new, p_new, time_new) =
                                                    generate_camera_subpath(
                                                        scene,
                                                        &mut tile_sampler,
                                                        integrator.max_depth + 2,
                                                        camera,
                                                        p_film,
                                                        &mut camera_vertices,
                                                    );
                                                n_camera = n_camera_new;
                                                p = p_new;
                                                time = time_new;
                                            }
                                            let light_distr: Arc<Distribution1D> =
                                                light_distribution.lookup(&p);
                                            let mut light_vertices: Vec<Vertex> =
                                                Vec::with_capacity(
                                                    (integrator.max_depth + 1) as usize,
                                                );
                                            let n_light;
                                            {
                                                n_light = generate_light_subpath(
                                                    scene,
                                                    &mut tile_sampler,
                                                    integrator.max_depth + 1,
                                                    time,
                                                    light_distr.clone(),
                                                    // light_to_index,
                                                    &mut light_vertices,
                                                );
                                            }
                                            // Execute all BDPT connection strategies
                                            let mut l: Spectrum = Spectrum::new(0.0 as Float);
                                            // println!("n_camera = {:?}", n_camera);
                                            // println!("n_light = {:?}", n_light);
                                            for t in 1..=n_camera {
                                                for s in 0..=n_light {
                                                    // int depth = t + s - 2;
                                                    let depth: isize = (t + s) as isize - 2;
                                                    if (s == 1 && t == 1)
                                                        || depth < 0
                                                        || depth > integrator.max_depth as isize
                                                    {
                                                        continue;
                                                    }
                                                    // execute the $(s, t)$ connection strategy and update _L_
                                                    let mut p_film_new: Point2f = Point2f {
                                                        x: p_film.x,
                                                        y: p_film.y,
                                                    };
                                                    let mut mis_weight: Option<Float> =
                                                        Some(0.0 as Float);
                                                    let lpath: Spectrum = connect_bdpt(
                                                        scene,
                                                        &light_vertices,
                                                        &camera_vertices,
                                                        s,
                                                        t,
                                                        light_distr.clone(),
                                                        camera,
                                                        &mut tile_sampler,
                                                        &mut p_film_new,
                                                        mis_weight.as_mut(),
                                                    );
                                                    // if let Some(mis_weight_flt) = mis_weight {
                                                    //     println!("Connect bdpt s: {:?}, t: {:?}, lpath: {:?}, mis_weight: {:?}",
                                                    //              s, t, lpath, mis_weight_flt);
                                                    // }
                                                    // if (visualizeStrategies || visualizeWeights) {
                                                    //     Spectrum value;
                                                    //     if (visualizeStrategies)
                                                    //         value =
                                                    //             mis_weight == 0 ? 0 : lpath / mis_weight;
                                                    //     if (visualizeWeights) value = lpath;
                                                    //     weightFilms[BufferIndex(s, t)]->AddSplat(
                                                    //         pFilmNew, value);
                                                    // }
                                                    if t != 1 {
                                                        l += lpath;
                                                    } else if !lpath.is_black() {
                                                        film.add_splat(p_film_new, &lpath);
                                                    }
                                                }
                                            }
                                            // println!(
                                            //     "Add film sample pFilm: {:?}, L: {:?}, (y: {:?})",
                                            //     p_film,
                                            //     l,
                                            //     l.y()
                                            // );
                                            film_tile.add_sample(p_film, &mut l, 1.0 as Float);
                                            done = !tile_sampler.start_next_sample();
                                        }
                                    }
                                }
                                // send the tile through the channel to main thread
                                pixel_tx
                                    .send(film_tile)
                                    .unwrap_or_else(|_| panic!("Failed to send tile"));
                            }
                        });
                    }
                    // spawn thread to collect pixels and render image to file
                    scope.spawn(move |_| {
                        for _ in pbr::PbIter::new(0..bq.len()) {
                            let film_tile = pixel_rx.recv().unwrap();
                            // merge image tile into _Film_
                            film.merge_film_tile(&film_tile);
                        }
                    });
                })
                .unwrap();
            }
            film.write_image(1.0 as Float / samples_per_pixel as Float);
            // TODO: Write buffers for debug visualization
        }
    }
    pub fn get_camera(&self) -> Arc<Camera> {
        self.camera.clone()
    }
    pub fn get_sampler(&self) -> &Sampler {
        &self.sampler
    }
}

// BDPT Utility Functions

pub fn correct_shading_normal(
    isect: &SurfaceInteraction,
    wo: &Vector3f,
    &wi: &Vector3f,
    mode: TransportMode,
) -> Float {
    if mode == TransportMode::Importance {
        let num: Float =
            vec3_abs_dot_nrmf(&wo, &isect.shading.n) * vec3_abs_dot_nrmf(&wi, &isect.common.n);
        let denom: Float =
            vec3_abs_dot_nrmf(&wo, &isect.common.n) * vec3_abs_dot_nrmf(&wi, &isect.shading.n);
        // wi is occasionally perpendicular to isect.shading.n; this
        // is fine, but we don't want to return an infinite or NaN
        // value in that case.
        if denom == 0.0 as Float {
            return 0.0 as Float;
        }
        num / denom
    } else {
        1.0 as Float
    }
}

pub fn generate_camera_subpath<'a>(
    scene: &'a Scene,
    sampler: &mut Sampler,
    max_depth: u32,
    camera: &'a Arc<Camera>,
    p_film: Point2f,
    path: &mut Vec<Vertex<'a>>,
) -> (usize, Point3f, Float) {
    if max_depth == 0 {
        return (0_usize, Point3f::default(), Float::default());
    }
    // TODO: ProfilePhase _(Prof::BDPTGenerateSubpath);
    // sample initial ray for camera subpath
    let mut camera_sample: CameraSample = CameraSample::default();
    camera_sample.p_film = p_film;
    camera_sample.time = sampler.get_1d();
    camera_sample.p_lens = sampler.get_2d();
    let mut ray: Ray = Ray::default();
    let mut beta: Spectrum =
        Spectrum::new(camera.generate_ray_differential(&camera_sample, &mut ray));
    ray.scale_differentials(1.0 as Float / (sampler.get_samples_per_pixel() as Float).sqrt());
    // generate first vertex on camera subpath and start random walk
    let vertex: Vertex = Vertex::create_camera_from_ray(camera, &ray, &beta);
    // get extra info
    let p: Point3f = vertex.p();
    let time: Float = vertex.time();
    // store vertex
    path.push(vertex);
    let (_pdf_pos, pdf_dir) = camera.pdf_we(&ray);
    (
        random_walk(
            scene,
            &ray,
            sampler,
            &mut beta,
            pdf_dir,
            max_depth - 1_u32,
            TransportMode::Radiance,
            path,
        ) + 1_usize,
        p,
        time,
    )
}

pub fn generate_light_subpath<'a>(
    scene: &'a Scene,
    sampler: &mut Sampler,
    max_depth: u32,
    time: Float,
    light_distr: Arc<Distribution1D>,
    // TODO: light_to_index
    path: &mut Vec<Vertex<'a>>,
) -> usize {
    let mut n_vertices: usize = 0_usize;
    if max_depth == 0_u32 {
        return 0_usize;
    }
    // TODO: ProfilePhase _(Prof::BDPTGenerateSubpath);
    // sample initial ray for light subpath
    let mut light_pdf: Option<Float> = Some(0.0 as Float);
    let light_num: usize = light_distr.sample_discrete(sampler.get_1d(), light_pdf.as_mut());
    let light = &scene.lights[light_num];
    let mut ray: Ray = Ray::default();
    let mut n_light: Normal3f = Normal3f::default();
    let mut pdf_pos: Float = 0.0 as Float;
    let mut pdf_dir: Float = 0.0 as Float;
    let u2: Point2f = sampler.get_2d();
    let u1: Point2f = sampler.get_2d();
    let le: Spectrum = light.sample_le(
        u1,
        u2,
        time,
        &mut ray,
        &mut n_light,
        &mut pdf_pos,
        &mut pdf_dir,
    );
    if pdf_pos == 0.0 as Float || pdf_dir == 0.0 as Float || le.is_black() {
        return 0_usize;
    }
    if let Some(light_pdf) = light_pdf {
        // generate first vertex on light subpath and start random walk
        let vertex: Vertex = Vertex::create_light(light, &ray, &n_light, &le, pdf_pos * light_pdf);
        let is_infinite_light: bool = vertex.is_infinite_light();
        path.push(vertex);
        let mut beta: Spectrum =
            le * nrm_abs_dot_vec3f(&n_light, &ray.d) / (light_pdf * pdf_pos * pdf_dir);
        // println!(
        //     "Starting light subpath. Ray: {:?}, Le {:?}, beta {:?}, pdf_pos {:?}, pdf_dir {:?}",
        //     ray, le, beta, pdf_pos, pdf_dir
        // );

        // set spatial density of _path[1]_ for infinite area
        // light is done in random_walk !!!
        n_vertices = random_walk(
            scene,
            &ray,
            sampler,
            &mut beta,
            pdf_dir,
            max_depth - 1,
            TransportMode::Importance,
            path,
        );
        // correct subpath sampling densities for infinite area lights
        if is_infinite_light {
            // set spatial density of _path[1]_ for infinite area light
            if n_vertices > 0 {
                path[1].pdf_fwd = pdf_pos;
                if path[1].is_on_surface() {
                    path[1].pdf_fwd *= vec3_abs_dot_nrmf(&ray.d, &path[1].ng());
                }
            }
            // set spatial density of _path[0]_ for infinite area light
            path[0].pdf_fwd = infinite_light_density(scene, light_distr, &ray.d);
        }
    }
    n_vertices + 1
}

pub fn random_walk<'a>(
    scene: &'a Scene,
    ray: &Ray,
    sampler: &mut Sampler,
    beta: &mut Spectrum,
    pdf: Float,
    max_depth: u32,
    mode: TransportMode,
    path: &mut Vec<Vertex<'a>>,
) -> usize {
    // create a copy of the ray which can be mutated
    let mut ray: Ray = ray.clone();
    let mut bounces: usize = 0_usize;
    if max_depth == 0_u32 {
        return bounces;
    }
    // declare variables for forward and reverse probability densities
    let mut pdf_fwd: Float = pdf;
    let mut pdf_rev: Float = 0.0;
    loop {
        // attempt to create the next subpath vertex in _path_
        // println!(
        //     "Random walk. Bounces {:?}, beta {:?}, pdf_fwd {:?}, pdf_rev {:?}",
        //     bounces, beta, pdf_fwd, pdf_rev
        // );
        let mut mi_opt: Option<MediumInteraction> = None;
        // trace a ray and sample the medium, if any
        let found_intersection: bool;
        let mut isect: SurfaceInteraction = SurfaceInteraction::default();
        if scene.intersect(&mut ray, &mut isect) {
            found_intersection = true;
        } else {
            found_intersection = false;
        }
        if let Some(ref medium) = ray.medium {
            let (spectrum, option) = medium.sample(&ray, sampler);
            *beta *= spectrum;
            if let Some(mi) = option {
                mi_opt = Some(mi);
            }
        }
        if beta.is_black() {
            break;
        }
        if let Some(mi) = mi_opt {
            // if mi.is_valid() {...}
            if let Some(phase) = mi.clone().phase {
                let vertex: Vertex;
                {
                    // record medium interaction in _path_ and compute forward density
                    let prev: &Vertex = &path[path.len() - 1];
                    vertex = Vertex::create_medium_interaction(mi, &beta, pdf_fwd, prev);
                }
                // if (++bounces >= maxDepth) break;
                bounces += 1;
                if bounces as u32 >= max_depth {
                    // store new vertex
                    path.push(vertex);
                    break;
                }
                // sample direction and compute reverse density at preceding vertex
                let mut wi: Vector3f = Vector3f::default();
                pdf_fwd = phase.sample_p(&(-ray.d), &mut wi, sampler.get_2d());
                pdf_rev = pdf_fwd;
                if let Some(ref mi) = vertex.mi {
                    let new_ray = mi.spawn_ray(&wi);
                    ray = new_ray;
                }
                // compute reverse area density at preceding vertex
                let new_pdf_rev;
                {
                    let prev: &Vertex = &path[path.len() - 1];
                    new_pdf_rev = vertex.convert_density(pdf_rev, prev);
                }
                let index: usize = path.len() - 1;
                path[index].pdf_rev = new_pdf_rev;
                // store new vertex
                path.push(vertex);
            }
        } else if !found_intersection {
            // capture escaped rays when tracing from the camera
            if mode == TransportMode::Radiance {
                let vertex: Vertex = Vertex::create_light_interaction(
                    EndpointInteraction::new_ray(&ray),
                    &beta,
                    pdf_fwd,
                );
                // store new vertex
                path.push(vertex);
                bounces += 1;
            }
            break;
        } else {
            // compute scattering functions for _mode_ and skip over medium
            // boundaries
            isect.compute_scattering_functions(&ray, true, mode);
            let isect_wo: Vector3f = isect.common.wo;
            let isect_shading_n: Normal3f = isect.shading.n;
            if isect.bsdf.is_none() {
                let new_ray = isect.spawn_ray(&ray.d);
                ray = new_ray;
                continue;
            }
            // initialize _vertex_ with surface intersection information
            let mut si_eval: SurfaceInteraction = SurfaceInteraction::default();
            si_eval.common.p = isect.common.p;
            si_eval.common.time = isect.common.time;
            si_eval.common.p_error = isect.common.p_error;
            si_eval.common.wo = isect.common.wo;
            si_eval.common.n = isect.common.n;
            if let Some(ref medium_interface) = isect.common.medium_interface {
                si_eval.common.medium_interface = Some(medium_interface.clone());
            } else {
                si_eval.common.medium_interface = None;
            }
            si_eval.uv = isect.uv;
            si_eval.dpdu = isect.dpdu;
            si_eval.dpdv = isect.dpdv;
            si_eval.dndu = isect.dndu;
            si_eval.dndv = isect.dndv;
            si_eval.dudx = Cell::new(isect.dudx.get());
            si_eval.dvdx = Cell::new(isect.dvdx.get());
            si_eval.dudy = Cell::new(isect.dudy.get());
            si_eval.dvdy = Cell::new(isect.dvdy.get());
            si_eval.dpdx = Cell::new(isect.dpdx.get());
            si_eval.dpdy = Cell::new(isect.dpdy.get());
            if let Some(primitive) = isect.primitive {
                si_eval.primitive = Some(primitive);
            } else {
                si_eval.primitive = None
            }
            si_eval.shading.n = isect.shading.n;
            si_eval.shading.dpdu = isect.shading.dpdu;
            si_eval.shading.dpdv = isect.shading.dpdv;
            si_eval.shading.dndu = isect.shading.dndu;
            si_eval.shading.dndv = isect.shading.dndv;
            if let Some(bsdf) = &isect.bsdf {
                si_eval.bsdf = Some(bsdf.clone());
            } else {
                si_eval.bsdf = None
            }
            // if let Some(bssrdf) = &isect.bssrdf {
            //     si_eval.bssrdf = Some(bssrdf.clone());
            // } else {
            //     si_eval.bssrdf = None
            // }
            if let Some(shape) = &isect.shape {
                si_eval.shape = Some(shape);
            } else {
                si_eval.shape = None
            }
            let mut vertex: Vertex =
                Vertex::create_surface_interaction(si_eval, &beta, pdf_fwd, &path[path.len() - 1]);
            bounces += 1;
            if bounces as u32 >= max_depth {
                // store new vertex
                path.push(vertex);
                break;
            }
            if let Some(ref bsdf) = isect.bsdf {
                // sample BSDF at current vertex and compute reverse probability
                let mut wi: Vector3f = Vector3f::default();
                let bsdf_flags: u8 = BxdfType::BsdfAll as u8;
                let mut sampled_type: u8 = u8::max_value(); // != 0
                let f: Spectrum = bsdf.sample_f(
                    &isect_wo,
                    &mut wi,
                    &sampler.get_2d(),
                    &mut pdf_fwd,
                    bsdf_flags,
                    &mut sampled_type,
                );
                // println!(
                //     "Random walk sampled dir {:?} f: {:?}, pdf_fwd: {:?}",
                //     wi, f, pdf_fwd
                // );
                if f.is_black() || pdf_fwd == 0.0 as Float {
                    // store new vertex
                    path.push(vertex);
                    break;
                }
                *beta *= f * vec3_abs_dot_nrmf(&wi, &isect_shading_n) / pdf_fwd;
                // println!("Random walk beta now {:?}", beta);
                pdf_rev = bsdf.pdf(&wi, &isect_wo, bsdf_flags);
                if (sampled_type & BxdfType::BsdfSpecular as u8) != 0_u8 {
                    vertex.delta = true;
                    pdf_rev = 0.0 as Float;
                    pdf_fwd = 0.0 as Float;
                }
                *beta *= Spectrum::new(correct_shading_normal(&isect, &isect_wo, &wi, mode));
                // println!(
                //     "Random walk beta after shading normal correction {:?}",
                //     beta
                // );
                let new_ray = isect.spawn_ray(&wi);
                ray = new_ray;
            }
            // compute reverse area density at preceding vertex
            let new_pdf_rev: Float;
            {
                let prev: &Vertex = &path[path.len() - 1];
                new_pdf_rev = vertex.convert_density(pdf_rev, prev);
            }
            let index: usize = path.len() - 1;
            path[index].pdf_rev = new_pdf_rev;
            // store new vertex
            path.push(vertex);
        }
    }
    assert!(
        bounces + 1 == path.len(),
        "bounces = {:?}, path.len = {:?}",
        bounces,
        path.len()
    );
    bounces
}

pub fn g<'a>(scene: &'a Scene, sampler: &mut Sampler, v0: &Vertex, v1: &Vertex) -> Spectrum {
    // Vector3f d = v0.p() - v1.p();
    let mut d: Vector3f = v0.p() - v1.p();
    let mut g: Float = 1.0 / d.length_squared();
    d *= g.sqrt();
    if v0.is_on_surface() {
        g *= nrm_abs_dot_vec3f(&v0.ns(), &d);
    }
    if v1.is_on_surface() {
        g *= nrm_abs_dot_vec3f(&v1.ns(), &d);
    }
    // VisibilityTester vis(v0.GetInteraction(), v1.GetInteraction());
    let mut p0: InteractionCommon = InteractionCommon::default();
    match v0.vertex_type {
        VertexType::Medium => {
            if let Some(ref mi) = v0.mi {
                p0 = mi.common.clone();
            }
        }
        VertexType::Surface => {
            if let Some(ref si) = v0.si {
                p0 = si.common.clone();
            }
        }
        _ => {
            if let Some(ref ei) = v0.ei {
                p0 = ei.common.clone();
            }
        }
    }
    let mut p1: InteractionCommon = InteractionCommon::default();
    match v1.vertex_type {
        VertexType::Medium => {
            if let Some(ref mi) = v1.mi {
                p1 = mi.common.clone();
            }
        }
        VertexType::Surface => {
            if let Some(ref si) = v1.si {
                p1 = si.common.clone();
            }
        }
        _ => {
            if let Some(ref ei) = v1.ei {
                p1 = ei.common.clone();
            }
        }
    }
    let vis: VisibilityTester = VisibilityTester {
        p0: Some(&p0),
        p1: Some(&p1),
    };
    vis.tr(scene, sampler) * g
}

pub fn mis_weight<'a>(
    scene: &'a Scene,
    light_vertices: &[Vertex<'a>],
    camera_vertices: &[Vertex<'a>],
    sampled: &Vertex,
    s: usize,
    t: usize,
    light_pdf: Arc<Distribution1D>,
) -> Float {
    if s + t == 2 as usize {
        return 1.0 as Float;
    }
    let mut sum_ri: Float = 0.0;
    // define helper function _remap0_ that deals with Dirac delta functions
    // auto remap0 = [](Float f) -> Float { return f != 0 ? f : 1; };

    // temporarily update vertex properties for current strategy

    // look up connection vertices and their predecessors
    // Vertex *qs = s > 0 ? &light_vertices[s - 1] : nullptr,
    //        *pt = t > 0 ? &camera_vertices[t - 1] : nullptr,
    //        *qsMinus = s > 1 ? &light_vertices[s - 2] : nullptr,
    //        *ptMinus = t > 1 ? &camera_vertices[t - 2] : nullptr;
    let mut qs: Option<Vertex> = None;
    let mut pt: Option<Vertex> = None;
    let mut qs_minus: Option<Vertex> = None;
    let mut pt_minus: Option<Vertex> = None;

    // update sampled vertex for $s=1$ or $t=1$ strategy
    if s == 1 {
        // a1 = {qs, sampled};
        let mut ei: Option<EndpointInteraction> = None;
        let mut mi: Option<MediumInteraction> = None;
        let mut si: Option<SurfaceInteraction> = None;
        if let Some(ref lv_ei) = sampled.ei {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut camera: Option<&Arc<Camera>> = None;
            let mut light: Option<&Arc<Light>> = None;
            if let Some(ref medium_interface_arc) = lv_ei.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(camera_box) = lv_ei.camera {
                camera = Some(camera_box);
            }
            if let Some(light_arc) = lv_ei.light {
                light = Some(light_arc);
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_ei.common.p;
            common.time = lv_ei.common.time;
            common.p_error = lv_ei.common.p_error;
            common.wo = lv_ei.common.wo;
            common.n = lv_ei.common.n;
            common.medium_interface = medium_interface;
            let new_ei: EndpointInteraction = EndpointInteraction {
                common,
                camera,
                light,
            };
            ei = Some(new_ei);
        }
        if let Some(ref lv_mi) = sampled.mi {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut phase: Option<Arc<HenyeyGreenstein>> = None;
            if let Some(ref medium_interface_arc) = lv_mi.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(ref phase_arc) = lv_mi.phase {
                phase = Some(phase_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_mi.common.p;
            common.time = lv_mi.common.time;
            common.p_error = lv_mi.common.p_error;
            common.wo = lv_mi.common.wo;
            common.n = lv_mi.common.n;
            common.medium_interface = medium_interface;
            let new_mi: MediumInteraction = MediumInteraction { common, phase };
            mi = Some(new_mi);
        }
        if let Some(ref lv_si) = sampled.si {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            if let Some(ref medium_interface_arc) = lv_si.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_si.common.p;
            common.time = lv_si.common.time;
            common.p_error = lv_si.common.p_error;
            common.wo = lv_si.common.wo;
            common.n = lv_si.common.n;
            common.medium_interface = medium_interface;
            if let Some(primitive) = lv_si.primitive {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: Some(primitive),
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            } else {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: None,
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
        }
        qs = Some(Vertex {
            vertex_type: sampled.vertex_type.clone(),
            beta: sampled.beta,
            ei,
            mi,
            si,
            delta: sampled.delta,
            pdf_fwd: sampled.pdf_fwd,
            pdf_rev: sampled.pdf_rev,
        });
    } else if t == 1 {
        // a1 = {pt, sampled};
        let mut ei: Option<EndpointInteraction> = None;
        let mut mi: Option<MediumInteraction> = None;
        let mut si: Option<SurfaceInteraction> = None;
        if let Some(ref lv_ei) = sampled.ei {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut camera: Option<&Arc<Camera>> = None;
            let mut light: Option<&Arc<Light>> = None;
            if let Some(ref medium_interface_arc) = lv_ei.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(camera_box) = lv_ei.camera {
                camera = Some(camera_box);
            }
            if let Some(light_arc) = lv_ei.light {
                light = Some(light_arc);
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_ei.common.p;
            common.time = lv_ei.common.time;
            common.p_error = lv_ei.common.p_error;
            common.wo = lv_ei.common.wo;
            common.n = lv_ei.common.n;
            common.medium_interface = medium_interface;
            let new_ei: EndpointInteraction = EndpointInteraction {
                common,
                camera,
                light,
            };
            ei = Some(new_ei);
        }
        if let Some(ref lv_mi) = sampled.mi {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut phase: Option<Arc<HenyeyGreenstein>> = None;
            if let Some(ref medium_interface_arc) = lv_mi.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(ref phase_arc) = lv_mi.phase {
                phase = Some(phase_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_mi.common.p;
            common.time = lv_mi.common.time;
            common.p_error = lv_mi.common.p_error;
            common.wo = lv_mi.common.wo;
            common.n = lv_mi.common.n;
            common.medium_interface = medium_interface;
            let new_mi: MediumInteraction = MediumInteraction { common, phase };
            mi = Some(new_mi);
        }
        if let Some(ref lv_si) = sampled.si {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            if let Some(ref medium_interface_arc) = lv_si.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_si.common.p;
            common.time = lv_si.common.time;
            common.p_error = lv_si.common.p_error;
            common.wo = lv_si.common.wo;
            common.n = lv_si.common.n;
            common.medium_interface = medium_interface;
            if let Some(primitive) = lv_si.primitive {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: Some(primitive),
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            } else {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: None,
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
        }
        pt = Some(Vertex {
            vertex_type: sampled.vertex_type.clone(),
            beta: sampled.beta,
            ei,
            mi,
            si,
            delta: sampled.delta,
            pdf_fwd: sampled.pdf_fwd,
            pdf_rev: sampled.pdf_rev,
        });
    }
    // mark connection vertices as non-degenerate
    if let Some(ref mut overwrite) = pt {
        overwrite.delta = false;
    } else if t > 0 {
        // *pt = t > 0 ? &cameraVertices[t - 1] : nullptr
        let mut ei: Option<EndpointInteraction> = None;
        let mut mi: Option<MediumInteraction> = None;
        let mut si: Option<SurfaceInteraction> = None;
        if let Some(ref cv_ei) = camera_vertices[t - 1].ei {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut camera: Option<&Arc<Camera>> = None;
            let mut light: Option<&Arc<Light>> = None;
            if let Some(ref medium_interface_arc) = cv_ei.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(camera_box) = cv_ei.camera {
                camera = Some(camera_box);
            }
            if let Some(light_arc) = cv_ei.light {
                light = Some(light_arc);
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = cv_ei.common.p;
            common.time = cv_ei.common.time;
            common.p_error = cv_ei.common.p_error;
            common.wo = cv_ei.common.wo;
            common.n = cv_ei.common.n;
            common.medium_interface = medium_interface;
            let new_ei: EndpointInteraction = EndpointInteraction {
                common,
                camera,
                light,
            };
            ei = Some(new_ei);
        }
        if let Some(ref cv_mi) = camera_vertices[t - 1].mi {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut phase: Option<Arc<HenyeyGreenstein>> = None;
            if let Some(ref medium_interface_arc) = cv_mi.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(ref phase_arc) = cv_mi.phase {
                phase = Some(phase_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = cv_mi.common.p;
            common.time = cv_mi.common.time;
            common.p_error = cv_mi.common.p_error;
            common.wo = cv_mi.common.wo;
            common.n = cv_mi.common.n;
            common.medium_interface = medium_interface;
            let new_mi: MediumInteraction = MediumInteraction { common, phase };
            mi = Some(new_mi);
        }
        if let Some(ref cv_si) = camera_vertices[t - 1].si {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            if let Some(ref medium_interface_arc) = cv_si.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = cv_si.common.p;
            common.time = cv_si.common.time;
            common.p_error = cv_si.common.p_error;
            common.wo = cv_si.common.wo;
            common.n = cv_si.common.n;
            common.medium_interface = medium_interface;
            if let Some(primitive) = cv_si.primitive {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: Some(primitive),
                    bsdf: cv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            } else {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: None,
                    bsdf: cv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
        }
        pt = Some(Vertex {
            vertex_type: camera_vertices[t - 1].vertex_type.clone(),
            beta: camera_vertices[t - 1].beta,
            ei,
            mi,
            si,
            delta: false, // overwrite
            pdf_fwd: camera_vertices[t - 1].pdf_fwd,
            pdf_rev: camera_vertices[t - 1].pdf_rev,
        });
    }
    if let Some(ref mut overwrite) = qs {
        overwrite.delta = false;
    } else if s > 0 {
        // *qs = s > 0 ? &lightVertices[s - 1] : nullptr
        let mut ei: Option<EndpointInteraction> = None;
        let mut mi: Option<MediumInteraction> = None;
        let mut si: Option<SurfaceInteraction> = None;
        if let Some(ref lv_ei) = light_vertices[s - 1].ei {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut camera: Option<&Arc<Camera>> = None;
            let mut light: Option<&Arc<Light>> = None;
            if let Some(ref medium_interface_arc) = lv_ei.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(camera_box) = lv_ei.camera {
                camera = Some(camera_box);
            }
            if let Some(light_arc) = lv_ei.light {
                light = Some(light_arc);
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_ei.common.p;
            common.time = lv_ei.common.time;
            common.p_error = lv_ei.common.p_error;
            common.wo = lv_ei.common.wo;
            common.n = lv_ei.common.n;
            common.medium_interface = medium_interface;
            let new_ei: EndpointInteraction = EndpointInteraction {
                common,
                camera,
                light,
            };
            ei = Some(new_ei);
        }
        if let Some(ref lv_mi) = light_vertices[s - 1].mi {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            let mut phase: Option<Arc<HenyeyGreenstein>> = None;
            if let Some(ref medium_interface_arc) = lv_mi.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            if let Some(ref phase_arc) = lv_mi.phase {
                phase = Some(phase_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_mi.common.p;
            common.time = lv_mi.common.time;
            common.p_error = lv_mi.common.p_error;
            common.wo = lv_mi.common.wo;
            common.n = lv_mi.common.n;
            common.medium_interface = medium_interface;
            let new_mi: MediumInteraction = MediumInteraction { common, phase };
            mi = Some(new_mi);
        }
        if let Some(ref lv_si) = light_vertices[s - 1].si {
            let mut medium_interface: Option<Arc<MediumInterface>> = None;
            if let Some(ref medium_interface_arc) = lv_si.common.medium_interface {
                medium_interface = Some(medium_interface_arc.clone());
            }
            let mut common: InteractionCommon = InteractionCommon::default();
            common.p = lv_si.common.p;
            common.time = lv_si.common.time;
            common.p_error = lv_si.common.p_error;
            common.wo = lv_si.common.wo;
            common.n = lv_si.common.n;
            common.medium_interface = medium_interface;
            if let Some(primitive) = lv_si.primitive {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: Some(primitive),
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            } else {
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    primitive: None,
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
        }
        qs = Some(Vertex {
            vertex_type: light_vertices[s - 1].vertex_type.clone(),
            beta: light_vertices[s - 1].beta,
            ei,
            mi,
            si,
            delta: false, // overwrite
            pdf_fwd: light_vertices[s - 1].pdf_fwd,
            pdf_rev: light_vertices[s - 1].pdf_rev,
        });
    }

    // update reverse density of vertex $\pt{}_{t-1}$
    if let Some(ref mut overwrite) = pt {
        if s > 0 {
            if let Some(ref callable) = qs {
                if s > 1 {
                    overwrite.pdf_rev =
                        callable.pdf(scene, Some(&light_vertices[s - 2]), &overwrite);
                } else {
                    overwrite.pdf_rev = callable.pdf(scene, None, &overwrite);
                }
            }
        } else if t > 1 {
            overwrite.pdf_rev =
                overwrite.pdf_light_origin(scene, &camera_vertices[t - 2], light_pdf);
        }
    }
    // update reverse density of vertex $\pt{}_{t-2}$
    if let Some(ref callable) = pt {
        if t > 1 {
            let mut ei: Option<EndpointInteraction> = None;
            let mut mi: Option<MediumInteraction> = None;
            let mut si: Option<SurfaceInteraction> = None;
            if let Some(ref cv_ei) = camera_vertices[t - 2].ei {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                let mut camera: Option<&Arc<Camera>> = None;
                let mut light: Option<&Arc<Light>> = None;
                if let Some(ref medium_interface_arc) = cv_ei.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                if let Some(camera_box) = cv_ei.camera {
                    camera = Some(camera_box);
                }
                if let Some(light_arc) = cv_ei.light {
                    light = Some(light_arc);
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = cv_ei.common.p;
                common.time = cv_ei.common.time;
                common.p_error = cv_ei.common.p_error;
                common.wo = cv_ei.common.wo;
                common.n = cv_ei.common.n;
                common.medium_interface = medium_interface;
                let new_ei: EndpointInteraction = EndpointInteraction {
                    common,
                    camera,
                    light,
                };
                ei = Some(new_ei);
            }
            if let Some(ref cv_mi) = camera_vertices[t - 2].mi {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                let mut phase: Option<Arc<HenyeyGreenstein>> = None;
                if let Some(ref medium_interface_arc) = cv_mi.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                if let Some(ref phase_arc) = cv_mi.phase {
                    phase = Some(phase_arc.clone());
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = cv_mi.common.p;
                common.time = cv_mi.common.time;
                common.p_error = cv_mi.common.p_error;
                common.wo = cv_mi.common.wo;
                common.n = cv_mi.common.n;
                common.medium_interface = medium_interface;
                let new_mi: MediumInteraction = MediumInteraction { common, phase };
                mi = Some(new_mi);
            }
            if let Some(ref cv_si) = camera_vertices[t - 2].si {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                if let Some(ref medium_interface_arc) = cv_si.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = cv_si.common.p;
                common.time = cv_si.common.time;
                common.p_error = cv_si.common.p_error;
                common.wo = cv_si.common.wo;
                common.n = cv_si.common.n;
                common.medium_interface = medium_interface;
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    bsdf: cv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
            let pdf_rev;
            if s > 0 {
                if let Some(ref qs_ref) = qs {
                    pdf_rev = callable.pdf(scene, Some(&qs_ref), &camera_vertices[t - 2]);
                } else {
                    pdf_rev = callable.pdf(scene, None, &camera_vertices[t - 2]);
                }
            } else {
                pdf_rev = callable.pdf_light(scene, &camera_vertices[t - 2]);
            }
            pt_minus = Some(Vertex {
                vertex_type: camera_vertices[t - 2].vertex_type.clone(),
                beta: camera_vertices[t - 2].beta,
                ei,
                mi,
                si,
                delta: camera_vertices[t - 2].delta,
                pdf_fwd: camera_vertices[t - 2].pdf_fwd,
                pdf_rev,
            });
        }
    }

    // update reverse density of vertices $\pq{}_{s-1}$ and $\pq{}_{s-2}$
    if let Some(ref mut overwrite) = qs {
        if let Some(ref callable) = pt {
            if let Some(ref pt_ref) = pt_minus {
                overwrite.pdf_rev = callable.pdf(scene, Some(&pt_ref), &overwrite);
            } else {
                overwrite.pdf_rev = callable.pdf(scene, None, &overwrite);
            }
        }
    }
    if let Some(ref callable) = qs {
        if s > 1 {
            let mut ei: Option<EndpointInteraction> = None;
            let mut mi: Option<MediumInteraction> = None;
            let mut si: Option<SurfaceInteraction> = None;
            if let Some(ref lv_ei) = light_vertices[s - 2].ei {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                let mut camera: Option<&Arc<Camera>> = None;
                let mut light: Option<&Arc<Light>> = None;
                if let Some(ref medium_interface_arc) = lv_ei.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                if let Some(camera_box) = lv_ei.camera {
                    camera = Some(camera_box);
                }
                if let Some(light_arc) = lv_ei.light {
                    light = Some(light_arc);
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = lv_ei.common.p;
                common.time = lv_ei.common.time;
                common.p_error = lv_ei.common.p_error;
                common.wo = lv_ei.common.wo;
                common.n = lv_ei.common.n;
                common.medium_interface = medium_interface;
                let new_ei: EndpointInteraction = EndpointInteraction {
                    common,
                    camera,
                    light,
                };
                ei = Some(new_ei);
            }
            if let Some(ref lv_mi) = light_vertices[s - 2].mi {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                let mut phase: Option<Arc<HenyeyGreenstein>> = None;
                if let Some(ref medium_interface_arc) = lv_mi.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                if let Some(ref phase_arc) = lv_mi.phase {
                    phase = Some(phase_arc.clone());
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = lv_mi.common.p;
                common.time = lv_mi.common.time;
                common.p_error = lv_mi.common.p_error;
                common.wo = lv_mi.common.wo;
                common.n = lv_mi.common.n;
                common.medium_interface = medium_interface;
                let new_mi: MediumInteraction = MediumInteraction { common, phase };
                mi = Some(new_mi);
            }
            if let Some(ref lv_si) = light_vertices[s - 2].si {
                let mut medium_interface: Option<Arc<MediumInterface>> = None;
                if let Some(ref medium_interface_arc) = lv_si.common.medium_interface {
                    medium_interface = Some(medium_interface_arc.clone());
                }
                let mut common: InteractionCommon = InteractionCommon::default();
                common.p = lv_si.common.p;
                common.time = lv_si.common.time;
                common.p_error = lv_si.common.p_error;
                common.wo = lv_si.common.wo;
                common.n = lv_si.common.n;
                common.medium_interface = medium_interface;
                let new_si: SurfaceInteraction = SurfaceInteraction {
                    common,
                    bsdf: lv_si.bsdf.clone(),
                    ..Default::default()
                };
                si = Some(new_si);
            }
            let pdf_rev;
            if let Some(ref pt_ref) = pt {
                pdf_rev = callable.pdf(scene, Some(&pt_ref), &light_vertices[s - 2]);
            } else {
                pdf_rev = callable.pdf(scene, None, &light_vertices[s - 2]);
            }
            qs_minus = Some(Vertex {
                vertex_type: light_vertices[s - 2].vertex_type.clone(),
                beta: light_vertices[s - 2].beta,
                ei,
                mi,
                si,
                delta: light_vertices[s - 2].delta,
                pdf_fwd: light_vertices[s - 2].pdf_fwd,
                pdf_rev,
            });
        }
    }

    // consider hypothetical connection strategies along the camera subpath
    let mut ri: Float = 1.0;
    let mut i: usize = t - 1;
    while i > 0 {
        let mut cv1: &Vertex = &camera_vertices[i];
        let mut cv0: &Vertex = &camera_vertices[i - 1];
        if i == t - 1 {
            // use modified camera vertices
            if let Some(ref cv) = pt {
                cv1 = cv;
            }
            if let Some(ref cv) = pt_minus {
                cv0 = cv;
            }
        } else if i == t - 2 {
            // use modified camera vertex
            if let Some(ref cv) = pt_minus {
                cv1 = cv;
            }
        }
        let mut numerator: Float = cv1.pdf_rev;
        if numerator == 0.0 {
            numerator = 1.0;
        }
        let mut denominator: Float = cv1.pdf_fwd;
        if denominator == 0.0 {
            denominator = 1.0;
        }
        ri *= numerator / denominator;
        if !cv1.delta && !cv0.delta {
            sum_ri += ri;
        }
        i -= 1;
    }

    // consider hypothetical connection strategies along the light subpath
    ri = 1.0 as Float;
    let mut i: isize = s as isize - 1;
    while i >= 0 {
        let mut lv1: &Vertex = &light_vertices[i as usize];
        if i == s as isize - 1 {
            // use modified light vertices
            if let Some(ref lv) = qs {
                lv1 = lv;
            }
        } else if i == s as isize - 2 {
            // use modified light vertex
            if let Some(ref lv) = qs_minus {
                lv1 = lv;
            }
        }
        let mut numerator: Float = lv1.pdf_rev;
        if numerator == 0.0 {
            numerator = 1.0;
        }
        let mut denominator: Float = lv1.pdf_fwd;
        if denominator == 0.0 {
            denominator = 1.0;
        }
        ri *= numerator / denominator;
        let delta_lightvertex: bool;
        if i > 0 {
            if i == s as isize - 1 {
                // i - 1 == s - 2 (qs_minus == light_vertices[s - 2])
                if let Some(ref lv) = qs_minus {
                    // use modified light vertex
                    delta_lightvertex = lv.delta;
                } else {
                    delta_lightvertex = light_vertices[(i - 1) as usize].delta;
                }
            } else {
                delta_lightvertex = light_vertices[(i - 1) as usize].delta;
            }
        } else {
            delta_lightvertex = lv1.is_delta_light();
        }
        if !lv1.delta && !delta_lightvertex {
            sum_ri += ri;
        }
        i -= 1;
    }
    1.0 as Float / (1.0 as Float + sum_ri)
}

pub fn connect_bdpt<'a>(
    scene: &'a Scene,
    light_vertices: &[Vertex<'a>],
    camera_vertices: &[Vertex<'a>],
    s: usize,
    t: usize,
    light_distr: Arc<Distribution1D>,
    camera: &'a Arc<Camera>,
    sampler: &mut Sampler,
    p_raster: &mut Point2f,
    mis_weight_opt: Option<&mut Float>,
) -> Spectrum {
    // TODO: ProfilePhase _(Prof::BDPTConnectSubpaths);
    let mut l: Spectrum = Spectrum::default();
    // ignore invalid connections related to infinite area lights
    if t > 1 && s != 0 && camera_vertices[t - 1].vertex_type == VertexType::Light {
        return Spectrum::default();
    }
    // perform connection and write contribution to _L_
    let mut sampled: Vertex = Vertex {
        vertex_type: VertexType::Medium,
        beta: Spectrum::default(),
        ei: None,
        mi: None,
        si: None,
        delta: false,
        pdf_fwd: 0.0 as Float,
        pdf_rev: 0.0 as Float,
    };
    if s == 0 {
        // interpret the camera subpath as a complete path
        if camera_vertices[t - 1].is_light() {
            l = camera_vertices[t - 1].le(scene, &camera_vertices[t - 2])
                * camera_vertices[t - 1].beta;
        }
        assert!(!l.has_nans());
    } else if t == 1 {
        // sample a point on the camera and connect it to the light subpath
        assert!(
            (s - 1) < light_vertices.len(),
            "(s - 1) = {:?} should be less than length of light vertices({:?})",
            (s - 1),
            light_vertices.len()
        );
        if light_vertices[s - 1].is_connectible() {
            let mut iref: InteractionCommon = InteractionCommon::default();
            let mut lens_intr: InteractionCommon = InteractionCommon::default();
            // qs.GetInteraction()
            match light_vertices[s - 1].vertex_type {
                VertexType::Medium => {
                    if let Some(ref mi) = light_vertices[s - 1].mi {
                        iref = mi.common.clone();
                    } else {
                    }
                }
                VertexType::Surface => {
                    if let Some(ref si) = light_vertices[s - 1].si {
                        iref = si.common.clone();
                    } else {
                    }
                }
                _ => {
                    if let Some(ref ei) = light_vertices[s - 1].ei {
                        iref = ei.common.clone();
                    } else {
                    }
                }
            }
            let mut wi: Vector3f = Vector3f::default();
            let mut pdf: Float = 0.0 as Float;
            let mut vis: VisibilityTester = VisibilityTester::default();
            let wi_color: Spectrum = camera.sample_wi(
                &iref,
                &mut lens_intr,
                sampler.get_2d(),
                &mut wi,
                &mut pdf,
                p_raster,
                &mut vis,
            );
            if pdf > 0.0 as Float && !wi_color.is_black() {
                // initialize dynamically sampled vertex and _L_ for $t=1$ case
                sampled = Vertex::create_camera_from_interaction(
                    camera,
                    vis.p1.as_ref().unwrap().clone(),
                    &(wi_color / pdf),
                );
                l = light_vertices[s - 1].beta
                    * light_vertices[s - 1].f(&sampled, TransportMode::Importance)
                    * sampled.beta;
                // println!("l = {:?}", l);
                if light_vertices[s - 1].is_on_surface() {
                    l *= Spectrum::new(vec3_abs_dot_nrmf(&wi, &light_vertices[s - 1].ns()));
                }
                assert!(!l.has_nans());
                // only check visibility after we know that the path
                // would make a non-zero contribution.
                if !l.is_black() {
                    l *= vis.tr(scene, sampler);
                }
            }
        }
    } else if s == 1 {
        // sample a point on a light and connect it to the camera subpath
        if camera_vertices[t - 1].is_connectible() {
            let mut light_intr: InteractionCommon = InteractionCommon::default();
            let mut wi: Vector3f = Vector3f::default();
            let mut pdf: Float = 0.0 as Float;
            let mut light_pdf: Option<Float> = Some(0.0 as Float);
            let mut vis: VisibilityTester = VisibilityTester::default();
            let light_num: usize =
                light_distr.sample_discrete(sampler.get_1d(), light_pdf.as_mut());
            //         const std::shared_ptr<Light> &light = scene.lights[light_num];
            let mut iref: InteractionCommon = InteractionCommon::default();
            // pt.GetInteraction()
            match camera_vertices[t - 1].vertex_type {
                VertexType::Medium => {
                    if let Some(ref mi) = camera_vertices[t - 1].mi {
                        iref.p = mi.common.p;
                        iref.time = mi.common.time;
                        iref.p_error = mi.common.p_error;
                        iref.wo = mi.common.wo;
                        iref.n = mi.common.n;
                        if let Some(ref medium_interface_arc) = mi.common.medium_interface {
                            iref.medium_interface = Some(medium_interface_arc.clone())
                        }
                    } else {
                    }
                }
                VertexType::Surface => {
                    if let Some(ref si) = camera_vertices[t - 1].si {
                        iref.p = si.common.p;
                        iref.time = si.common.time;
                        iref.p_error = si.common.p_error;
                        iref.wo = si.common.wo;
                        iref.n = si.common.n;
                    } else {
                    }
                }
                _ => {
                    if let Some(ref ei) = camera_vertices[t - 1].ei {
                        iref.p = ei.common.p;
                        iref.time = ei.common.time;
                        iref.p_error = ei.common.p_error;
                        iref.wo = ei.common.wo;
                        iref.n = ei.common.n;
                    } else {
                    }
                }
            }
            let light_weight: Spectrum = scene.lights[light_num].sample_li(
                &iref,
                &mut light_intr,
                sampler.get_2d(),
                &mut wi,
                &mut pdf,
                &mut vis,
            );
            if pdf > 0.0 as Float && !light_weight.is_black() {
                let ei: EndpointInteraction = EndpointInteraction::new_interaction_from_light(
                    vis.p1.as_ref().unwrap().clone(),
                    &scene.lights[light_num],
                );
                sampled = Vertex::create_light_interaction(
                    ei,
                    &(light_weight / (pdf * light_pdf.unwrap())),
                    0.0 as Float,
                );
                sampled.pdf_fwd =
                    sampled.pdf_light_origin(scene, &camera_vertices[t - 1], light_distr.clone());
                l = camera_vertices[t - 1].beta
                    * camera_vertices[t - 1].f(&sampled, TransportMode::Radiance)
                    * sampled.beta;
                if camera_vertices[t - 1].is_on_surface() {
                    l *= Spectrum::new(vec3_abs_dot_nrmf(&wi, &camera_vertices[t - 1].ns()));
                }
                // only check visibility if the path would carry radiance.
                if !l.is_black() {
                    l *= vis.tr(scene, sampler);
                }
            }
        }
    } else {
        // handle all other bidirectional connection cases
        if light_vertices[s - 1].is_connectible() && camera_vertices[t - 1].is_connectible() {
            let radiance =
                camera_vertices[t - 1].f(&light_vertices[s - 1], TransportMode::Radiance);
            let importance =
                light_vertices[s - 1].f(&camera_vertices[t - 1], TransportMode::Importance);
            l = light_vertices[s - 1].beta * importance * radiance * camera_vertices[t - 1].beta;
            // print!("General connect s: {:?}, t: {:?} ", s, t);
            // print!(
            //     "qs: {:?}, pt: {:?}, ",
            //     light_vertices[s - 1],
            //     camera_vertices[t - 1]
            // );
            // print!(
            //     "qs.f(pt): {:?}, ",
            //     light_vertices[s - 1].f(camera_vertices[t - 1], TransportMode::Importance)
            // );
            // print!(
            //     "pt.f(qs): {:?}, ",
            //     camera_vertices[t - 1].f(light_vertices[s - 1], TransportMode::Radiance)
            // );
            // print!(
            //     "G: {:?}, ",
            //     g(
            //         scene,
            //         sampler,
            //         light_vertices[s - 1],
            //         camera_vertices[t - 1]
            //     )
            // );
            // println!(
            //     "dist^2: {:?}",
            //     distance_squared(light_vertices[s - 1].p(), camera_vertices[t - 1].p())
            // );
            if !l.is_black() {
                l *= g(
                    scene,
                    sampler,
                    &light_vertices[s - 1],
                    &camera_vertices[t - 1],
                );
            }
        }
    }
    // TODO:
    // ++totalPaths;
    // if (L.IsBlack()) ++zeroRadiancePaths;
    // ReportValue(pathLength, s + t - 2);

    // compute MIS weight for connection strategy
    let mis_weight_flt = if !l.is_black() {
        mis_weight(
            scene,
            light_vertices,
            camera_vertices,
            &sampled,
            s,
            t,
            light_distr,
        )
    } else {
        0.0 as Float
    };
    // if mis_weight_flt > 0.0 {
    //     println!(
    //         "MIS weight for (s,t) = ({:?}, {:?}) connection: {:?}",
    //         s, t, mis_weight_flt
    //     );
    // }
    assert!(!mis_weight_flt.is_nan());
    l *= Spectrum::new(mis_weight_flt);
    if let Some(mis_weight_ptr) = mis_weight_opt {
        *mis_weight_ptr = mis_weight_flt;
    }
    l
}

pub fn infinite_light_density<'a>(
    scene: &'a Scene,
    light_distr: Arc<Distribution1D>,
    // const std::unordered_map<const Light *, size_t> &lightToDistrIndex,
    w: &Vector3f,
) -> Float {
    let mut pdf: Float = 0.0 as Float;
    for light in &scene.infinite_lights {
        // for i in 0..scene.infinite_lights.len() {
        //     CHECK(lightToDistrIndex.find(light.get()) != lightToDistrIndex.end());
        //     size_t index = lightToDistrIndex.find(light.get())->second;
        let index: usize = 0; // TODO: calculate index (see above)
        pdf += light.pdf_li(&SurfaceInteraction::default(), &-(*w)) * light_distr.func[index];
    }
    // TODO: Old loop (without cache) !!!
    // for (size_t i = 0; i < scene.lights.size(); ++i)
    //     if (scene.lights[i]->flags & (int)LightFlags::Infinite)
    //         pdf +=
    //             scene.lights[i]->Pdf_Li(Interaction(), -w) * light_distr.func[i];
    pdf / (light_distr.func_int * light_distr.count() as Float)
}