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
//! The geometry of a particular point on a surface is represented by
//! a **SurfaceInteraction**. Having this abstraction lets most of the
//! system work with points on surfaces without needing to consider
//! the particular type of geometric shape the points lie on; the
//! **SurfaceInteraction** abstraction supplies enough information
//! about the surface point to allow the shading and geometric
//! operations in the rest of **pbrt** to be implemented generically.
//!

// std
use std::cell::Cell;
use std::sync::Arc;
// pbrt
use crate::core::bssrdf::TabulatedBssrdf;
use crate::core::geometry::{
    nrm_dot_vec3f, nrm_faceforward_nrm, pnt3_offset_ray_origin, vec3_cross_vec3, vec3_dot_nrmf,
};
use crate::core::geometry::{Normal3f, Point2f, Point3f, Ray, Vector3f, XYZEnum};
use crate::core::material::TransportMode;
use crate::core::medium::{HenyeyGreenstein, Medium, MediumInterface};
use crate::core::pbrt::SHADOW_EPSILON;
use crate::core::pbrt::{Float, Spectrum};
use crate::core::primitive::Primitive;
use crate::core::reflection::Bsdf;
use crate::core::shape::Shape;
use crate::core::transform::solve_linear_system_2x2;

// see interaction.h

pub trait Interaction {
    fn is_surface_interaction(&self) -> bool;
    fn is_medium_interaction(&self) -> bool;
    fn spawn_ray(&self, d: &Vector3f) -> Ray;
    fn get_common(&self) -> &InteractionCommon;
    fn get_p(&self) -> &Point3f;
    fn get_time(&self) -> Float;
    fn get_p_error(&self) -> &Vector3f;
    fn get_wo(&self) -> &Vector3f;
    fn get_n(&self) -> &Normal3f;
    fn get_medium_interface(&self) -> Option<Arc<MediumInterface>>;
    fn get_bsdf(&self) -> Option<&Bsdf>;
    fn get_shading_n(&self) -> Option<&Normal3f>;
    fn get_phase(&self) -> Option<Arc<HenyeyGreenstein>>;
}

#[derive(Default, Clone)]
pub struct InteractionCommon {
    // Interaction Public Data
    pub p: Point3f,
    pub time: Float,
    pub p_error: Vector3f,
    pub wo: Vector3f,
    pub n: Normal3f,
    pub medium_interface: Option<Arc<MediumInterface>>,
}

impl InteractionCommon {
    pub fn spawn_ray(&self, d: &Vector3f) -> Ray {
        let o: Point3f = pnt3_offset_ray_origin(&self.p, &self.p_error, &self.n, d);
        Ray {
            o,
            d: *d,
            t_max: Cell::new(std::f32::INFINITY),
            time: self.time,
            differential: None,
            medium: self.get_medium(d),
        }
    }
    pub fn spawn_ray_to_pnt(&self, p2: &Point3f) -> Ray {
        let d: Vector3f = *p2 - self.p;
        let origin: Point3f = pnt3_offset_ray_origin(&self.p, &self.p_error, &self.n, &d);
        Ray {
            o: origin,
            d,
            t_max: Cell::new(1.0 - SHADOW_EPSILON),
            time: self.time,
            differential: None,
            medium: self.get_medium(&d),
        }
    }
    pub fn spawn_ray_to(&self, it: &InteractionCommon) -> Ray {
        let origin: Point3f =
            pnt3_offset_ray_origin(&self.p, &self.p_error, &self.n, &(it.p - self.p));
        let target: Point3f = pnt3_offset_ray_origin(&it.p, &it.p_error, &it.n, &(origin - it.p));
        let d: Vector3f = target - origin;
        Ray {
            o: origin,
            d,
            t_max: Cell::new(1.0 - SHADOW_EPSILON),
            time: self.time,
            differential: None,
            medium: self.get_medium(&d),
        }
    }
    pub fn get_medium(&self, w: &Vector3f) -> Option<Arc<Medium>> {
        if vec3_dot_nrmf(w, &self.n) > 0.0 as Float {
            if let Some(ref medium_interface_arc) = self.medium_interface {
                medium_interface_arc.get_outside()
            } else {
                None
            }
        } else if let Some(ref medium_interface_arc) = self.medium_interface {
            medium_interface_arc.get_inside()
        } else {
            None
        }
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Shading {
    pub n: Normal3f,
    pub dpdu: Vector3f,
    pub dpdv: Vector3f,
    pub dndu: Normal3f,
    pub dndv: Normal3f,
}

#[derive(Default, Clone)]
pub struct MediumInteraction {
    // Interaction Public Data
    pub common: InteractionCommon,
    // MediumInteraction Public Data
    pub phase: Option<Arc<HenyeyGreenstein>>,
}

impl MediumInteraction {
    pub fn new(
        p: &Point3f,
        wo: &Vector3f,
        time: Float,
        medium: Option<Arc<Medium>>,
        phase: Option<Arc<HenyeyGreenstein>>,
    ) -> Self {
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = *p;
        common.time = time;
        common.p_error = Vector3f::default();
        common.wo = *wo;
        common.n = Normal3f::default();
        if let Some(medium_arc) = medium {
            let inside: Option<Arc<Medium>> = Some(medium_arc.clone());
            let outside: Option<Arc<Medium>> = Some(medium_arc);
            common.medium_interface = Some(Arc::new(MediumInterface::new(inside, outside)));
            MediumInteraction { common, phase }
        } else {
            common.medium_interface = None;
            MediumInteraction { common, phase }
        }
    }
    pub fn get_medium(&self, w: &Vector3f) -> Option<Arc<Medium>> {
        if vec3_dot_nrmf(w, &self.get_n()) > 0.0 as Float {
            if let Some(ref medium_interface) = self.get_medium_interface() {
                if let Some(ref outside_arc) = medium_interface.outside {
                    Some(outside_arc.clone())
                } else {
                    None
                }
            } else {
                None
            }
        } else if let Some(ref medium_interface) = self.get_medium_interface() {
            if let Some(ref inside_arc) = medium_interface.inside {
                Some(inside_arc.clone())
            } else {
                None
            }
        } else {
            None
        }
    }
    pub fn is_valid(&self) -> bool {
        if let Some(ref _arc) = self.phase {
            true
        } else {
            false
        }
    }
    pub fn get_phase(&self) -> Option<Arc<HenyeyGreenstein>> {
        if let Some(ref phase) = self.phase {
            Some(phase.clone())
        } else {
            None
        }
    }
}

impl Interaction for MediumInteraction {
    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>> {
        if let Some(ref phase) = self.phase {
            Some(phase.clone())
        } else {
            None
        }
    }
}

#[derive(Default)]
pub struct SurfaceInteraction<'a> {
    // Interaction Public Data
    pub common: InteractionCommon,
    // SurfaceInteraction Public Data
    pub uv: Point2f,
    pub dpdu: Vector3f,
    pub dpdv: Vector3f,
    pub dndu: Normal3f,
    pub dndv: Normal3f,
    pub dpdx: Cell<Vector3f>,
    pub dpdy: Cell<Vector3f>,
    pub dudx: Cell<Float>,
    pub dvdx: Cell<Float>,
    pub dudy: Cell<Float>,
    pub dvdy: Cell<Float>,
    pub primitive: Option<*const Primitive>,
    pub shading: Shading,
    pub bsdf: Option<Bsdf>,
    pub bssrdf: Option<TabulatedBssrdf>,
    pub shape: Option<&'a Shape>,
}

impl<'a> SurfaceInteraction<'a> {
    pub fn new(
        p: &Point3f,
        p_error: &Vector3f,
        uv: Point2f,
        wo: &Vector3f,
        dpdu: &Vector3f,
        dpdv: &Vector3f,
        dndu: &Normal3f,
        dndv: &Normal3f,
        time: Float,
        sh: Option<&'a Shape>,
    ) -> Self {
        let nv: Vector3f = vec3_cross_vec3(dpdu, dpdv).normalize();
        let mut n: Normal3f = Normal3f {
            x: nv.x,
            y: nv.y,
            z: nv.z,
        };
        // initialize shading geometry from true geometry
        let mut shading: Shading = Shading {
            n,
            dpdu: *dpdu,
            dpdv: *dpdv,
            dndu: *dndu,
            dndv: *dndv,
        };
        if let Some(ref shape) = sh {
            // adjust normal based on orientation and handedness
            if shape.get_reverse_orientation() ^ shape.get_transform_swaps_handedness() {
                n *= -1.0 as Float;
                shading.n *= -1.0 as Float;
            }
        }
        let mut common: InteractionCommon = InteractionCommon::default();
        common.p = *p;
        common.time = time;
        common.p_error = *p_error;
        common.wo = wo.normalize();
        common.n = n;
        common.medium_interface = None;
        if let Some(ref shape) = sh {
            SurfaceInteraction {
                common,
                uv,
                dpdu: *dpdu,
                dpdv: *dpdv,
                dndu: *dndu,
                dndv: *dndv,
                dpdx: Cell::new(Vector3f::default()),
                dpdy: Cell::new(Vector3f::default()),
                dudx: Cell::new(0.0 as Float),
                dvdx: Cell::new(0.0 as Float),
                dudy: Cell::new(0.0 as Float),
                dvdy: Cell::new(0.0 as Float),
                primitive: None,
                shading,
                bsdf: None,
                bssrdf: None,
                shape: Some(shape),
            }
        } else {
            SurfaceInteraction {
                common,
                uv,
                dpdu: *dpdu,
                dpdv: *dpdv,
                dndu: *dndu,
                dndv: *dndv,
                dpdx: Cell::new(Vector3f::default()),
                dpdy: Cell::new(Vector3f::default()),
                dudx: Cell::new(0.0 as Float),
                dvdx: Cell::new(0.0 as Float),
                dudy: Cell::new(0.0 as Float),
                dvdy: Cell::new(0.0 as Float),
                primitive: None,
                shading,
                bsdf: None,
                bssrdf: None,
                shape: None,
            }
        }
    }
    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 {
                if let Some(ref outside_arc) = medium_interface.outside {
                    Some(outside_arc.clone())
                } else {
                    None
                }
            } else {
                None
            }
        } else if let Some(ref medium_interface) = self.common.medium_interface {
            if let Some(ref inside_arc) = medium_interface.inside {
                Some(inside_arc.clone())
            } else {
                None
            }
        } else {
            None
        }
    }
    pub fn set_shading_geometry(
        &mut self,
        dpdus: &Vector3f,
        dpdvs: &Vector3f,
        dndus: &Normal3f,
        dndvs: &Normal3f,
        orientation_is_authoritative: bool,
    ) {
        // compute _shading.n_ for _SurfaceInteraction_
        self.shading.n = Normal3f::from(vec3_cross_vec3(dpdus, dpdvs)).normalize();
        if let Some(ref shape) = self.shape {
            if shape.get_reverse_orientation() ^ shape.get_transform_swaps_handedness() {
                self.shading.n = -self.shading.n;
            }
        }
        if orientation_is_authoritative {
            self.common.n = nrm_faceforward_nrm(&self.common.n, &self.shading.n);
        } else {
            self.shading.n = nrm_faceforward_nrm(&self.shading.n, &self.common.n);
        }
        // initialize _shading_ partial derivative values
        self.shading.dpdu = *dpdus;
        self.shading.dpdv = *dpdvs;
        self.shading.dndu = *dndus;
        self.shading.dndv = *dndvs;
    }
    pub fn compute_scattering_functions(
        &mut self,
        ray: &Ray,
        // arena: &mut Arena,
        allow_multiple_lobes: bool,
        mode: TransportMode,
    ) {
        self.compute_differentials(ray);
        if let Some(primitive_raw) = self.primitive {
            let primitive = unsafe { &*primitive_raw };
            primitive.compute_scattering_functions(
                self, // arena,
                mode,
                allow_multiple_lobes,
            );
        }
    }
    pub fn compute_differentials(&mut self, ray: &Ray) {
        if let Some(ref diff) = ray.differential {
            // estimate screen space change in $\pt{}$ and $(u,v)$

            // compute auxiliary intersection points with plane
            let d: Float = nrm_dot_vec3f(
                &self.common.n,
                &Vector3f {
                    x: self.common.p.x,
                    y: self.common.p.y,
                    z: self.common.p.z,
                },
            );
            let tx: Float = -(nrm_dot_vec3f(&self.common.n, &Vector3f::from(diff.rx_origin)) - d)
                / nrm_dot_vec3f(&self.common.n, &diff.rx_direction);
            if tx.is_infinite() || tx.is_nan() {
                self.dudx.set(0.0 as Float);
                self.dvdx.set(0.0 as Float);
                self.dudy.set(0.0 as Float);
                self.dvdy.set(0.0 as Float);
                self.dpdx.set(Vector3f::default());
                self.dpdy.set(Vector3f::default());
            } else {
                let px: Point3f = diff.rx_origin + diff.rx_direction * tx;
                let ty: Float = -(nrm_dot_vec3f(&self.common.n, &Vector3f::from(diff.ry_origin))
                    - d)
                    / nrm_dot_vec3f(&self.common.n, &diff.ry_direction);
                if ty.is_infinite() || ty.is_nan() {
                    self.dudx.set(0.0 as Float);
                    self.dvdx.set(0.0 as Float);
                    self.dudy.set(0.0 as Float);
                    self.dvdy.set(0.0 as Float);
                    self.dpdx.set(Vector3f::default());
                    self.dpdy.set(Vector3f::default());
                } else {
                    let py: Point3f = diff.ry_origin + diff.ry_direction * ty;
                    self.dpdx.set(px - self.common.p);
                    self.dpdy.set(py - self.common.p);

                    // compute $(u,v)$ offsets at auxiliary points

                    // choose two dimensions to use for ray offset computation
                    let mut dim: [XYZEnum; 2] = [XYZEnum::X; 2];
                    if self.common.n.x.abs() > self.common.n.y.abs()
                        && self.common.n.x.abs() > self.common.n.z.abs()
                    {
                        dim[0] = XYZEnum::Y;
                        dim[1] = XYZEnum::Z;
                    } else if self.common.n.y.abs() > self.common.n.z.abs() {
                        dim[0] = XYZEnum::X;
                        dim[1] = XYZEnum::Z;
                    } else {
                        dim[0] = XYZEnum::X;
                        dim[1] = XYZEnum::Y;
                    }

                    // initialize _a_, _bx_, and _by_ matrices for offset computation
                    let a0: [Float; 2] = [self.dpdu[dim[0]], self.dpdv[dim[0]]];
                    let a1: [Float; 2] = [self.dpdu[dim[1]], self.dpdv[dim[1]]];
                    let a: [[Float; 2]; 2] = [a0, a1];
                    let bx: [Float; 2] = [
                        px[dim[0]] - self.common.p[dim[0]],
                        px[dim[1]] - self.common.p[dim[1]],
                    ];
                    let by: [Float; 2] = [
                        py[dim[0]] - self.common.p[dim[0]],
                        py[dim[1]] - self.common.p[dim[1]],
                    ];
                    if !solve_linear_system_2x2(a, bx, self.dudx.get_mut(), self.dvdx.get_mut()) {
                        self.dudx.set(0.0 as Float);
                        self.dvdx.set(0.0 as Float);
                    }
                    if !solve_linear_system_2x2(a, by, self.dudy.get_mut(), self.dvdy.get_mut()) {
                        self.dudy.set(0.0 as Float);
                        self.dvdy.set(0.0 as Float);
                    }
                }
            }
        } else {
            self.dudx.set(0.0 as Float);
            self.dvdx.set(0.0 as Float);
            self.dudy.set(0.0 as Float);
            self.dvdy.set(0.0 as Float);
            self.dpdx.set(Vector3f::default());
            self.dpdy.set(Vector3f::default());
        }
    }
    pub fn le(&self, w: &Vector3f) -> Spectrum {
        if let Some(primitive_raw) = self.primitive {
            let primitive = unsafe { &*primitive_raw };
            if let Some(area_light) = primitive.get_area_light() {
                return area_light.l(&self.common, w);
            }
        }
        Spectrum::default()
    }
}

impl<'a> Interaction for SurfaceInteraction<'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> {
        if let Some(ref bsdf) = self.bsdf {
            Some(bsdf)
        } else {
            None
        }
    }
    fn get_shading_n(&self) -> Option<&Normal3f> {
        Some(&self.shading.n)
    }
    fn get_phase(&self) -> Option<Arc<HenyeyGreenstein>> {
        None
    }
}