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
//! Almost all nontrivial graphics programs are built on a foundation
//! of geometric classes. These classes represent mathematical
//! constructs like points, vectors, and rays.
//!
//! # Points
//!
//! A **point** is a zero-dimensional location in 2D or 3D space. The
//! **Point2** and **Point3** classes in **pbrt** represent points in
//! the obvious way: using x, y, z (in 3D) coordinates with respect to
//! a coordinate system. Although the same representation is used for
//! vectors, the fact that a point represents a position whereas a
//! vector represents a direction leads to a number of important
//! differences in how they are treated.
//!
//! ```rust
//! use rs_pbrt::core::geometry::{Point3i, Point3f};
//!
//! fn main() {
//!     let int_origin = Point3i { x: 0, y: 0, z: 0 };
//!     let float_origin = Point3f {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("int   {:?}", int_origin);
//!     println!("float {:?}", float_origin);
//! }
//! ```
//!
//! # Vectors
//!
//! **pbrt** provides both 2D and 3D **vector** classes. Both are
//! parameterized by the type of the underlying vector element, thus
//! making it easy to instantiate vectors of both integer and
//! floating-point types.
//!
//! ```rust
//! use rs_pbrt::core::geometry::{Vector3i, Vector3f};
//!
//! fn main() {
//!     let int_null = Vector3i { x: 0, y: 0, z: 0 };
//!     let float_null = Vector3f {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("int   {:?}", int_null);
//!     println!("float {:?}", float_null);
//! }
//! ```
//!
//! # Normals
//!
//! A surface **normal** (or just normal) is a vector that is
//! perpendicular to a surface at a particular position. It can be
//! defined as the cross product of any two nonparallel vectors that
//! are tangent to the surface at a point. Although normals are
//! superficially similar to vectors, it is important to distinguish
//! between the two of them: because normals are defined in terms of
//! their relationship to a particular surface, they behave
//! differently than vectors in some situations, particularly when
//! applying transformations.
//!
//! ```rust
//! use rs_pbrt::core::geometry::Normal3f;
//!
//! fn main() {
//!     let float_null = Normal3f {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("float {:?}", float_null);
//! }
//! ```
//!
//! # Rays
//!
//! A **ray** is a semi-infinite line specified by its origin and
//! direction. **pbrt** represents a **Ray** with a **Point3f** for
//! the origin and a **Vector3f** for the direction. We only need rays
//! with floating-point origins and directions, so **Ray** isn't a
//! template class parameterized by an arbitrary type, as points,
//! vectors, and normals were.
//!
//! ```rust
//! use rs_pbrt::core::geometry::{Ray, Point3f, Vector3f};
//! use std::cell::Cell;
//!
//! fn main() {
//!     let origin = Point3f {
//!         x: -5.5,
//!         y: 2.75,
//!         z: 0.0,
//!     };
//!     let direction = Vector3f {
//!         x: 1.0,
//!         y: -8.75,
//!         z: 2.25,
//!     };
//!     let ray = Ray {
//!         o: origin,
//!         d: direction,
//!         t_max: Cell::new(std::f32::INFINITY),
//!         time: 0.0,
//!         medium: None,
//!         differential: None,
//!     };
//! }
//! ```
//!
//! ## RayDifferentials
//!
//! **RayDifferential** is a subclass of **Ray** that contains
//! additional information about two auxiliary rays. These extra rays
//! represent camera rays offset by one sample in the *x* and *y*
//! direction from the main ray on the film plane. By determining the
//! area that these three rays project on an object being shaded, the
//! **Texture** can estimate an area to average over for proper
//! antialiasing.
//!
//! In Rust we don't have inheritance, therefore we use an
//! **Option<RayDifferential>** in the **Ray** struct, which means the
//! additional information can be present (or not).
//!
//! # Bounding Boxes
//!
//! Many parts of the system operate on axis-aligned regions of
//! space. For example, multi-threading in **pbrt** is implemented by
//! subdividing the image into rectangular tiles that can be processed
//! independently, and the bounding volume hierarchy uses 3D boxes to
//! bound geometric primitives in the scene. The **Bounds2** and
//! **Bounds3** template classes are used to represent the extent of
//! these sort of regions. Both are parameterized by a type T that is
//! used to represent the coordinates of its extents.
//!
//!
//! ```rust
//! use rs_pbrt::core::geometry::{Bounds3i, Bounds3f, Point3i, Point3f};
//!
//! fn main() {
//!     let int_origin = Point3i { x: 0, y: 0, z: 0 };
//!     let int_xyz111 = Point3i { x: 1, y: 1, z: 1 };
//!     let float_origin = Point3f {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!     let float_xyz111 = Point3f {
//!         x: 1.0,
//!         y: 1.0,
//!         z: 1.0,
//!     };
//!     let int_unit_cube = Bounds3i {
//!         p_min: int_origin,
//!         p_max: int_xyz111,
//!     };
//!     let float_unit_cube = Bounds3f {
//!         p_min: float_origin,
//!         p_max: float_xyz111,
//!     };
//!
//!     println!("int   {:?}", int_unit_cube);
//!     println!("float {:?}", float_unit_cube);
//! }
//! ```

// std
use std::cell::Cell;
use std::f32::consts::PI;
use std::ops;
use std::ops::{Index, IndexMut};
use std::sync::Arc;
// others
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
// pbrt
use crate::core::medium::Medium;
use crate::core::pbrt::Float;
use crate::core::pbrt::{clamp_t, gamma, lerp, next_float_down, next_float_up};

// see geometry.h

// pub type Point2f = Point2<Float>;
// pub type Point2i = Point2<i32>;
// pub type Point3f = Point3<Float>;
// pub type Point3i = Point3<i32>;
// pub type Vector2f = Vector2<Float>;
// pub type Vector2i = Vector2<i32>;
// pub type Vector3f = Vector3<Float>;
// pub type Vector3i = Vector3<i32>;
// pub type Normal3f = Normal3<Float>;

#[derive(EnumIter, Debug, Copy, Clone)]
#[repr(u8)]
pub enum XYEnum {
    X = 0,
    Y = 1,
}

#[derive(EnumIter, Debug, Copy, Clone)]
#[repr(u8)]
pub enum MinMaxEnum {
    Min = 0,
    Max = 1,
}

#[derive(EnumIter, Debug, Copy, Clone)]
#[repr(u8)]
pub enum XYZEnum {
    X = 0,
    Y = 1,
    Z = 2,
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Vector2f {
    pub x: Float,
    pub y: Float,
}

impl Vector2f {
    pub fn has_nans(&self) -> bool {
        self.x.is_nan() || self.y.is_nan()
    }
    pub fn length_squared(&self) -> Float {
        self.x * self.x + self.y * self.y
    }
    pub fn length(&self) -> Float {
        self.length_squared().sqrt()
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Vector2i {
    pub x: i32,
    pub y: i32,
}

impl Vector2i {
    pub fn length_squared(&self) -> i32 {
        self.x * self.x + self.y * self.y
    }
}

impl Index<XYEnum> for Vector2f {
    type Output = Float;
    fn index(&self, index: XYEnum) -> &Float {
        match index {
            XYEnum::X => &self.x,
            _ => &self.y,
        }
    }
}

impl Index<XYEnum> for Vector2i {
    type Output = i32;
    fn index(&self, index: XYEnum) -> &i32 {
        match index {
            XYEnum::X => &self.x,
            _ => &self.y,
        }
    }
}

impl IndexMut<XYEnum> for Vector2f {
    fn index_mut(&mut self, index: XYEnum) -> &mut Float {
        match index {
            XYEnum::X => &mut self.x,
            _ => &mut self.y,
        }
    }
}

impl IndexMut<XYEnum> for Vector2i {
    fn index_mut(&mut self, index: XYEnum) -> &mut i32 {
        match index {
            XYEnum::X => &mut self.x,
            _ => &mut self.y,
        }
    }
}

// impl<T> AddAssign<Vector2<T>> for Vector2<T>
// where
//     T: AddAssign,
// {
//     fn add_assign(&mut self, rhs: Vector2<T>) {
//         self.x += rhs.x;
//         self.y += rhs.y;
//     }
// }

// impl<T> Add for Vector2<T>
// where
//     T: Copy + Add<T, Output = T>,
// {
//     type Output = Vector2<T>;
//     fn add(self, rhs: Vector2<T>) -> Vector2<T> {
//         Vector2::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//         }
//     }
// }

// impl<T> SubAssign<Vector2<T>> for Vector2<T>
// where
//     T: SubAssign,
// {
//     fn sub_assign(&mut self, rhs: Vector2<T>) {
//         self.x -= rhs.x;
//         self.y -= rhs.y;
//     }
// }

// impl<T> Sub for Vector2<T>
// where
//     T: Copy + Sub<T, Output = T>,
// {
//     type Output = Vector2<T>;
//     fn sub(self, rhs: Vector2<T>) -> Vector2<T> {
//         Vector2::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//         }
//     }
// }

// impl<T> MulAssign<T> for Vector2<T>
// where
//     T: Copy + MulAssign,
// {
//     fn mul_assign(&mut self, rhs: T) {
//         self.x *= rhs;
//         self.y *= rhs;
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl Div<Float> for Vector2<f32> {
//     type Output = Vector2<f32>;
//     fn div(self, rhs: Float) -> Vector2<f32> {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         Vector2::<f32> {
//             x: self.x * inv,
//             y: self.y * inv,
//         }
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl DivAssign<Float> for Vector2<f32> {
//     fn div_assign(&mut self, rhs: Float) {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         self.x *= inv;
//         self.y *= inv;
//     }
// }

impl From<Vector2f> for Point2f {
    fn from(v: Vector2f) -> Self {
        Point2f { x: v.x, y: v.y }
    }
}

impl From<Vector2i> for Point2i {
    fn from(v: Vector2i) -> Self {
        Point2i { x: v.x, y: v.y }
    }
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
pub fn vec2_dotf(v1: &Vector2f, v2: &Vector2f) -> Float {
    v1.x * v2.x + v1.y * v2.y
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
pub fn vec2_doti(v1: &Vector2i, v2: &Vector2i) -> i32 {
    v1.x * v2.x + v1.y * v2.y
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Vector3f {
    pub x: Float,
    pub y: Float,
    pub z: Float,
}

impl Vector3f {
    pub fn has_nans(&self) -> bool {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
    }
    pub fn abs(&self) -> Vector3f {
        Vector3f {
            x: self.x.abs(),
            y: self.y.abs(),
            z: self.z.abs(),
        }
    }
    pub fn length_squared(&self) -> Float {
        self.x * self.x + self.y * self.y + self.z * self.z
    }
    pub fn length(&self) -> Float {
        self.length_squared().sqrt()
    }
    /// Compute a new vector pointing in the same direction but with unit
    /// length.
    pub fn normalize(&self) -> Vector3f {
        *self / self.length()
    }
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Vector3i {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

impl Vector3i {
    pub fn abs(&self) -> Vector3i {
        Vector3i {
            x: self.x.abs(),
            y: self.y.abs(),
            z: self.z.abs(),
        }
    }
    pub fn length_squared(&self) -> i32 {
        self.x * self.x + self.y * self.y + self.z * self.z
    }
}

// impl<T> AddAssign<Vector3<T>> for Vector3<T>
// where
//     T: AddAssign,
// {
//     fn add_assign(&mut self, rhs: Vector3<T>) {
//         self.x += rhs.x;
//         self.y += rhs.y;
//         self.z += rhs.z;
//     }
// }

// impl<T> Add for Vector3<T>
// where
//     T: Copy + Add<T, Output = T>,
// {
//     type Output = Vector3<T>;
//     fn add(self, rhs: Vector3<T>) -> Vector3<T> {
//         Vector3::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//             z: self.z + rhs.z,
//         }
//     }
// }

// impl<T> SubAssign<Vector3<T>> for Vector3<T>
// where
//     T: SubAssign,
// {
//     fn sub_assign(&mut self, rhs: Vector3<T>) {
//         self.x -= rhs.x;
//         self.y -= rhs.y;
//         self.z -= rhs.z;
//     }
// }

// impl<T> Sub for Vector3<T>
// where
//     T: Copy + Sub<T, Output = T>,
// {
//     type Output = Vector3<T>;
//     fn sub(self, rhs: Vector3<T>) -> Vector3<T> {
//         Vector3::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//             z: self.z - rhs.z,
//         }
//     }
// }

// impl<T> Mul<T> for Vector3<T>
// where
//     T: Copy + Mul<T, Output = T>,
// {
//     type Output = Vector3<T>;
//     fn mul(self, rhs: T) -> Vector3<T>
//     where
//         T: Copy + Mul<T, Output = T>,
//     {
//         Vector3::<T> {
//             x: self.x * rhs,
//             y: self.y * rhs,
//             z: self.z * rhs,
//         }
//     }
// }

// impl<T> MulAssign<T> for Vector3<T>
// where
//     T: Copy + MulAssign,
// {
//     fn mul_assign(&mut self, rhs: T) {
//         self.x *= rhs;
//         self.y *= rhs;
//         self.z *= rhs;
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl Div<Float> for Vector3<f32> {
//     type Output = Vector3<f32>;
//     fn div(self, rhs: Float) -> Vector3<f32> {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         Vector3::<f32> {
//             x: self.x * inv,
//             y: self.y * inv,
//             z: self.z * inv,
//         }
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl DivAssign<Float> for Vector3<f32> {
//     fn div_assign(&mut self, rhs: Float) {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         self.x *= inv;
//         self.y *= inv;
//         self.z *= inv;
//     }
// }

impl_op!(-|a: Vector2f| -> Vector2f { Vector2f { x: -a.x, y: -a.y } });

impl_op!(-|a: Vector3f| -> Vector3f {
    Vector3f {
        x: -a.x,
        y: -a.y,
        z: -a.z,
    }
});

impl_op!(-|a: Normal3f| -> Normal3f {
    Normal3f {
        x: -a.x,
        y: -a.y,
        z: -a.z,
    }
});

// impl<T> Neg for Vector3<T>
// where
//     T: Copy + Neg<Output = T>,
// {
//     type Output = Vector3<T>;
//     fn neg(self) -> Vector3<T> {
//         Vector3::<T> {
//             x: -self.x,
//             y: -self.y,
//             z: -self.z,
//         }
//     }
// }

impl Index<XYZEnum> for Vector3f {
    type Output = Float;
    fn index(&self, index: XYZEnum) -> &Float {
        match index {
            XYZEnum::X => &self.x,
            XYZEnum::Y => &self.y,
            _ => &self.z,
        }
    }
}

impl Index<XYZEnum> for Vector3i {
    type Output = i32;
    fn index(&self, index: XYZEnum) -> &i32 {
        match index {
            XYZEnum::X => &self.x,
            XYZEnum::Y => &self.y,
            _ => &self.z,
        }
    }
}

// impl<T> IndexMut<XYZEnum> for Vector3<T> {
//     fn index_mut(&mut self, index: XYZEnum) -> &mut T {
//         match index {
//             XYZEnum::X => &mut self.x,
//             XYZEnum::Y => &mut self.y,
//             _ => &mut self.z,
//         }
//     }
// }

impl From<Point3f> for Vector3f {
    fn from(p: Point3f) -> Self {
        Vector3f {
            x: p.x,
            y: p.y,
            z: p.z,
        }
    }
}

impl From<Normal3f> for Vector3f {
    fn from(n: Normal3f) -> Self {
        Vector3f {
            x: n.x,
            y: n.y,
            z: n.z,
        }
    }
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
pub fn vec3_dot_vec3f(v1: &Vector3f, v2: &Vector3f) -> Float {
    v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
pub fn vec3_dot_vec3i(v1: &Vector3i, v2: &Vector3i) -> i32 {
    v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
}

/// Product of the Euclidean magnitudes of a vector (and a normal) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn vec3_dot_nrmf(v1: &Vector3f, n2: &Normal3f) -> Float {
    // DCHECK(!v1.HasNaNs() && !n2.HasNaNs());
    v1.x * n2.x + v1.y * n2.y + v1.z * n2.z
}

/// Product of the Euclidean magnitudes of a vector (and a normal) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn vec3_dot_nrmi(v1: &Vector3i, n2: &Normal3i) -> i32 {
    // DCHECK(!v1.HasNaNs() && !n2.HasNaNs());
    v1.x * n2.x + v1.y * n2.y + v1.z * n2.z
}

/// Computes the absolute value of the dot product.
pub fn vec3_abs_dot_vec3f(v1: &Vector3f, v2: &Vector3f) -> Float {
    vec3_dot_vec3f(v1, v2).abs()
}

/// Computes the absolute value of the dot product.
pub fn vec3_abs_dot_vec3i(v1: &Vector3i, v2: &Vector3i) -> i32 {
    vec3_dot_vec3i(v1, v2).abs()
}

/// Computes the absolute value of the dot product.
pub fn vec3_abs_dot_nrmf(v1: &Vector3f, n2: &Normal3f) -> Float {
    vec3_dot_nrmf(v1, n2).abs()
}

/// Computes the absolute value of the dot product.
pub fn vec3_abs_dot_nrmi(v1: &Vector3i, n2: &Normal3i) -> i32 {
    vec3_dot_nrmi(v1, n2).abs()
}

/// Given two vectors in 3D, the cross product is a vector that is
/// perpendicular to both of them.
pub fn vec3_cross_vec3(v1: &Vector3f, v2: &Vector3f) -> Vector3f {
    let v1x: f64 = v1.x as f64;
    let v1y: f64 = v1.y as f64;
    let v1z: f64 = v1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((v1y * v2z) - (v1z * v2y)) as Float,
        y: ((v1z * v2x) - (v1x * v2z)) as Float,
        z: ((v1x * v2y) - (v1y * v2x)) as Float,
    }
}

/// Given a vectors and a normal in 3D, the cross product is a vector
/// that is perpendicular to both of them.
pub fn vec3_cross_nrm(v1: &Vector3f, v2: &Normal3f) -> Vector3f {
    let v1x: f64 = v1.x as f64;
    let v1y: f64 = v1.y as f64;
    let v1z: f64 = v1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((v1y * v2z) - (v1z * v2y)) as Float,
        y: ((v1z * v2x) - (v1x * v2z)) as Float,
        z: ((v1x * v2y) - (v1y * v2x)) as Float,
    }
}

/// Return the largest coordinate value.
pub fn vec3_max_componentf(v: &Vector3f) -> Float {
    v.x.max(v.y.max(v.z))
}

/// Return the largest coordinate value.
pub fn vec3_max_componenti(v: &Vector3i) -> i32 {
    v.x.max(v.y.max(v.z))
}

/// Return the index of the component with the largest value.
pub fn vec3_max_dimensionf(v: &Vector3f) -> usize {
    if v.x > v.y {
        if v.x > v.z {
            0_usize
        } else {
            2_usize
        }
    } else if v.y > v.z {
        1_usize
    } else {
        2_usize
    }
}

/// Return the index of the component with the largest value.
pub fn vec3_max_dimensioni(v: &Vector3i) -> usize {
    if v.x > v.y {
        if v.x > v.z {
            0_usize
        } else {
            2_usize
        }
    } else if v.y > v.z {
        1_usize
    } else {
        2_usize
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn vec3_permutef(v: &Vector3f, x: usize, y: usize, z: usize) -> Vector3f {
    let v3: [Float; 3] = [v.x, v.y, v.z];
    let xp: Float = v3[x];
    let yp: Float = v3[y];
    let zp: Float = v3[z];
    Vector3f {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn vec3_permutei(v: &Vector3i, x: usize, y: usize, z: usize) -> Vector3i {
    let v3: [i32; 3] = [v.x, v.y, v.z];
    let xp: i32 = v3[x];
    let yp: i32 = v3[y];
    let zp: i32 = v3[z];
    Vector3i {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Construct a local coordinate system given only a single 3D vector.
pub fn vec3_coordinate_system(v1: &Vector3f, v2: &mut Vector3f, v3: &mut Vector3f) {
    if v1.x.abs() > v1.y.abs() {
        *v2 = Vector3f {
            x: -v1.z,
            y: 0.0 as Float,
            z: v1.x,
        } / (v1.x * v1.x + v1.z * v1.z).sqrt();
    } else {
        *v2 = Vector3f {
            x: 0.0 as Float,
            y: v1.z,
            z: -v1.y,
        } / (v1.y * v1.y + v1.z * v1.z).sqrt();
    }
    *v3 = vec3_cross_vec3(v1, &*v2);
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point2f {
    pub x: Float,
    pub y: Float,
}

impl Point2f {
    pub fn has_nans(&self) -> bool {
        self.x.is_nan() || self.y.is_nan()
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point2i {
    pub x: i32,
    pub y: i32,
}

// impl<T> PartialEq for Point2<T>
// where
//     T: std::cmp::PartialOrd,
// {
//     fn eq(&self, rhs: &Point2<T>) -> bool {
//         self.x == rhs.x && self.y == rhs.y
//     }
// }

// impl<T> Add<Point2<T>> for Point2<T>
// where
//     T: Add<T, Output = T>,
// {
//     type Output = Point2<T>;
//     fn add(self, rhs: Point2<T>) -> Point2<T> {
//         Point2::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//         }
//     }
// }

// impl<T> Add<Vector2<T>> for Point2<T>
// where
//     T: Add<T, Output = T>,
// {
//     type Output = Point2<T>;
//     fn add(self, rhs: Vector2<T>) -> Point2<T> {
//         Point2::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//         }
//     }
// }

// impl<T> Sub<Point2<T>> for Point2<T>
// where
//     T: Sub<T, Output = T>,
// {
//     type Output = Vector2<T>;
//     fn sub(self, rhs: Point2<T>) -> Vector2<T> {
//         Vector2::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//         }
//     }
// }

// impl<T> Sub<Vector2<T>> for Point2<T>
// where
//     T: Sub<T, Output = T>,
// {
//     type Output = Point2<T>;
//     fn sub(self, rhs: Vector2<T>) -> Point2<T> {
//         Point2::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//         }
//     }
// }

// impl<T> Mul<T> for Point2<T>
// where
//     T: Copy + Mul<T, Output = T>,
// {
//     type Output = Point2<T>;
//     fn mul(self, rhs: T) -> Point2<T>
//     where
//         T: Copy + Mul<T, Output = T>,
//     {
//         Point2::<T> {
//             x: self.x * rhs,
//             y: self.y * rhs,
//         }
//     }
// }

// impl<T> Neg for Vector2<T>
// where
//     T: Copy + Neg<Output = T>,
// {
//     type Output = Vector2<T>;
//     fn neg(self) -> Vector2<T> {
//         Vector2::<T> {
//             x: -self.x,
//             y: -self.y,
//         }
//     }
// }

impl Index<XYEnum> for Point2f {
    type Output = Float;
    fn index(&self, index: XYEnum) -> &Float {
        match index {
            XYEnum::X => &self.x,
            _ => &self.y,
        }
    }
}

impl Index<XYEnum> for Point2i {
    type Output = i32;
    fn index(&self, index: XYEnum) -> &i32 {
        match index {
            XYEnum::X => &self.x,
            _ => &self.y,
        }
    }
}

impl IndexMut<XYEnum> for Point2f {
    fn index_mut(&mut self, index: XYEnum) -> &mut Float {
        match index {
            XYEnum::X => &mut self.x,
            _ => &mut self.y,
        }
    }
}

impl IndexMut<XYEnum> for Point2i {
    fn index_mut(&mut self, index: XYEnum) -> &mut i32 {
        match index {
            XYEnum::X => &mut self.x,
            _ => &mut self.y,
        }
    }
}

/// Apply floor operation component-wise.
pub fn pnt2_floor(p: Point2f) -> Point2f {
    Point2f {
        x: p.x.floor(),
        y: p.y.floor(),
    }
}

/// Apply ceil operation component-wise.
pub fn pnt2_ceil(p: Point2f) -> Point2f {
    Point2f {
        x: p.x.ceil(),
        y: p.y.ceil(),
    }
}

/// Apply std::cmp::min operation component-wise.
pub fn pnt2_min_pnt2i(pa: Point2i, pb: Point2i) -> Point2i {
    Point2i {
        x: std::cmp::min(pa.x, pb.x),
        y: std::cmp::min(pa.y, pb.y),
    }
}

/// Apply std::cmp::max operation component-wise.
pub fn pnt2_max_pnt2i(pa: Point2i, pb: Point2i) -> Point2i {
    Point2i {
        x: std::cmp::max(pa.x, pb.x),
        y: std::cmp::max(pa.y, pb.y),
    }
}

/// Given a bounding box and a point, the **bnd2_union_pnt2()**
/// function returns a new bounding box that encompasses that point as
/// well as the original box.
pub fn bnd2_union_pnt2(b: &Bounds2f, p: Point2f) -> Bounds2f {
    let p_min: Point2f = Point2f {
        x: b.p_min.x.min(p.x),
        y: b.p_min.y.min(p.y),
    };
    let p_max: Point2f = Point2f {
        x: b.p_max.x.max(p.x),
        y: b.p_max.y.max(p.y),
    };
    Bounds2f { p_min, p_max }
}

/// Determine if a given point is inside the bounding box.
pub fn pnt2_inside_bnd2f(pt: Point2f, b: &Bounds2f) -> bool {
    pt.x >= b.p_min.x && pt.x <= b.p_max.x && pt.y >= b.p_min.y && pt.y <= b.p_max.y
}

/// Determine if a given point is inside the bounding box.
pub fn pnt2_inside_bnd2i(pt: Point2i, b: &Bounds2i) -> bool {
    pt.x >= b.p_min.x && pt.x <= b.p_max.x && pt.y >= b.p_min.y && pt.y <= b.p_max.y
}

/// Is a 2D point inside a 2D bound?
pub fn pnt2_inside_exclusivef(pt: Point2f, b: &Bounds2f) -> bool {
    pt.x >= b.p_min.x && pt.x < b.p_max.x && pt.y >= b.p_min.y && pt.y < b.p_max.y
}

/// Is a 2D point inside a 2D bound?
pub fn pnt2_inside_exclusivei(pt: Point2i, b: &Bounds2i) -> bool {
    pt.x >= b.p_min.x && pt.x < b.p_max.x && pt.y >= b.p_min.y && pt.y < b.p_max.y
}

/// Pads the bounding box by a constant factor in both dimensions.
pub fn bnd2_expand(b: &Bounds2f, delta: Float) -> Bounds2f {
    Bounds2f {
        p_min: b.p_min - Vector2f { x: delta, y: delta },
        p_max: b.p_max + Vector2f { x: delta, y: delta },
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point3f {
    pub x: Float,
    pub y: Float,
    pub z: Float,
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point3i {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

impl Point3f {
    pub fn has_nans(&self) -> bool {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
    }
}

// impl<T> AddAssign<Point3<T>> for Point3<T>
// where
//     T: AddAssign,
// {
//     fn add_assign(&mut self, rhs: Point3<T>) {
//         self.x += rhs.x;
//         self.y += rhs.y;
//         self.z += rhs.z;
//     }
// }

impl_op_ex!(+|a: &Point3f, b: &Point3f| -> Point3f {
    Point3f {
        x: a.x + b.x,
        y: a.y + b.y,
        z: a.z + b.z,
    }
});

impl_op_ex!(+|a: &Point2i, b: &Point2i| -> Point2i {
    Point2i {
        x: a.x + b.x,
        y: a.y + b.y,
    }
});

impl_op_ex!(+|a: &Point2f, b: &Point2f| -> Point2f {
    Point2f {
        x: a.x + b.x,
        y: a.y + b.y,
    }
});

impl_op_ex!(+|a: &Vector3f, b: &Vector3f| -> Vector3f {
    Vector3f {
        x: a.x + b.x,
        y: a.y + b.y,
        z: a.z + b.z,
    }
});

impl_op_ex!(+|a: &Normal3f, b: &Normal3f| -> Normal3f {
    Normal3f {
        x: a.x + b.x,
        y: a.y + b.y,
        z: a.z + b.z,
    }
});

impl_op_ex!(-|a: &Normal3f, b: &Normal3f| -> Normal3f {
    Normal3f {
        x: a.x - b.x,
        y: a.y - b.y,
        z: a.z - b.z,
    }
});

impl_op_ex!(-|a: &Vector3f, b: &Vector3f| -> Vector3f {
    Vector3f {
        x: a.x - b.x,
        y: a.y - b.y,
        z: a.z - b.z,
    }
});

impl_op_ex!(+|a: &Point3f, b: &Vector3f| -> Point3f {
    Point3f {
        x: a.x + b.x,
        y: a.y + b.y,
        z: a.z + b.z,
    }
});

impl_op_ex!(+|a: &Point3i, b: &Vector3i| -> Point3i {
    Point3i {
        x: a.x + b.x,
        y: a.y + b.y,
        z: a.z + b.z,
    }
});

impl_op_ex!(+|a: &Point2f, b: &Vector2f| -> Point2f {
    Point2f {
        x: a.x + b.x,
        y: a.y + b.y,
    }
});

impl_op_ex!(-|a: &Point3f, b: &Point3f| -> Vector3f {
    Vector3f {
        x: a.x - b.x,
        y: a.y - b.y,
        z: a.z - b.z,
    }
});

impl_op_ex!(-|a: &Point3i, b: &Point3i| -> Vector3i {
    Vector3i {
        x: a.x - b.x,
        y: a.y - b.y,
        z: a.z - b.z,
    }
});

impl_op_ex!(-|a: &Point2f, b: &Point2f| -> Vector2f {
    Vector2f {
        x: a.x - b.x,
        y: a.y - b.y,
    }
});

impl_op_ex!(-|a: &Point2i, b: &Point2i| -> Vector2i {
    Vector2i {
        x: a.x - b.x,
        y: a.y - b.y,
    }
});

impl_op_ex!(-|a: &Point2f, b: &Vector2f| -> Point2f {
    Point2f {
        x: a.x - b.x,
        y: a.y - b.y,
    }
});

impl_op_ex!(-|a: &Point2i, b: &Vector2i| -> Point2i {
    Point2i {
        x: a.x - b.x,
        y: a.y - b.y,
    }
});

impl_op_ex!(-|a: &Point3f, b: &Vector3f| -> Point3f {
    Point3f {
        x: a.x - b.x,
        y: a.y - b.y,
        z: a.z - b.z,
    }
});

// impl<T> Add<Point3<T>> for Point3<T>
// where
//     T: Add<T, Output = T>,
// {
//     type Output = Point3<T>;
//     fn add(self, rhs: Point3<T>) -> Point3<T> {
//         Point3::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//             z: self.z + rhs.z,
//         }
//     }
// }

// impl<T> Add<Vector3<T>> for Point3<T>
// where
//     T: Add<T, Output = T>,
// {
//     type Output = Point3<T>;
//     fn add(self, rhs: Vector3<T>) -> Point3<T> {
//         Point3::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//             z: self.z + rhs.z,
//         }
//     }
// }

// impl<T> AddAssign<Vector3<T>> for Point3<T>
// where
//     T: AddAssign,
// {
//     fn add_assign(&mut self, rhs: Vector3<T>) {
//         self.x += rhs.x;
//         self.y += rhs.y;
//         self.z += rhs.z;
//     }
// }

// impl<T> Sub<Vector3<T>> for Point3<T>
// where
//     T: Sub<T, Output = T>,
// {
//     type Output = Point3<T>;
//     fn sub(self, rhs: Vector3<T>) -> Point3<T> {
//         Point3::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//             z: self.z - rhs.z,
//         }
//     }
// }

impl_op_ex!(*|a: &Point2f, b: Float| -> Point2f {
    Point2f {
        x: a.x * b,
        y: a.y * b,
    }
});

impl_op_ex!(*|a: &Point3f, b: Float| -> Point3f {
    Point3f {
        x: a.x * b,
        y: a.y * b,
        z: a.z * b,
    }
});

impl_op_ex!(*|a: &Normal3f, b: Float| -> Normal3f {
    Normal3f {
        x: a.x * b,
        y: a.y * b,
        z: a.z * b,
    }
});

impl_op_ex!(*|a: &Vector3f, b: Float| -> Vector3f {
    Vector3f {
        x: a.x * b,
        y: a.y * b,
        z: a.z * b,
    }
});

impl_op_ex!(/|a: &Point3f, b: Float| -> Point3f {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    Point3f {
        x: a.x * inv,
        y: a.y * inv,
        z: a.z * inv,
    }
});

impl_op_ex!(/|a: &Vector3f, b: Float| -> Vector3f {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    Vector3f {
        x: a.x * inv,
        y: a.y * inv,
        z: a.z * inv,
    }
});

impl_op_ex!(/|a: &Vector2f, b: Float| -> Vector2f {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    Vector2f {
        x: a.x * inv,
        y: a.y * inv,
    }
});

impl_op_ex!(/|a: &Normal3f, b: Float| -> Normal3f {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    Normal3f {
        x: a.x * inv,
        y: a.y * inv,
        z: a.z * inv,
    }
});

// impl<T> Mul<T> for Point3<T>
// where
//     T: Copy + Mul<T, Output = T>,
// {
//     type Output = Point3<T>;
//     fn mul(self, rhs: T) -> Point3<T>
//     where
//         T: Copy + Mul<T, Output = T>,
//     {
//         Point3::<T> {
//             x: self.x * rhs,
//             y: self.y * rhs,
//             z: self.z * rhs,
//         }
//     }
// }

// impl<T> MulAssign<T> for Point3<T>
// where
//     T: Copy + MulAssign,
// {
//     fn mul_assign(&mut self, rhs: T) {
//         self.x *= rhs;
//         self.y *= rhs;
//         self.z *= rhs;
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl Div<Float> for Point3<f32> {
//     type Output = Point3<f32>;
//     fn div(self, rhs: Float) -> Point3<f32> {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         Point3::<f32> {
//             x: self.x * inv,
//             y: self.y * inv,
//             z: self.z * inv,
//         }
//     }
// }

impl_op!(*= |a: &mut Point2f, b: Float| {
    a.x *= b;
    a.y *= b;
});

impl_op!(*= |a: &mut Point3f, b: Float| {
    a.x *= b;
    a.y *= b;
    a.z *= b;
});

impl_op!(+= |a: &mut Point3f, b: Point3f| {
    a.x += b.x;
    a.y += b.y;
    a.z += b.z;
});

impl_op!(+= |a: &mut Point3f, b: Vector3f| {
    a.x += b.x;
    a.y += b.y;
    a.z += b.z;
});

impl_op!(+= |a: &mut Vector3f, b: Vector3f| {
    a.x += b.x;
    a.y += b.y;
    a.z += b.z;
});

impl_op!(*= |a: &mut Vector2f, b: Float| {
    a.x *= b;
    a.y *= b;
});

impl_op!(*= |a: &mut Vector3f, b: Float| {
    a.x *= b;
    a.y *= b;
    a.z *= b;
});

impl_op!(*= |a: &mut Normal3f, b: Float| {
    a.x *= b;
    a.y *= b;
    a.z *= b;
});

impl_op!(/= |a: &mut Point3f, b: Float| {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    a.x *= inv;
    a.y *= inv;
    a.z *= inv;
});

impl_op!(/= |a: &mut Vector3f, b: Float| {
    assert_ne!(b, 0.0 as Float);
    let inv: Float = 1.0 as Float / b;
    a.x *= inv;
    a.y *= inv;
    a.z *= inv;
});

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl DivAssign<Float> for Point3<f32> {
//     fn div_assign(&mut self, rhs: Float) {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         self.x *= inv;
//         self.y *= inv;
//         self.z *= inv;
//     }
// }

impl Index<XYZEnum> for Point3f {
    type Output = Float;
    fn index(&self, index: XYZEnum) -> &Float {
        match index {
            XYZEnum::X => &self.x,
            XYZEnum::Y => &self.y,
            _ => &self.z,
        }
    }
}

impl Index<XYZEnum> for Point3i {
    type Output = i32;
    fn index(&self, index: XYZEnum) -> &i32 {
        match index {
            XYZEnum::X => &self.x,
            XYZEnum::Y => &self.y,
            _ => &self.z,
        }
    }
}

impl IndexMut<XYZEnum> for Point3f {
    fn index_mut(&mut self, index: XYZEnum) -> &mut Float {
        match index {
            XYZEnum::X => &mut self.x,
            XYZEnum::Y => &mut self.y,
            _ => &mut self.z,
        }
    }
}

impl IndexMut<XYZEnum> for Point3i {
    fn index_mut(&mut self, index: XYZEnum) -> &mut i32 {
        match index {
            XYZEnum::X => &mut self.x,
            XYZEnum::Y => &mut self.y,
            _ => &mut self.z,
        }
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn pnt3_permutef(v: &Point3f, x: usize, y: usize, z: usize) -> Point3f {
    let v3: [Float; 3] = [v.x, v.y, v.z];
    let xp: Float = v3[x];
    let yp: Float = v3[y];
    let zp: Float = v3[z];
    Point3f {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn pnt3_permutei(v: &Point3i, x: usize, y: usize, z: usize) -> Point3i {
    let v3: [i32; 3] = [v.x, v.y, v.z];
    let xp: i32 = v3[x];
    let yp: i32 = v3[y];
    let zp: i32 = v3[z];
    Point3i {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Interpolate linearly between two provided points.
pub fn pnt3_lerp(t: Float, p0: &Point3f, p1: &Point3f) -> Point3f {
    *p0 * (1.0 as Float - t) as Float + *p1 * t
}

/// Apply floor operation component-wise.
pub fn pnt3_floor(p: &Point3f) -> Point3f {
    Point3f {
        x: p.x.floor(),
        y: p.y.floor(),
        z: p.z.floor(),
    }
}

/// Apply ceil operation component-wise.
pub fn pnt3_ceil(p: &Point3f) -> Point3f {
    Point3f {
        x: p.x.ceil(),
        y: p.y.ceil(),
        z: p.z.ceil(),
    }
}

/// Apply abs operation component-wise.
pub fn pnt3_abs(p: &Point3f) -> Point3f {
    Point3f {
        x: p.x.abs(),
        y: p.y.abs(),
        z: p.z.abs(),
    }
}

/// The distance between two points is the length of the vector
/// between them.
pub fn pnt3_distancef(p1: &Point3f, p2: &Point3f) -> Float {
    (p1 - p2).length()
}

/// The distance squared between two points is the length of the
/// vector between them squared.
pub fn pnt3_distance_squaredf(p1: &Point3f, p2: &Point3f) -> Float {
    (p1 - p2).length_squared()
}

/// When tracing spawned rays leaving the intersection point p, we
/// offset their origins enough to ensure that they are past the
/// boundary of the error box and thus won't incorrectly re-intersect
/// the surface.
pub fn pnt3_offset_ray_origin(
    p: &Point3f,
    p_error: &Vector3f,
    n: &Normal3f,
    w: &Vector3f,
) -> Point3f {
    let d: Float = nrm_dot_vec3f(&nrm_absf(n), p_error);
    let mut offset: Vector3f = Vector3f::from(*n) * d;
    if vec3_dot_nrmf(w, n) < 0.0 as Float {
        offset = -offset;
    }
    let mut po: Point3f = *p + offset;
    // round offset point _po_ away from _p_
    for i in XYZEnum::iter() {
        if offset[i] > 0.0 as Float {
            po[i] = next_float_up(po[i]);
        } else if offset[i] < 0.0 as Float {
            po[i] = next_float_down(po[i]);
        }
    }
    po
}

/// Calculate appropriate direction vector from two angles.
pub fn spherical_direction(sin_theta: Float, cos_theta: Float, phi: Float) -> Vector3f {
    Vector3f {
        x: sin_theta * phi.cos(),
        y: sin_theta * phi.sin(),
        z: cos_theta,
    }
}

/// Take three basis vectors representing the x, y, and z axes and
/// return the appropriate direction vector with respect to the
/// coordinate frame defined by them.
pub fn spherical_direction_vec3(
    sin_theta: Float,
    cos_theta: Float,
    phi: Float,
    x: &Vector3f,
    y: &Vector3f,
    z: &Vector3f,
) -> Vector3f {
    *x * (sin_theta * phi.cos()) + *y * (sin_theta * phi.sin()) + *z * cos_theta
}

/// Conversion of a direction to spherical angles. Note that
/// **spherical_theta()** assumes that the vector **v** has been
/// normalized before being passed in.
pub fn spherical_theta(v: &Vector3f) -> Float {
    clamp_t(v.z, -1.0 as Float, 1.0 as Float).acos()
}

/// Conversion of a direction to spherical angles.
pub fn spherical_phi(v: &Vector3f) -> Float {
    let p: Float = v.y.atan2(v.x);
    if p < 0.0 as Float {
        p + 2.0 as Float * PI
    } else {
        p
    }
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Normal3f {
    pub x: Float,
    pub y: Float,
    pub z: Float,
}

impl Normal3f {
    pub fn length_squared(&self) -> Float {
        self.x * self.x + self.y * self.y + self.z * self.z
    }
    pub fn length(&self) -> Float {
        self.length_squared().sqrt()
    }
    /// Compute a new normal pointing in the same direction but with unit
    /// length.
    pub fn normalize(&self) -> Normal3f {
        *self / self.length()
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Normal3i {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

// impl<T> Add for Normal3<T>
// where
//     T: Copy + Add<T, Output = T>,
// {
//     type Output = Normal3<T>;
//     fn add(self, rhs: Normal3<T>) -> Normal3<T> {
//         Normal3::<T> {
//             x: self.x + rhs.x,
//             y: self.y + rhs.y,
//             z: self.z + rhs.z,
//         }
//     }
// }

// impl<T> Sub for Normal3<T>
// where
//     T: Copy + Sub<T, Output = T>,
// {
//     type Output = Normal3<T>;
//     fn sub(self, rhs: Normal3<T>) -> Normal3<T> {
//         Normal3::<T> {
//             x: self.x - rhs.x,
//             y: self.y - rhs.y,
//             z: self.z - rhs.z,
//         }
//     }
// }

// impl<T> Mul<T> for Normal3<T>
// where
//     T: Copy + Mul<T, Output = T>,
// {
//     type Output = Normal3<T>;
//     fn mul(self, rhs: T) -> Normal3<T>
//     where
//         T: Copy + Mul<T, Output = T>,
//     {
//         Normal3::<T> {
//             x: self.x * rhs,
//             y: self.y * rhs,
//             z: self.z * rhs,
//         }
//     }
// }

// impl<T> MulAssign<T> for Normal3<T>
// where
//     T: Copy + MulAssign,
// {
//     fn mul_assign(&mut self, rhs: T) {
//         self.x *= rhs;
//         self.y *= rhs;
//         self.z *= rhs;
//     }
// }

// impl<T> Neg for Normal3<T>
// where
//     T: Copy + Neg<Output = T>,
// {
//     type Output = Normal3<T>;
//     fn neg(self) -> Normal3<T> {
//         Normal3::<T> {
//             x: -self.x,
//             y: -self.y,
//             z: -self.z,
//         }
//     }
// }

impl Index<XYZEnum> for Normal3f {
    type Output = Float;
    fn index(&self, index: XYZEnum) -> &Float {
        match index {
            XYZEnum::X => &self.x,
            XYZEnum::Y => &self.y,
            _ => &self.z,
        }
    }
}

// impl<T> IndexMut<XYZEnum> for Normal3<T> {
//     fn index_mut(&mut self, index: XYZEnum) -> &mut T {
//         match index {
//             XYZEnum::X => &mut self.x,
//             XYZEnum::Y => &mut self.y,
//             _ => &mut self.z,
//         }
//     }
// }

// impl<T> Normal3<T> {
//     pub fn length_squared(&self) -> T
//     where
//         T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
//     {
//         self.x * self.x + self.y * self.y + self.z * self.z
//     }
//     pub fn length(&self) -> T
//     where
//         T: num::Float,
//     {
//         self.length_squared().sqrt()
//     }
// }

// impl<T> PartialEq for Normal3<T>
// where
//     T: std::cmp::PartialOrd,
// {
//     fn eq(&self, rhs: &Normal3<T>) -> bool {
//         self.x == rhs.x && self.y == rhs.y && self.z == rhs.z
//     }
// }

// work around bug
// https://github.com/rust-lang/rust/issues/40395
// impl Div<Float> for Normal3<f32> {
//     type Output = Normal3<f32>;
//     fn div(self, rhs: Float) -> Normal3<f32> {
//         assert_ne!(rhs, 0.0 as Float);
//         let inv: Float = 1.0 as Float / rhs;
//         Normal3::<f32> {
//             x: self.x * inv,
//             y: self.y * inv,
//             z: self.z * inv,
//         }
//     }
// }

impl From<Vector3f> for Normal3f {
    fn from(v: Vector3f) -> Self {
        Normal3f {
            x: v.x,
            y: v.y,
            z: v.z,
        }
    }
}

/// Given a normal and a vector in 3D, the cross product is a vector
/// that is perpendicular to both of them.
pub fn nrm_cross_vec3(n1: &Normal3f, v2: &Vector3f) -> Vector3f {
    let n1x: f64 = n1.x as f64;
    let n1y: f64 = n1.y as f64;
    let n1z: f64 = n1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((n1y * v2z) - (n1z * v2y)) as Float,
        y: ((n1z * v2x) - (n1x * v2z)) as Float,
        z: ((n1x * v2y) - (n1y * v2x)) as Float,
    }
}

/// Product of the Euclidean magnitudes of a normal (and another
/// normal) and the cosine of the angle between them. A return value
/// of zero means both are orthogonal, a value if one means they are
/// codirectional.
pub fn nrm_dot_nrmf(n1: &Normal3f, n2: &Normal3f) -> Float {
    n1.x * n2.x + n1.y * n2.y + n1.z * n2.z
}

/// Product of the Euclidean magnitudes of a normal (and another
/// normal) and the cosine of the angle between them. A return value
/// of zero means both are orthogonal, a value if one means they are
/// codirectional.
pub fn nrm_dot_nrmi(n1: &Normal3i, n2: &Normal3i) -> i32 {
    n1.x * n2.x + n1.y * n2.y + n1.z * n2.z
}

/// Product of the Euclidean magnitudes of a normal (and a vector) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn nrm_dot_vec3f(n1: &Normal3f, v2: &Vector3f) -> Float {
    n1.x * v2.x + n1.y * v2.y + n1.z * v2.z
}

/// Product of the Euclidean magnitudes of a normal (and a vector) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn nrm_dot_vec3i(n1: &Normal3i, v2: &Vector3i) -> i32 {
    n1.x * v2.x + n1.y * v2.y + n1.z * v2.z
}

/// Computes the absolute value of the dot product.
pub fn nrm_abs_dot_vec3f(n1: &Normal3f, v2: &Vector3f) -> Float {
    nrm_dot_vec3f(n1, v2).abs()
}

/// Computes the absolute value of the dot product.
pub fn nrm_abs_dot_vec3i(n1: &Normal3i, v2: &Vector3i) -> i32 {
    nrm_dot_vec3i(n1, v2).abs()
}

/// Return normal with the absolute value of each coordinate.
pub fn nrm_absf(n: &Normal3f) -> Normal3f {
    Normal3f {
        x: n.x.abs(),
        y: n.y.abs(),
        z: n.z.abs(),
    }
}

/// Return normal with the absolute value of each coordinate.
pub fn nrm_absi(n: &Normal3i) -> Normal3i {
    Normal3i {
        x: n.x.abs(),
        y: n.y.abs(),
        z: n.z.abs(),
    }
}

/// Flip a surface normal so that it lies in the same hemisphere as a
/// given vector.
pub fn nrm_faceforward_vec3(n: &Normal3f, v: &Vector3f) -> Normal3f {
    if nrm_dot_vec3f(n, v) < 0.0 as Float {
        -(*n)
    } else {
        *n
    }
}

/// Flip a surface normal so that it lies in the same hemisphere as a
/// given normal.
pub fn nrm_faceforward_nrm(n: &Normal3f, n2: &Normal3f) -> Normal3f {
    if nrm_dot_nrmf(n, n2) < 0.0 as Float {
        -(*n)
    } else {
        *n
    }
}

// pub type Bounds2f = Bounds2<Float>;
// pub type Bounds2i = Bounds2<i32>;
// pub type Bounds3f = Bounds3<Float>;
// pub type Bounds3i = Bounds3<i32>;

#[derive(Debug, Default, Copy, Clone)]
pub struct Bounds2f {
    pub p_min: Point2f,
    pub p_max: Point2f,
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Bounds2i {
    pub p_min: Point2i,
    pub p_max: Point2i,
}

impl Bounds2f {
    pub fn diagonal(&self) -> Vector2f {
        self.p_max - self.p_min
    }
    pub fn area(&self) -> Float {
        let d: Vector2f = self.p_max - self.p_min;
        d.x * d.y
    }
    pub fn lerp(&self, t: Point2f) -> Point2f {
        Point2f {
            x: lerp(t.x, self.p_min.x, self.p_max.x),
            y: lerp(t.y, self.p_min.y, self.p_max.y),
        }
    }
    pub fn offset(&self, p: Point2f) -> Vector2f {
        let mut o: Vector2f = p - self.p_min;
        if self.p_max.x > self.p_min.x {
            o.x /= self.p_max.x - self.p_min.x;
        }
        if self.p_max.y > self.p_min.y {
            o.y /= self.p_max.y - self.p_min.y;
        }
        o
    }
}

impl Bounds2i {
    pub fn new(p1: Point2i, p2: Point2i) -> Self {
        let p_min: Point2i = Point2i {
            x: std::cmp::min(p1.x, p2.x),
            y: std::cmp::min(p1.y, p2.y),
        };
        let p_max: Point2i = Point2i {
            x: std::cmp::max(p1.x, p2.x),
            y: std::cmp::max(p1.y, p2.y),
        };
        Bounds2i { p_min, p_max }
    }
    pub fn diagonal(&self) -> Vector2i {
        self.p_max - self.p_min
    }
    pub fn area(&self) -> i32 {
        let d: Vector2i = self.p_max - self.p_min;
        d.x * d.y
    }
}

pub struct Bounds2Iterator<'a> {
    p: Point2i,
    bounds: &'a Bounds2i,
}

impl<'a> Iterator for Bounds2Iterator<'a> {
    type Item = Point2i;

    fn next(&mut self) -> Option<Point2i> {
        self.p.x += 1;
        if self.p.x == self.bounds.p_max.x {
            self.p.x = self.bounds.p_min.x;
            self.p.y += 1;
        }
        if self.p.y == self.bounds.p_max.y {
            None
        } else {
            Some(self.p)
        }
    }
}

impl<'a> IntoIterator for &'a Bounds2i {
    type Item = Point2i;
    type IntoIter = Bounds2Iterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Bounds2Iterator {
            // need to start 1 before p_min.x as next() will be called
            // to get the first element
            p: Point2i {
                x: self.p_min.x - 1,
                y: self.p_min.y,
            },
            bounds: self,
        }
    }
}

/// The intersection of two bounding boxes can be found by computing
/// the maximum of their two respective minimum coordinates and the
/// minimum of their maximum coordinates.
pub fn bnd2_intersect_bnd2i(b1: &Bounds2i, b2: &Bounds2i) -> Bounds2i {
    Bounds2i {
        p_min: Point2i {
            x: std::cmp::max(b1.p_min.x, b2.p_min.x),
            y: std::cmp::max(b1.p_min.y, b2.p_min.y),
        },
        p_max: Point2i {
            x: std::cmp::min(b1.p_max.x, b2.p_max.x),
            y: std::cmp::min(b1.p_max.y, b2.p_max.y),
        },
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Bounds3f {
    pub p_min: Point3f,
    pub p_max: Point3f,
}

#[derive(Debug, Copy, Clone)]
pub struct Bounds3i {
    pub p_min: Point3i,
    pub p_max: Point3i,
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Default for Bounds3f {
    fn default() -> Bounds3f {
        let min_num: Float = std::f32::MIN;
        let max_num: Float = std::f32::MAX;
        // Bounds3f
        Bounds3f {
            p_min: Point3f {
                x: max_num,
                y: max_num,
                z: max_num,
            },
            p_max: Point3f {
                x: min_num,
                y: min_num,
                z: min_num,
            },
        }
    }
}

impl Bounds3f {
    pub fn new(p1: Point3f, p2: Point3f) -> Self {
        let p_min: Point3f = Point3f {
            x: p1.x.min(p2.x),
            y: p1.y.min(p2.y),
            z: p1.z.min(p2.z),
        };
        let p_max: Point3f = Point3f {
            x: p1.x.max(p2.x),
            y: p1.y.max(p2.y),
            z: p1.z.max(p2.z),
        };
        Bounds3f { p_min, p_max }
    }
    pub fn corner(&self, corner: u8) -> Point3f {
        // assert!(corner >= 0_u8);
        assert!(corner < 8_u8);
        let x: Float;
        if corner & 1 == 0 {
            x = self.p_min.x;
        } else {
            x = self.p_max.x;
        }
        let y: Float;
        if corner & 2 == 0 {
            y = self.p_min.y;
        } else {
            y = self.p_max.y;
        }
        let z: Float;
        if corner & 4 == 0 {
            z = self.p_min.z;
        } else {
            z = self.p_max.z;
        }
        Point3f { x, y, z }
    }
    pub fn diagonal(&self) -> Vector3f {
        self.p_max - self.p_min
    }
    pub fn surface_area(&self) -> Float {
        let d: Vector3f = self.diagonal();
        // 2 * (d.x * d.y + d.x * d.z + d.y * d.z)
        let r: Float = d.x * d.y + d.x * d.z + d.y * d.z;
        r + r // avoid '2 *'
    }
    pub fn maximum_extent(&self) -> u8 {
        let d: Vector3f = self.diagonal();
        if d.x > d.y && d.x > d.z {
            0_u8
        } else if d.y > d.z {
            1_u8
        } else {
            2_u8
        }
    }
    pub fn offset(&self, p: &Point3f) -> Vector3f {
        let mut o: Vector3f = p - self.p_min;
        if self.p_max.x > self.p_min.x {
            o.x /= self.p_max.x - self.p_min.x;
        }
        if self.p_max.y > self.p_min.y {
            o.y /= self.p_max.y - self.p_min.y;
        }
        if self.p_max.z > self.p_min.z {
            o.z /= self.p_max.z - self.p_min.z;
        }
        o
    }
    pub fn bounding_sphere(b: &Bounds3f, center: &mut Point3f, radius: &mut Float) {
        let p_min: Point3f = b.p_min as Point3f;
        let p_max: Point3f = b.p_max as Point3f;
        let sum: Point3f = p_min + p_max;
        *center = sum / 2.0;
        let center_copy: Point3f = *center as Point3f;
        let is_inside: bool = pnt3_inside_bnd3(&center_copy, b);
        if is_inside {
            *radius = pnt3_distancef(&center_copy, &p_max);
        } else {
            *radius = 0.0;
        }
    }
}

impl Bounds3i {
    pub fn new(p1: Point3i, p2: Point3i) -> Self {
        let p_min: Point3i = Point3i {
            x: p1.x.min(p2.x),
            y: p1.y.min(p2.y),
            z: p1.z.min(p2.z),
        };
        let p_max: Point3i = Point3i {
            x: p1.x.max(p2.x),
            y: p1.y.max(p2.y),
            z: p1.z.max(p2.z),
        };
        Bounds3i { p_min, p_max }
    }
    pub fn corner(&self, corner: u8) -> Point3i {
        // assert!(corner >= 0_u8);
        assert!(corner < 8_u8);
        let x: i32;
        if corner & 1 == 0 {
            x = self.p_min.x;
        } else {
            x = self.p_max.x;
        }
        let y: i32;
        if corner & 2 == 0 {
            y = self.p_min.y;
        } else {
            y = self.p_max.y;
        }
        let z: i32;
        if corner & 4 == 0 {
            z = self.p_min.z;
        } else {
            z = self.p_max.z;
        }
        Point3i { x, y, z }
    }
    pub fn diagonal(&self) -> Vector3i {
        self.p_max - self.p_min
    }
    pub fn surface_area(&self) -> i32 {
        let d: Vector3i = self.diagonal();
        // 2 * (d.x * d.y + d.x * d.z + d.y * d.z)
        let r: i32 = d.x * d.y + d.x * d.z + d.y * d.z;
        r + r // avoid '2 *'
    }
    pub fn maximum_extent(&self) -> u8 {
        let d: Vector3i = self.diagonal();
        if d.x > d.y && d.x > d.z {
            0_u8
        } else if d.y > d.z {
            1_u8
        } else {
            2_u8
        }
    }
    pub fn offset(&self, p: &Point3i) -> Vector3i {
        let mut o: Vector3i = *p - self.p_min;
        if self.p_max.x > self.p_min.x {
            o.x /= self.p_max.x - self.p_min.x;
        }
        if self.p_max.y > self.p_min.y {
            o.y /= self.p_max.y - self.p_min.y;
        }
        if self.p_max.z > self.p_min.z {
            o.z /= self.p_max.z - self.p_min.z;
        }
        o
    }
    pub fn bounding_sphere(b: &Bounds3f, center: &mut Point3f, radius: &mut Float) {
        let p_min: Point3f = b.p_min as Point3f;
        let p_max: Point3f = b.p_max as Point3f;
        let sum: Point3f = p_min + p_max;
        *center = sum / 2.0;
        let center_copy: Point3f = *center as Point3f;
        let is_inside: bool = pnt3_inside_bnd3(&center_copy, b);
        if is_inside {
            *radius = pnt3_distancef(&center_copy, &p_max);
        } else {
            *radius = 0.0;
        }
    }
}

impl Bounds3f {
    pub fn lerp(&self, t: &Point3f) -> Point3f {
        Point3f {
            x: lerp(t.x, self.p_min.x as Float, self.p_max.x as Float),
            y: lerp(t.y, self.p_min.y as Float, self.p_max.y as Float),
            z: lerp(t.z, self.p_min.z as Float, self.p_max.z as Float),
        }
    }
    pub fn intersect_b(&self, ray: &Ray, hitt0: &mut Float, hitt1: &mut Float) -> bool {
        let mut t0: Float = 0.0;
        let mut t1: Float = ray.t_max.get();
        for i in XYZEnum::iter() {
            // update interval for _i_th bounding box slab
            let inv_ray_dir: Float = 1.0 as Float / ray.d[i];
            let mut t_near: Float = (self.p_min[i] - ray.o[i]) * inv_ray_dir;
            let mut t_far: Float = (self.p_max[i] - ray.o[i]) * inv_ray_dir;
            // update parametric interval from slab intersection $t$ values
            if t_near > t_far {
                std::mem::swap(&mut t_near, &mut t_far);
            }
            // update _t_far_ to ensure robust ray--bounds intersection
            t_far *= 1.0 as Float + 2.0 as Float * gamma(3_i32);
            if t_near > t0 {
                t0 = t_near;
            }
            if t_far < t1 {
                t1 = t_far;
            }
            if t0 > t1 {
                return false;
            }
        }
        *hitt0 = t0;
        *hitt1 = t1;
        true
    }
    pub fn intersect_p(&self, ray: &Ray, inv_dir: &Vector3f, dir_is_neg: &[u8; 3]) -> bool {
        let dir_is_neg_0: MinMaxEnum = match dir_is_neg[0] {
            0 => MinMaxEnum::Min,
            _ => MinMaxEnum::Max,
        };
        let dir_is_not_neg_0: MinMaxEnum = match dir_is_neg[0] {
            0 => MinMaxEnum::Max,
            _ => MinMaxEnum::Min,
        };
        let dir_is_neg_1: MinMaxEnum = match dir_is_neg[1] {
            0 => MinMaxEnum::Min,
            _ => MinMaxEnum::Max,
        };
        let dir_is_not_neg_1: MinMaxEnum = match dir_is_neg[1] {
            0 => MinMaxEnum::Max,
            _ => MinMaxEnum::Min,
        };
        let dir_is_neg_2: MinMaxEnum = match dir_is_neg[2] {
            0 => MinMaxEnum::Min,
            _ => MinMaxEnum::Max,
        };
        let dir_is_not_neg_2: MinMaxEnum = match dir_is_neg[2] {
            0 => MinMaxEnum::Max,
            _ => MinMaxEnum::Min,
        };
        // check for ray intersection against $x$ and $y$ slabs
        let mut t_min: Float = (self[dir_is_neg_0].x - ray.o.x) * inv_dir.x;
        let mut t_max: Float = (self[dir_is_not_neg_0].x - ray.o.x) * inv_dir.x;
        let ty_min: Float = (self[dir_is_neg_1].y - ray.o.y) * inv_dir.y;
        let mut ty_max: Float = (self[dir_is_not_neg_1].y - ray.o.y) * inv_dir.y;
        // update _t_max_ and _ty_max_ to ensure robust bounds intersection
        t_max *= 1.0 + 2.0 * gamma(3_i32);
        ty_max *= 1.0 + 2.0 * gamma(3_i32);
        if t_min > ty_max || ty_min > t_max {
            return false;
        }
        if ty_min > t_min {
            t_min = ty_min;
        }
        if ty_max < t_max {
            t_max = ty_max;
        }
        // check for ray intersection against $z$ slab
        let tz_min: Float = (self[dir_is_neg_2].z - ray.o.z) * inv_dir.z;
        let mut tz_max: Float = (self[dir_is_not_neg_2].z - ray.o.z) * inv_dir.z;
        // update _tz_max_ to ensure robust bounds intersection
        tz_max *= 1.0 + 2.0 * gamma(3_i32);
        if t_min > tz_max || tz_min > t_max {
            return false;
        }
        if tz_min > t_min {
            t_min = tz_min;
        }
        if tz_max < t_max {
            t_max = tz_max;
        }
        (t_min < ray.t_max.get()) && (t_max > 0.0)
    }
}

impl Index<MinMaxEnum> for Bounds3f {
    type Output = Point3f;
    fn index(&self, i: MinMaxEnum) -> &Point3f {
        match i {
            MinMaxEnum::Min => &self.p_min,
            _ => &self.p_max,
        }
    }
}

// /// Minimum squared distance from point to box; returns zero if point
// /// is inside.
// pub fn pnt3_distance_squared_bnd3(p: Point3f, b: Bounds3f) -> Float {
//     let dx: Float = (b.p_min.x - p.x).max(num::Zero::zero()).max(p.x - b.p_max.x);
//     let dy: Float = (b.p_min.y - p.y).max(num::Zero::zero()).max(p.y - b.p_max.y);
//     let dz: Float = (b.p_min.z - p.z).max(num::Zero::zero()).max(p.z - b.p_max.z);
//     dx * dx + dy * dy + dz * dz
// }

// /// Minimum distance from point to box; returns zero if point is
// /// inside.
// pub fn pnt3_distance_bnd3(p: Point3f, b: Bounds3f) -> Float {
//     pnt3_distance_squared_bnd3(p, b).sqrt()
// }

/// Given a bounding box and a point, the **bnd3_union_pnt3()**
/// function returns a new bounding box that encompasses that point as
/// well as the original box.
pub fn bnd3_union_pnt3f(b: &Bounds3f, p: &Point3f) -> Bounds3f {
    let p_min: Point3f = Point3f {
        x: b.p_min.x.min(p.x),
        y: b.p_min.y.min(p.y),
        z: b.p_min.z.min(p.z),
    };
    let p_max: Point3f = Point3f {
        x: b.p_max.x.max(p.x),
        y: b.p_max.y.max(p.y),
        z: b.p_max.z.max(p.z),
    };
    Bounds3f { p_min, p_max }
}

/// Construct a new box that bounds the space encompassed by two other
/// bounding boxes.
pub fn bnd3_union_bnd3f(b1: &Bounds3f, b2: &Bounds3f) -> Bounds3f {
    let p_min: Point3f = Point3f {
        x: b1.p_min.x.min(b2.p_min.x),
        y: b1.p_min.y.min(b2.p_min.y),
        z: b1.p_min.z.min(b2.p_min.z),
    };
    let p_max: Point3f = Point3f {
        x: b1.p_max.x.max(b2.p_max.x),
        y: b1.p_max.y.max(b2.p_max.y),
        z: b1.p_max.z.max(b2.p_max.z),
    };
    Bounds3f { p_min, p_max }
}

/// Determine if a given point is inside the bounding box.
pub fn pnt3_inside_bnd3(p: &Point3f, b: &Bounds3f) -> bool {
    p.x >= b.p_min.x
        && p.x <= b.p_max.x
        && p.y >= b.p_min.y
        && p.y <= b.p_max.y
        && p.z >= b.p_min.z
        && p.z <= b.p_max.z
}

/// Is a 3D point inside a 3D bound?
pub fn pnt3i_inside_exclusive(p: &Point3i, b: &Bounds3i) -> bool {
    p.x >= b.p_min.x
        && p.x < b.p_max.x
        && p.y >= b.p_min.y
        && p.y < b.p_max.y
        && p.z >= b.p_min.z
        && p.z < b.p_max.z
}

/// Is a 3D point inside a 3D bound?
pub fn pnt3f_inside_exclusive(p: &Point3f, b: &Bounds3f) -> bool {
    p.x >= b.p_min.x
        && p.x < b.p_max.x
        && p.y >= b.p_min.y
        && p.y < b.p_max.y
        && p.z >= b.p_min.z
        && p.z < b.p_max.z
}

/// Pads the bounding box by a constant factor in all dimensions.
pub fn bnd3_expand(b: &Bounds3f, delta: Float) -> Bounds3f {
    Bounds3f::new(
        b.p_min
            - Vector3f {
                x: delta,
                y: delta,
                z: delta,
            },
        b.p_max
            + Vector3f {
                x: delta,
                y: delta,
                z: delta,
            },
    )
}

#[derive(Default, Clone)]
pub struct Ray {
    /// origin
    pub o: Point3f,
    /// direction
    pub d: Vector3f,
    /// limits the ray to a segment along its infinite extent
    pub t_max: Cell<Float>,
    /// used for animations
    pub time: Float,
    pub medium: Option<Arc<Medium>>,
    /// in C++: 'class RayDifferential : public Ray'
    pub differential: Option<RayDifferential>,
}

impl Ray {
    // Point3f operator()(Float t) const { return o + d * t; }
    pub fn position(&self, t: Float) -> Point3f {
        self.o + self.d * t
    }
    // from class RayDifferential
    pub fn scale_differentials(&mut self, s: Float) {
        if let Some(d) = self.differential.iter_mut().next() {
            d.rx_origin = self.o + (d.rx_origin - self.o) * s;
            d.ry_origin = self.o + (d.ry_origin - self.o) * s;
            d.rx_direction = self.d + (d.rx_direction - self.d) * s;
            d.ry_direction = self.d + (d.ry_direction - self.d) * s;
        }
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct RayDifferential {
    pub rx_origin: Point3f,
    pub ry_origin: Point3f,
    pub rx_direction: Vector3f,
    pub ry_direction: Vector3f,
}