Compare commits

..

2 commits

90 changed files with 2098 additions and 1471 deletions

View file

@ -19,7 +19,7 @@ use crate::spectra::{
N_SPECTRUM_SAMPLES, RGBColorSpace, RGBUnboundedSpectrum, SampledSpectrum, SampledWavelengths,
StandardColorSpaces,
};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::hash::hash_buffer;
use crate::utils::math::{
clamp, fast_exp, i0, lerp, log_i0, radians, safe_acos, safe_asin, safe_sqrt, sample_discrete,

View file

@ -8,7 +8,7 @@ use crate::core::geometry::{
use crate::core::scattering::reflect;
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::math::square;
use crate::utils::ptr::{Ptr, Slice};
use crate::utils::ptr::{DevicePtr, Slice};
use crate::utils::sampling::{PiecewiseLinear2D, cosine_hemisphere_pdf, sample_cosine_hemisphere};
use crate::{Float, INV_PI, PI, PI_OVER_2};
use core::any::Any;
@ -28,7 +28,7 @@ pub struct MeasuredBxDFData {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct MeasuredBxDF {
pub brdf: Ptr<MeasuredBxDFData>,
pub brdf: DevicePtr<MeasuredBxDFData>,
pub lambda: SampledWavelengths,
}
@ -38,7 +38,7 @@ unsafe impl Sync for MeasuredBxDF {}
impl MeasuredBxDF {
pub fn new(brdf: &MeasuredBxDFData, lambda: &SampledWavelengths) -> Self {
Self {
brdf: Ptr::from(brdf),
brdf: DevicePtr::from(brdf),
lambda: *lambda,
}
}

View file

@ -5,7 +5,7 @@ use crate::core::film::Film;
use crate::core::geometry::{
Bounds2f, Normal3f, Point2f, Point2i, Point3f, Ray, Vector2f, Vector2i, Vector3f, VectorLike,
};
use crate::core::image::{Image, PixelFormat};
use crate::core::image::{DeviceImage, PixelFormat};
use crate::core::medium::Medium;
use crate::core::pbrt::Float;
use crate::core::sampler::CameraSample;
@ -37,7 +37,7 @@ pub struct RealisticCamera {
base: CameraBase,
focus_distance: Float,
set_aperture_diameter: Float,
aperture_image: *const Image,
aperture_image: *const DeviceImage,
element_interfaces: *const LensElementInterface,
n_elements: usize,
physical_extent: Bounds2f,
@ -51,7 +51,7 @@ impl RealisticCamera {
lens_params: &[Float],
focus_distance: Float,
set_aperture_diameter: Float,
aperture_image: Option<Image>,
aperture_image: Option<DeviceImage>,
) -> Self {
let film_ptr = base.film;
if film_ptr.is_null() {

View file

@ -2,17 +2,17 @@ use crate::Float;
use crate::core::bxdf::{BSDFSample, BxDF, BxDFFlags, BxDFTrait, FArgs, TransportMode};
use crate::core::geometry::{Frame, Normal3f, Point2f, Vector3f, VectorLike};
use crate::spectra::SampledSpectrum;
use crate::utils::Ptr;
use crate::utils::DevicePtr;
#[repr(C)]
#[derive(Copy, Debug, Default)]
pub struct BSDF {
bxdf: Ptr<BxDF>,
bxdf: DevicePtr<BxDF>,
shading_frame: Frame,
}
impl BSDF {
pub fn new(ns: Normal3f, dpdus: Vector3f, bxdf: Ptr<BxDF>) -> Self {
pub fn new(ns: Normal3f, dpdus: Vector3f, bxdf: DevicePtr<BxDF>) -> Self {
Self {
bxdf,
shading_frame: Frame::new(dpdus.normalize(), Vector3f::from(ns)),

View file

@ -3,7 +3,7 @@ use crate::core::geometry::{Frame, Normal3f, Point2f, Point3f, Point3fi, Vector3
use crate::core::interaction::{InteractionBase, ShadingGeom, SurfaceInteraction};
use crate::core::shape::Shape;
use crate::spectra::{N_SPECTRUM_SAMPLES, SampledSpectrum};
use crate::utils::ArenaPtr;
use crate::utils::Ptr;
use crate::utils::math::{catmull_rom_weights, square};
use crate::utils::sampling::sample_catmull_rom_2d;
use crate::utils::{Ptr, ptr::Slice};

View file

@ -10,7 +10,7 @@ use crate::core::pbrt::Float;
use crate::core::sampler::CameraSample;
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::math::lerp;
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
use crate::utils::transform::{AnimatedTransform, Transform};
use enum_dispatch::enum_dispatch;
@ -113,8 +113,8 @@ pub struct CameraBase {
pub min_pos_differential_y: Vector3f,
pub min_dir_differential_x: Vector3f,
pub min_dir_differential_y: Vector3f,
pub film: Ptr<Film>,
pub medium: Ptr<Medium>,
pub film: DevicePtr<Film>,
pub medium: DevicePtr<Medium>,
}
#[enum_dispatch(CameraTrait)]
@ -232,13 +232,13 @@ pub trait CameraTrait {
Point3f::new(0., 0., 0.) + self.base().min_pos_differential_x,
Vector3f::new(0., 0., 1.) + self.base().min_dir_differential_x,
None,
&Ptr::default(),
&DevicePtr::default(),
);
let y_ray = Ray::new(
Point3f::new(0., 0., 0.) + self.base().min_pos_differential_y,
Vector3f::new(0., 0., 1.) + self.base().min_dir_differential_y,
None,
&Ptr::default(),
&DevicePtr::default(),
);
let n_down = Vector3f::from(n_down_z);
let tx = -(n_down.dot(y_ray.o.into())) / n_down.dot(x_ray.d);

View file

@ -4,14 +4,16 @@ use std::ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};
use crate::Float;
use crate::core::geometry::Point2f;
use crate::core::pbrt::{Float, find_interval};
use crate::core::spectrum::Spectrum;
use crate::utils::find_interval;
use crate::utils::math::{SquareMatrix, SquareMatrix3f, clamp, evaluate_polynomial, lerp};
use enum_dispatch::enum_dispatch;
#[derive(Debug, Clone)]
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub struct XYZ {
pub x: Float,
pub y: Float,
@ -24,6 +26,12 @@ impl From<(Float, Float, Float)> for XYZ {
}
}
impl From<[Float; 3]> for XYZ {
fn from(triplet: (Float, Float, Float)) -> Self {
XYZ::new(triplet.0, triplet.1, triplet.2)
}
}
impl<'a> IntoIterator for &'a XYZ {
type Item = &'a Float;
type IntoIter = std::array::IntoIter<&'a Float, 3>;
@ -81,9 +89,9 @@ impl XYZ {
}
}
impl Index<usize> for XYZ {
impl Index<u32> for XYZ {
type Output = Float;
fn index(&self, index: usize) -> &Self::Output {
fn index(&self, index: u32) -> &Self::Output {
debug_assert!(index < 3);
match index {
0 => &self.x,
@ -93,8 +101,8 @@ impl Index<usize> for XYZ {
}
}
impl IndexMut<usize> for XYZ {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
impl IndexMut<u32> for XYZ {
fn index_mut(&mut self, index: u32) -> &mut Self::Output {
debug_assert!(index < 3);
match index {
0 => &mut self.x,
@ -247,7 +255,8 @@ impl fmt::Display for XYZ {
}
}
#[derive(Debug, Default, Copy, Clone)]
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub struct RGB {
pub r: Float,
pub g: Float,
@ -286,7 +295,7 @@ impl RGB {
self.r.min(self.g).min(self.b)
}
pub fn min_component_index(&self) -> usize {
pub fn min_component_index(&self) -> u32 {
if self.r < self.g {
if self.r < self.b { 0 } else { 2 }
} else {
@ -294,7 +303,7 @@ impl RGB {
}
}
pub fn max_component_index(&self) -> usize {
pub fn max_component_index(&self) -> u32 {
if self.r > self.g {
if self.r > self.b { 0 } else { 2 }
} else {
@ -315,9 +324,9 @@ impl RGB {
}
}
impl Index<usize> for RGB {
impl Index<u32> for RGB {
type Output = Float;
fn index(&self, index: usize) -> &Self::Output {
fn index(&self, index: u32) -> &Self::Output {
debug_assert!(index < 3);
match index {
0 => &self.r,
@ -327,8 +336,8 @@ impl Index<usize> for RGB {
}
}
impl IndexMut<usize> for RGB {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
impl IndexMut<u32> for RGB {
fn index_mut(&mut self, index: u32) -> &mut Self::Output {
debug_assert!(index < 3);
match index {
0 => &mut self.r,
@ -658,7 +667,7 @@ impl ColorEncodingTrait for SRGBEncoding {
fn to_linear(&self, vin: &[u8], vout: &mut [Float]) {
for (i, &v) in vin.iter().enumerate() {
vout[i] = SRGB_TO_LINEAR_LUT[v as usize];
vout[i] = SRGB_TO_LINEAR_LUT[v as u32];
}
}
@ -961,7 +970,7 @@ const SRGB_TO_LINEAR_LUT: [Float; 256] = [
1.0000000000,
];
pub const RES: usize = 64;
pub const RES: u32 = 64;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
@ -1007,9 +1016,9 @@ unsafe impl Sync for RGBToSpectrumTable {}
impl RGBToSpectrumTable {
#[inline(always)]
fn get_coeffs(&self, bucket: usize, z: usize, y: usize, x: usize) -> Coeffs {
fn get_coeffs(&self, bucket: u32, z: u32, y: u32, x: u32) -> Coeffs {
let offset = bucket * (RES * RES * RES) + z * (RES * RES) + y * (RES) + x;
unsafe { *self.coeffs.add(offset) }
unsafe { *self.coeffs.add(offset as usize) }
}
pub fn evaluate(&self, rgb: RGB) -> RGBSigmoidPolynomial {
@ -1045,25 +1054,25 @@ impl RGBToSpectrumTable {
let x = coord_a / z;
let y = coord_b / z;
let z_nodes_slice = unsafe { core::slice::from_raw_parts(self.z_nodes, RES) };
let zi = find_interval(RES, |i| z_nodes_slice[i] < z);
let z_nodes_slice = unsafe { core::slice::from_raw_parts(self.z_nodes, RES as usize) };
let zi = find_interval(RES, |i| z_nodes_slice[i as usize] < z) as usize;
let dz = (z - z_nodes_slice[zi]) / (z_nodes_slice[zi + 1] - z_nodes_slice[zi]);
let x_float = x * (RES - 1) as Float;
let xi = (x_float as usize).min(RES - 2);
let xi = (x_float as u32).min(RES - 2);
let dx = x_float - xi as Float;
let y_float = y * (RES - 1) as Float;
let yi = (y_float as usize).min(RES - 2);
let yi = (y_float as u32).min(RES - 2);
let dy = y_float - yi as Float;
let c000 = self.get_coeffs(c_idx, zi, yi, xi);
let c001 = self.get_coeffs(c_idx, zi, yi, xi + 1);
let c010 = self.get_coeffs(c_idx, zi, yi + 1, xi);
let c011 = self.get_coeffs(c_idx, zi, yi + 1, xi + 1);
let c100 = self.get_coeffs(c_idx, zi + 1, yi, xi);
let c101 = self.get_coeffs(c_idx, zi + 1, yi, xi + 1);
let c110 = self.get_coeffs(c_idx, zi + 1, yi + 1, xi);
let c111 = self.get_coeffs(c_idx, zi + 1, yi + 1, xi + 1);
let c000 = self.get_coeffs(c_idx, zi as u32, yi, xi);
let c001 = self.get_coeffs(c_idx, zi as u32, yi, xi + 1);
let c010 = self.get_coeffs(c_idx, zi as u32, yi + 1, xi);
let c011 = self.get_coeffs(c_idx, zi as u32, yi + 1, xi + 1);
let c100 = self.get_coeffs(c_idx, zi as u32 + 1, yi, xi);
let c101 = self.get_coeffs(c_idx, zi as u32 + 1, yi, xi + 1);
let c110 = self.get_coeffs(c_idx, zi as u32 + 1, yi + 1, xi);
let c111 = self.get_coeffs(c_idx, zi as u32 + 1, yi + 1, xi + 1);
let c00 = lerp(dx, c000, c001);
let c01 = lerp(dx, c010, c011);
let c10 = lerp(dx, c100, c101);

View file

@ -5,7 +5,7 @@ use crate::core::geometry::{
Bounds2f, Bounds2fi, Bounds2i, Normal3f, Point2f, Point2i, Point3f, Tuple, Vector2f, Vector2fi,
Vector2i, Vector3f,
};
use crate::core::image::{Image, PixelFormat};
use crate::core::image::{DeviceImage, PixelFormat};
use crate::core::interaction::SurfaceInteraction;
use crate::core::pbrt::Float;
use crate::core::spectrum::{Spectrum, SpectrumTrait, StandardSpectra};
@ -17,7 +17,7 @@ use crate::utils::AtomicFloat;
use crate::utils::containers::Array2D;
use crate::utils::math::linear_least_squares;
use crate::utils::math::{SquareMatrix, wrap_equal_area_square};
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
use crate::utils::sampling::VarianceEstimator;
use crate::utils::transform::AnimatedTransform;
@ -472,7 +472,7 @@ impl PixelSensor {
pub fn new_with_white_balance(
output_colorspace: &RGBColorSpace,
sensor_illum: Ptr<Spectrum>,
sensor_illum: DevicePtr<Spectrum>,
imaging_ratio: Float,
spectra: *const StandardSpectra,
) -> Self {

View file

@ -3,7 +3,7 @@ use crate::core::pbrt::Float;
use crate::filters::*;
use crate::utils::containers::Array2D;
use crate::utils::math::{gaussian, gaussian_integral, lerp, sample_tent, windowed_sinc};
use crate::utils::sampling::PiecewiseConstant2D;
use crate::utils::sampling::DevicePiecewiseConstant2D;
use enum_dispatch::enum_dispatch;
pub struct FilterSample {
@ -15,7 +15,7 @@ pub struct FilterSample {
#[derive(Clone, Debug, Copy)]
pub struct FilterSampler {
pub domain: Bounds2f,
pub distrib: PiecewiseConstant2D,
pub distrib: DevicePiecewiseConstant2D,
pub f: Array2D<Float>,
}
@ -43,7 +43,7 @@ impl FilterSampler {
f[(x as i32, y as i32)] = func(p);
}
}
let distrib = PiecewiseConstant2D::new_with_bounds(&f, domain);
let distrib = DevicePiecewiseConstant2D::new_with_bounds(&f, domain);
Self { domain, f, distrib }
}

View file

@ -2,7 +2,7 @@ use super::{Normal3f, Point3f, Point3fi, Vector3f, VectorLike};
use crate::core::medium::Medium;
use crate::core::pbrt::Float;
use crate::utils::math::{next_float_down, next_float_up};
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
@ -10,7 +10,7 @@ pub struct Ray {
pub o: Point3f,
pub d: Vector3f,
pub time: Float,
pub medium: Ptr<Medium>,
pub medium: DevicePtr<Medium>,
// We do this instead of creating a trait for Rayable or some gnarly thing like that
pub has_differentials: bool,
pub differential: RayDifferential,
@ -21,7 +21,7 @@ impl Default for Ray {
Self {
o: Point3f::new(0.0, 0.0, 0.0),
d: Vector3f::new(0.0, 0.0, 0.0),
medium: Ptr::null(),
medium: DevicePtr::null(),
time: 0.0,
has_differentials: false,
differential: RayDifferential::default(),
@ -35,7 +35,7 @@ impl Ray {
o,
d,
time: time.unwrap_or_else(|| Self::default().time),
medium: Ptr::from(medium),
medium: DevicePtr::from(medium),
..Self::default()
}
}
@ -71,7 +71,7 @@ impl Ray {
o: origin,
d,
time,
medium: Ptr::null(),
medium: DevicePtr::null(),
has_differentials: false,
differential: RayDifferential::default(),
}
@ -99,7 +99,7 @@ impl Ray {
o: pf,
d,
time,
medium: Ptr::null(),
medium: DevicePtr::null(),
has_differentials: false,
differential: RayDifferential::default(),
}

View file

@ -66,87 +66,75 @@ pub enum Pixels {
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Image {
#[derive(Clone, Copy, Debug)]
pub struct ImageBase {
pub format: PixelFormat,
pub pixels: Pixels,
pub encoding: ColorEncoding,
pub resolution: Point2i,
pub n_channels: i32,
}
impl Image {
pub fn resolution(&self) -> Point2i {
self.resolution
}
pub fn is_valid(&self) -> bool {
self.resolution.x() > 0. && self.resolution.y() > 0.
}
pub fn format(&self) -> PixelFormat {
self.format
}
pub fn n_channels(&self) -> i32 {
self.n_channels
}
pub fn pixel_offset(&self, p: Point2i) -> u32 {
let width = self.resolution.x() as u32;
let idx = p.y() as u32 * width + p.x() as u32;
idx * (self.n_channels as u32)
}
pub fn get_channel_with_wrap(&self, p: Point2i, c: i32, wrap_mode: WrapMode2D) -> Float {
if !self.remap_pixel_coords(&mut p, wrap_mode) {
return 0.;
}
let offset = self.pixel_offset(p) + c;
unsafe {
match self.pixels {
Pixels::U8(ptr) => {
let raw_u8 = *ptr.add(offset);
self.encoding.to_linear_scalar(raw_u8)
}
Pixels::F16(ptr) => {
let half_bits = *ptr.add(offset);
f16_to_f32(f16::from_bits(half_bits))
}
Pixels::F32(ptr) => *ptr.add(offset),
}
}
}
pub fn get_channel(&self, p: Point2i, c: i32) -> Float {
self.get_channel_with_wrap(p, c, WrapMode::Clamp.into())
}
impl ImageBase {
pub fn remap_pixel_coords(&self, p: &mut Point2i, wrap_mode: WrapMode2D) -> bool {
let resolution = self.resolution;
for i in 0..2 {
if p[i] >= 0 && p[i] < self.resolution[i] {
if p[i] >= 0 && p[i] < resolution[i] {
continue;
}
match wrap_mode.uv[i] {
WrapMode::Black => return false,
WrapMode::Clamp => p[i] = p[i].clamp(0, self.resolution[i] - 1),
WrapMode::Repeat => p[i] = p[i].rem_euclid(self.resolution[i]),
WrapMode::Clamp => p[i] = p[i].clamp(0, resolution[i] - 1),
WrapMode::Repeat => p[i] = p[i].rem_euclid(resolution[i]),
WrapMode::OctahedralSphere => {
p[i] = p[i].clamp(0, self.resolution[i] - 1);
p[i] = p[i].clamp(0, resolution[i] - 1);
}
}
}
true
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct DeviceImage {
pub base: ImageBase,
pub pixels: Pixels,
}
impl DeviceImage {
pub fn base(&self) -> ImageBase {
self.base
}
pub fn resolution(&self) -> Point2i {
self.base.resolution
}
pub fn is_valid(&self) -> bool {
self.resolution().x() > 0 && self.resolution().y() > 0
}
pub fn format(&self) -> PixelFormat {
self.base().format
}
pub fn n_channels(&self) -> i32 {
self.base().n_channels
}
pub fn pixel_offset(&self, p: Point2i) -> u32 {
let width = self.resolution().x() as u32;
let idx = p.y() as u32 * width + p.x() as u32;
idx * (self.n_channels() as u32)
}
pub fn bilerp_channel(&self, p: Point2f, c: i32) -> Float {
self.bilerp_channel_with_wrap(p, c, WrapMode::Clamp.into())
}
pub fn bilerp_channel_with_wrap(&self, p: Point2f, c: i32, wrap_mode: WrapMode2D) -> Float {
let x = p.x() * self.resolution.x() as Float - 0.5;
let y = p.y() * self.resolution.y() as Float - 0.5;
let x = p.x() * self.resolution().x() as Float - 0.5;
let y = p.y() * self.resolution().y() as Float - 0.5;
let xi = x.floor() as i32;
let yi = y.floor() as i32;
let dx = x - xi as Float;
@ -157,22 +145,51 @@ impl Image {
let v11 = self.get_channel_with_wrap(Point2i::new(xi + 1, yi + 1), c, wrap_mode);
lerp(dy, lerp(dx, v00, v10), lerp(dx, v01, v11))
}
}
pub fn lookup_nearest_channel_with_wrap(
&self,
p: Point2f,
c: i32,
wrap_mode: WrapMode2D,
) -> Float {
pub trait ImageAccess {
fn get_channel_with_wrap(&self, p: Point2i, c: i32, wrap_mode: WrapMode2D) -> Float;
fn get_channel(&self, p: Point2i, c: i32) -> Float;
fn lookup_nearest_channel_with_wrap(&self, p: Point2f, c: i32, wrap_mode: WrapMode2D) -> Float;
fn lookup_nearest_channel(&self, p: Point2f, c: i32) -> Float;
}
impl ImageAccess for DeviceImage {
fn get_channel_with_wrap(&self, mut p: Point2i, c: i32, wrap_mode: WrapMode2D) -> Float {
if !self.base.remap_pixel_coords(&mut p, wrap_mode) {
return 0.;
}
let offset = self.pixel_offset(p) + c as u32;
unsafe {
match self.pixels {
Pixels::U8(ptr) => {
let raw_u8 = *ptr.add(offset as usize);
self.base().encoding.to_linear_scalar(raw_u8)
}
Pixels::F16(ptr) => {
let half_bits: u16 = *ptr.add(offset as usize) as u16;
f16_to_f32(half_bits)
}
Pixels::F32(ptr) => *ptr.add(offset as usize),
}
}
}
fn get_channel(&self, p: Point2i, c: i32) -> Float {
self.get_channel_with_wrap(p, c, WrapMode::Clamp.into())
}
fn lookup_nearest_channel_with_wrap(&self, p: Point2f, c: i32, wrap_mode: WrapMode2D) -> Float {
let pi = Point2i::new(
p.x() as i32 * self.resolution.x(),
p.y() as i32 * self.resolution.y(),
p.x() as i32 * self.resolution().x(),
p.y() as i32 * self.resolution().y(),
);
self.get_channel_with_wrap(pi, c, wrap_mode)
}
pub fn lookup_nearest_channel(&self, p: Point2f, c: i32) -> Float {
fn lookup_nearest_channel(&self, p: Point2f, c: i32) -> Float {
self.lookup_nearest_channel_with_wrap(p, c, WrapMode::Clamp.into())
}
}

View file

@ -5,7 +5,7 @@ use crate::core::camera::{Camera, CameraTrait};
use crate::core::geometry::{
Normal3f, Point2f, Point3f, Point3fi, Ray, RayDifferential, Vector3f, VectorLike,
};
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::light::{Light, LightTrait};
use crate::core::material::{
Material, MaterialEvalContext, MaterialTrait, NormalBumpEvalContext, bump_map, normal_map,
@ -413,7 +413,7 @@ impl SurfaceInteraction {
&mut self,
tex_eval: &UniversalTextureEvaluator,
displacement: Ptr<GPUFloatTexture>,
normal_image: Ptr<Image>,
normal_image: Ptr<DeviceImage>,
) {
let ctx = NormalBumpEvalContext::from(&*self);
let (dpdu, dpdv) = if !displacement.is_null() {

View file

@ -3,7 +3,7 @@ use crate::core::geometry::{
Bounds2f, Bounds3f, DirectionCone, Normal3f, Point2f, Point2i, Point3f, Point3fi, Ray,
Vector3f, VectorLike, cos_theta,
};
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::interaction::{
Interaction, InteractionBase, InteractionTrait, MediumInteraction, SimpleInteraction,
SurfaceInteraction,
@ -17,8 +17,8 @@ use crate::spectra::{
};
use crate::utils::Transform;
use crate::utils::math::{equal_area_sphere_to_square, radians, safe_sqrt, smooth_step, square};
use crate::utils::ptr::Ptr;
use crate::utils::sampling::PiecewiseConstant2D;
use crate::utils::ptr::{DevicePtr, Ptr};
use crate::utils::sampling::DevicePiecewiseConstant2D;
use crate::{Float, PI};
use bitflags::bitflags;
@ -340,9 +340,9 @@ pub enum Light {
DiffuseArea(DiffuseAreaLight),
Distant(DistantLight),
Goniometric(GoniometricLight),
InfiniteUniform(InfiniteUniformLight),
InfiniteImage(InfiniteImageLight),
InfinitePortal(InfinitePortalLight),
InfiniteUniform(UniformInfiniteLight),
InfiniteImage(ImageInfiniteLight),
InfinitePortal(PortalInfiniteLight),
Point(PointLight),
Projection(ProjectionLight),
Spot(SpotLight),

View file

@ -10,7 +10,7 @@ use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::geometry::{Frame, Normal3f, Point2f, Point3f, Vector2f, Vector3f, VectorLike};
use crate::core::image::{Image, WrapMode, WrapMode2D};
use crate::core::image::{DeviceImage, WrapMode, WrapMode2D};
use crate::core::interaction::{Interaction, InteractionTrait, ShadingGeom, SurfaceInteraction};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
@ -19,7 +19,7 @@ use crate::core::texture::{
};
use crate::materials::*;
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::hash::hash_float;
use crate::utils::math::clamp;
@ -103,7 +103,7 @@ impl From<&NormalBumpEvalContext> for TextureEvalContext {
}
}
pub fn normal_map(normal_map: &Image, ctx: &NormalBumpEvalContext) -> (Vector3f, Vector3f) {
pub fn normal_map(normal_map: &DeviceImage, ctx: &NormalBumpEvalContext) -> (Vector3f, Vector3f) {
let wrap = WrapMode2D::from(WrapMode::Repeat);
let uv = Point2f::new(ctx.uv[0], 1. - ctx.uv[1]);
let r = normal_map.bilerp_channel_with_wrap(uv, 0, wrap);
@ -125,7 +125,7 @@ pub fn bump_map<T: TextureEvaluator>(
displacement: &GPUFloatTexture,
ctx: &NormalBumpEvalContext,
) -> (Vector3f, Vector3f) {
debug_assert!(tex_eval.can_evaluate(&[Ptr::from(displacement)], &[]));
debug_assert!(tex_eval.can_evaluate(&[DevicePtr::from(displacement)], &[]));
let mut du = 0.5 * (ctx.dudx.abs() + ctx.dudy.abs());
if du == 0.0 {
du = 0.0005;
@ -173,8 +173,8 @@ pub trait MaterialTrait {
) -> Option<BSSRDF>;
fn can_evaluate_textures(&self, tex_eval: &dyn TextureEvaluator) -> bool;
fn get_normal_map(&self) -> Option<&Image>;
fn get_displacement(&self) -> Ptr<GPUFloatTexture>;
fn get_normal_map(&self) -> Option<&DeviceImage>;
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture>;
fn has_subsurface_scattering(&self) -> bool;
}

View file

@ -12,7 +12,7 @@ use crate::spectra::{
};
use crate::utils::containers::SampledGrid;
use crate::utils::math::{clamp, square};
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
use crate::utils::rng::Rng;
use crate::utils::transform::Transform;
@ -829,8 +829,8 @@ impl MediumTrait for NanoVDBMedium {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct MediumInterface {
pub inside: Ptr<Medium>,
pub outside: Ptr<Medium>,
pub inside: DevicePtr<Medium>,
pub outside: DevicePtr<Medium>,
}
unsafe impl Send for MediumInterface {}
@ -839,17 +839,32 @@ unsafe impl Sync for MediumInterface {}
impl Default for MediumInterface {
fn default() -> Self {
Self {
inside: Ptr::null(),
outside: Ptr::null(),
inside: DevicePtr::null(),
outside: DevicePtr::null(),
}
}
}
impl From<Medium> for MediumInterface {
fn from(medium: Medium) -> Self {
Self {
inside: DevicePtr::from(&medium),
outside: DevicePtr::from(&medium),
}
}
}
impl From<&Medium> for MediumInterface {
fn from(medium: &Medium) -> Self {
Self::from(medium.clone())
}
}
impl MediumInterface {
pub fn new(inside: &Medium, outside: &Medium) -> Self {
Self {
inside: Ptr::from(inside),
outside: Ptr::from(outside),
inside: DevicePtr::from(inside),
outside: DevicePtr::from(outside),
}
}

View file

@ -5,8 +5,50 @@ use std::hash::Hash;
use std::ops::{Add, Mul};
use std::sync::{Arc, Mutex};
use crate::core::image::DeviceImage;
use crate::core::light::LightTrait;
use crate::core::shape::Shape;
use crate::core::texture::GPUFloatTexture;
use crate::lights::*;
use crate::spectra::{DenselySampledSpectrum, RGBColorSpace};
use crate::utils::Ptr;
pub type Float = f32;
// #[derive(Copy, Clone, Debug)]
// pub struct Host;
//
// #[derive(Copy, Clone, Debug)]
// pub struct Device;
//
// pub trait Backend: Copy + Clone + 'static {
// type ShapeRef: Copy + Clone;
// type TextureRef: Copy + Clone;
// type ImageRef: Copy + Clone;
// type DenseSpectrumRef = Ptr<DenselySampledSpectrum>;
// type ColorSpaceRef = Ptr<RGBColorSpace>;
// type DiffuseLight: LightTrait;
// type PointLight: LightTrait;
// type UniformInfiniteLight: LightTrait;
// type PortalInfiniteLight: LightTrait;
// type ImageInfiniteLight: LightTrait;
// type SpotLight: LightTrait;
// }
//
// impl Backend for Device {
// type ShapeRef = Ptr<Shape>;
// type TextureRef = Ptr<GPUFloatTexture>;
// type ColorSpaceRef = Ptr<RGBColorSpace>;
// type DenseSpectrumRef = Ptr<DenselySampledSpectrum>;
// type ImageRef = Ptr<DeviceImage>;
// type DiffuseLight = Ptr<DiffuseAreaLight<Device>>;
// type PointLight = Ptr<PointLight<Device>>;
// type UniformInfiniteLight = Ptr<UniformInfiniteLight<Device>>;
// type PortalInfiniteLight = Ptr<PortalInfiniteLight<Device>>;
// type ImageInfiniteLight = Ptr<ImageInfiniteLight<Device>>;
// type SpotLight = Ptr<SpotLight<Device>>;
// }
//
#[cfg(not(feature = "use_f64"))]
pub type FloatBits = u32;
@ -100,36 +142,11 @@ pub const PI_OVER_2: Float = 1.570_796_326_794_896_619_23;
pub const PI_OVER_4: Float = 0.785_398_163_397_448_309_61;
pub const SQRT_2: Float = 1.414_213_562_373_095_048_80;
#[inline]
pub fn find_interval<F>(sz: u32, pred: F) -> u32
where
F: Fn(u32) -> bool,
{
let mut first = 0;
let mut len = sz;
while len > 0 {
let half = len >> 1;
let middle = first + half;
if pred(middle) {
first = middle + 1;
len -= half + 1;
} else {
len = half;
}
}
let ret = (first as i32 - 1).max(0) as u32;
ret.min(sz.saturating_sub(2))
}
#[inline]
pub fn gamma(n: i32) -> Float {
n as Float * MACHINE_EPSILON / (1. - n as Float * MACHINE_EPSILON)
}
// Define the static counters. These are thread-safe.
pub static RARE_EVENT_TOTAL_CALLS: AtomicU64 = AtomicU64::new(0);
pub static RARE_EVENT_CONDITION_MET: AtomicU64 = AtomicU64::new(0);

View file

@ -7,7 +7,7 @@ use crate::core::medium::{Medium, MediumInterface};
use crate::core::pbrt::Float;
use crate::core::shape::{Shape, ShapeIntersection, ShapeTrait};
use crate::core::texture::{GPUFloatTexture, TextureEvalContext};
use crate::utils::ArenaPtr;
use crate::utils::Ptr;
use crate::utils::hash::hash_float;
use crate::utils::transform::{AnimatedTransform, Transform};
@ -88,13 +88,13 @@ impl PrimitiveTrait for GeometricPrimitive {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct SimplePrimitive {
shape: ArenaPtr<Shape>,
material: ArenaPtr<Material>,
shape: Ptr<Shape>,
material: Ptr<Material>,
}
#[derive(Debug, Clone)]
pub struct TransformedPrimitive {
pub primitive: ArenaPtr<Primitive>,
pub primitive: Ptr<Primitive>,
pub render_from_primitive: Transform,
}
@ -129,7 +129,7 @@ impl PrimitiveTrait for TransformedPrimitive {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct AnimatedPrimitive {
primitive: ArenaPtr<Primitive>,
primitive: Ptr<Primitive>,
render_from_primitive: AnimatedTransform,
}
@ -164,7 +164,7 @@ impl PrimitiveTrait for AnimatedPrimitive {
#[derive(Debug, Clone, Copy)]
pub struct BVHAggregatePrimitive {
max_prims_in_node: u32,
primitives: *const ArenaPtr<Primitive>,
primitives: *const Ptr<Primitive>,
nodes: *const LinearBVHNode,
}

View file

@ -1,7 +1,7 @@
use crate::core::filter::FilterTrait;
use crate::core::geometry::{Bounds2f, Point2f, Point2i, Vector2f};
use crate::core::options::{PBRTOptions, get_options};
use crate::core::pbrt::{Float, ONE_MINUS_EPSILON, PI, PI_OVER_2, PI_OVER_4, find_interval};
use crate::core::pbrt::{Float, ONE_MINUS_EPSILON, PI, PI_OVER_2, PI_OVER_4};
use crate::utils::Ptr;
use crate::utils::containers::Array2D;
use crate::utils::math::{

View file

@ -10,7 +10,7 @@ use crate::core::material::Material;
use crate::core::medium::{Medium, MediumInterface};
use crate::shapes::*;
use crate::utils::math::{next_float_down, next_float_up};
use crate::utils::{Ptr, Transform};
use crate::utils::{DevicePtr, Transform};
use crate::{Float, PI};
use enum_dispatch::enum_dispatch;
@ -118,7 +118,12 @@ impl ShapeSampleContext {
}
pub fn spawn_ray(&self, w: Vector3f) -> Ray {
Ray::new(self.offset_ray_origin(w), w, Some(self.time), &Ptr::null())
Ray::new(
self.offset_ray_origin(w),
w,
Some(self.time),
&DevicePtr::null(),
)
}
}

View file

@ -9,7 +9,7 @@ use crate::spectra::{
SampledWavelengths,
};
use crate::textures::*;
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::Transform;
use crate::utils::math::square;
use crate::{Float, INV_2_PI, INV_PI, PI};
@ -428,8 +428,8 @@ pub trait TextureEvaluator: Send + Sync {
fn can_evaluate(
&self,
_ftex: &[Ptr<GPUFloatTexture>],
_stex: &[Ptr<GPUSpectrumTexture>],
_ftex: &[DevicePtr<GPUFloatTexture>],
_stex: &[DevicePtr<GPUSpectrumTexture>],
) -> bool;
}
@ -453,8 +453,8 @@ impl TextureEvaluator for UniversalTextureEvaluator {
fn can_evaluate(
&self,
_float_textures: &[Ptr<GPUFloatTexture>],
_spectrum_textures: &[Ptr<GPUSpectrumTexture>],
_float_textures: &[DevicePtr<GPUFloatTexture>],
_spectrum_textures: &[DevicePtr<GPUSpectrumTexture>],
) -> bool {
true
}

View file

@ -1,6 +1,7 @@
#![allow(unused_imports, dead_code)]
#![feature(float_erf)]
#![feature(f16)]
#![feature(associated_type_defaults)]
pub mod bxdfs;
pub mod cameras;

View file

@ -1,7 +1,6 @@
use crate::PI;
use crate::core::color::{RGB, XYZ};
use crate::core::geometry::*;
use crate::core::image::Image;
use crate::core::image::{DeviceImage, ImageAccess};
use crate::core::interaction::{
Interaction, InteractionTrait, MediumInteraction, SurfaceInteraction,
};
@ -9,7 +8,6 @@ use crate::core::light::{
LightBase, LightBounds, LightLiSample, LightSampleContext, LightTrait, LightType,
};
use crate::core::medium::MediumInterface;
use crate::core::pbrt::Float;
use crate::core::shape::{Shape, ShapeSampleContext, ShapeTrait};
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::core::texture::{
@ -18,6 +16,7 @@ use crate::core::texture::{
use crate::spectra::*;
use crate::utils::hash::hash_float;
use crate::utils::{Ptr, Transform};
use crate::{Float, PI};
#[repr(C)]
#[derive(Clone, Debug, Copy)]
@ -25,9 +24,9 @@ pub struct DiffuseAreaLight {
pub base: LightBase,
pub shape: Ptr<Shape>,
pub alpha: Ptr<GPUFloatTexture>,
pub image_color_space: Ptr<RGBColorSpace>,
pub colorspace: Ptr<RGBColorSpace>,
pub lemit: Ptr<DenselySampledSpectrum>,
pub image: Ptr<Image>,
pub image: Ptr<DeviceImage>,
pub area: Float,
pub two_sided: bool,
pub scale: Float,
@ -175,8 +174,8 @@ impl LightTrait for DiffuseAreaLight {
fn bounds(&self) -> Option<LightBounds> {
let mut phi = 0.;
if !self.image.is_null() {
for y in 0..self.image.resolution.y() {
for x in 0..self.image.resolution.x() {
for y in 0..self.image.base.resolution.y() {
for x in 0..self.image.base.resolution.x() {
for c in 0..3 {
phi += self.image.get_channel(Point2i::new(x, y), c);
}

View file

@ -5,7 +5,7 @@ use crate::core::interaction::{Interaction, InteractionBase, SimpleInteraction};
use crate::core::light::{LightBase, LightBounds, LightLiSample, LightSampleContext, LightTrait};
use crate::core::spectrum::SpectrumTrait;
use crate::spectra::{DenselySampledSpectrum, SampledSpectrum, SampledWavelengths};
use crate::utils::{ArenaPtr, Ptr};
use crate::utils::Ptr;
use crate::{Float, PI};
#[repr(C)]

View file

@ -1,5 +1,5 @@
use crate::core::geometry::{Bounds3f, Normal3f, Point2f, Point2i, Point3f, Ray, Vector3f};
use crate::core::image::Image;
use crate::core::image::{DeviceImage, ImageAccess};
use crate::core::light::{
LightBase, LightBounds, LightLiSample, LightSampleContext, LightTrait, LightType,
};
@ -7,17 +7,17 @@ use crate::core::medium::MediumInterface;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::spectra::{DenselySampledSpectrum, SampledSpectrum, SampledWavelengths};
use crate::utils::math::equal_area_sphere_to_square;
use crate::utils::sampling::PiecewiseConstant2D;
use crate::utils::sampling::DevicePiecewiseConstant2D;
use crate::utils::{Ptr, Transform};
use crate::{Float, PI};
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
pub struct GoniometricLight {
pub base: LightBase,
iemit: DenselySampledSpectrum,
scale: Float,
image: Ptr<Image>,
distrib: Ptr<PiecewiseConstant2D>,
pub iemit: DenselySampledSpectrum,
pub scale: Float,
pub image: Ptr<DeviceImage>,
pub distrib: Ptr<DevicePiecewiseConstant2D>,
}
impl GoniometricLight {
@ -77,13 +77,14 @@ impl LightTrait for GoniometricLight {
#[cfg(not(target_os = "cuda"))]
fn phi(&self, lambda: SampledWavelengths) -> SampledSpectrum {
let resolution = self.image.resolution();
let mut sum_y = 0.;
for y in 0..self.image.resolution.y() {
for x in 0..self.image.resolution.x() {
for y in 0..resolution.y() {
for x in 0..resolution.x() {
sum_y += self.image.get_channel(Point2i::new(x, y), 0);
}
}
self.scale * self.iemit.sample(&lambda) * 4. * PI * sum_y
/ (self.image.resolution.x() * self.image.resolution.y()) as Float
/ (resolution.x() * resolution.y()) as Float
}
}

View file

@ -1,23 +1,10 @@
use crate::{
core::{
geometry::{Frame, VectorLike},
interaction::InteractionBase,
},
spectra::{RGBColorSpace, RGBIlluminantSpectrum},
utils::{
math::{clamp, equal_area_sphere_to_square, equal_area_square_to_sphere, square},
sampling::{
AliasTable, PiecewiseConstant2D, WindowedPiecewiseConstant2D, sample_uniform_sphere,
uniform_sphere_pdf,
},
},
};
use crate::core::color::RGB;
use crate::core::geometry::{
Bounds2f, Bounds3f, Normal3f, Point2f, Point2i, Point3f, Ray, Vector2f, Vector3f,
};
use crate::core::image::{Image, PixelFormat, WrapMode};
use crate::core::geometry::{Frame, VectorLike};
use crate::core::image::{DeviceImage, ImageAccess, PixelFormat, WrapMode};
use crate::core::interaction::InteractionBase;
use crate::core::interaction::{Interaction, SimpleInteraction};
use crate::core::light::{
LightBase, LightBounds, LightLiSample, LightSampleContext, LightTrait, LightType,
@ -25,14 +12,19 @@ use crate::core::light::{
use crate::core::medium::{Medium, MediumInterface};
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::spectra::{DenselySampledSpectrum, SampledSpectrum, SampledWavelengths};
use crate::utils::Transform;
use crate::utils::ptr::Ptr;
use crate::spectra::{RGBColorSpace, RGBIlluminantSpectrum};
use crate::utils::math::{clamp, equal_area_sphere_to_square, equal_area_square_to_sphere, square};
use crate::utils::sampling::{
AliasTable, DevicePiecewiseConstant2D, WindowedPiecewiseConstant2D, sample_uniform_sphere,
uniform_sphere_pdf,
};
use crate::utils::{Ptr, Transform};
use crate::{Float, PI};
use std::sync::Arc;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct InfiniteUniformLight {
pub struct UniformInfiniteLight {
pub base: LightBase,
pub lemit: Ptr<DenselySampledSpectrum>,
pub scale: Float,
@ -40,10 +32,10 @@ pub struct InfiniteUniformLight {
pub scene_radius: Float,
}
unsafe impl Send for InfiniteUniformLight {}
unsafe impl Sync for InfiniteUniformLight {}
unsafe impl Send for UniformInfiniteLight {}
unsafe impl Sync for UniformInfiniteLight {}
impl LightTrait for InfiniteUniformLight {
impl LightTrait for UniformInfiniteLight {
fn base(&self) -> &LightBase {
&self.base
}
@ -120,21 +112,21 @@ impl LightTrait for InfiniteUniformLight {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct InfiniteImageLight {
pub struct ImageInfiniteLight {
pub base: LightBase,
pub image: Ptr<Image>,
pub image: Ptr<DeviceImage>,
pub image_color_space: Ptr<RGBColorSpace>,
pub distrib: Ptr<PiecewiseConstant2D>,
pub compensated_distrib: Ptr<PiecewiseConstant2D>,
pub distrib: Ptr<DevicePiecewiseConstant2D>,
pub compensated_distrib: Ptr<DevicePiecewiseConstant2D>,
pub scale: Float,
pub scene_radius: Float,
pub scene_center: Point3f,
}
unsafe impl Send for InfiniteImageLight {}
unsafe impl Sync for InfiniteImageLight {}
unsafe impl Send for ImageInfiniteLight {}
unsafe impl Sync for ImageInfiniteLight {}
impl InfiniteImageLight {
impl ImageInfiniteLight {
fn image_le(&self, uv: Point2f, lambda: &SampledWavelengths) -> SampledSpectrum {
let mut rgb = RGB::default();
for c in 0..3 {
@ -149,7 +141,7 @@ impl InfiniteImageLight {
}
}
impl LightTrait for InfiniteImageLight {
impl LightTrait for ImageInfiniteLight {
fn base(&self) -> &LightBase {
&self.base
}
@ -256,9 +248,9 @@ impl LightTrait for InfiniteImageLight {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct InfinitePortalLight {
pub struct PortalInfiniteLight {
pub base: LightBase,
pub image: Ptr<Image>,
pub image: Ptr<DeviceImage>,
pub image_color_space: Ptr<RGBColorSpace>,
pub scale: Float,
pub portal: [Point3f; 4],
@ -268,7 +260,7 @@ pub struct InfinitePortalLight {
pub scene_radius: Float,
}
impl InfinitePortalLight {
impl PortalInfiniteLight {
pub fn image_lookup(&self, uv: Point2f, lambda: &SampledWavelengths) -> SampledSpectrum {
let mut rgb = RGB::default();
for c in 0..3 {
@ -325,7 +317,7 @@ impl InfinitePortalLight {
}
}
impl LightTrait for InfinitePortalLight {
impl LightTrait for PortalInfiniteLight {
fn base(&self) -> &LightBase {
&self.base
}

View file

@ -10,7 +10,7 @@ pub mod spot;
pub use diffuse::DiffuseAreaLight;
pub use distant::DistantLight;
pub use goniometric::GoniometricLight;
pub use infinite::{InfiniteImageLight, InfinitePortalLight, InfiniteUniformLight};
pub use infinite::{ImageInfiniteLight, PortalInfiniteLight, UniformInfiniteLight};
pub use point::PointLight;
pub use projection::ProjectionLight;
pub use spot::SpotLight;

View file

@ -7,7 +7,7 @@ use crate::core::light::{
};
use crate::core::spectrum::SpectrumTrait;
use crate::spectra::{DenselySampledSpectrum, SampledSpectrum, SampledWavelengths};
use crate::utils::ptr::Ptr;
use crate::utils::Ptr;
use crate::{Float, PI};
#[repr(C)]

View file

@ -3,7 +3,7 @@ use crate::core::color::RGB;
use crate::core::geometry::{
Bounds2f, Bounds3f, Normal3f, Point2f, Point2i, Point3f, Ray, Vector3f, VectorLike, cos_theta,
};
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::light::{
LightBase, LightBounds, LightLiSample, LightSampleContext, LightTrait, LightType,
};
@ -11,10 +11,9 @@ use crate::core::medium::MediumInterface;
use crate::core::spectrum::SpectrumTrait;
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::math::{radians, square};
use crate::utils::ptr::Ptr;
use crate::{
spectra::{RGBColorSpace, RGBIlluminantSpectrum},
utils::{Transform, sampling::PiecewiseConstant2D},
utils::{Ptr, Transform, sampling::DevicePiecewiseConstant2D},
};
#[repr(C)]
@ -27,8 +26,8 @@ pub struct ProjectionLight {
pub screen_from_light: Transform,
pub light_from_screen: Transform,
pub a: Float,
pub image: Ptr<Image>,
pub distrib: Ptr<PiecewiseConstant2D>,
pub image: Ptr<DeviceImage>,
pub distrib: Ptr<DevicePiecewiseConstant2D>,
pub image_color_space: Ptr<RGBColorSpace>,
}

View file

@ -6,7 +6,7 @@ use crate::core::light::{LightBounds, LightSampleContext};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::math::{clamp, lerp, sample_discrete};
use crate::utils::math::{safe_sqrt, square};
use crate::utils::ptr::{Ptr, Slice};
use crate::utils::ptr::{DevicePtr, Slice};
use crate::utils::sampling::AliasTable;
use crate::{Float, ONE_MINUS_EPSILON, PI};
use enum_dispatch::enum_dispatch;
@ -154,14 +154,14 @@ impl CompactLightBounds {
#[derive(Debug, Clone)]
pub struct SampledLight {
pub light: Ptr<Light>,
pub light: DevicePtr<Light>,
pub p: Float,
}
impl SampledLight {
pub fn new(light: Light, p: Float) -> Self {
Self {
light: Ptr::from(&light),
light: DevicePtr::from(&light),
p,
}
}
@ -214,7 +214,7 @@ impl LightSamplerTrait for UniformLightSampler {
let light_index = (u as u32 * self.lights_len).min(self.lights_len - 1) as usize;
Some(SampledLight {
light: Ptr::from(&self.light(light_index)),
light: DevicePtr::from(&self.light(light_index)),
p: 1. / self.lights_len as Float,
})
}
@ -262,7 +262,7 @@ impl LightSamplerTrait for PowerLightSampler {
let light_ref = &self.lights[light_index as usize];
Some(SampledLight {
light: Ptr::from(light_ref),
light: DevicePtr::from(light_ref),
p: pmf,
})
}

View file

@ -4,7 +4,7 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
@ -16,7 +16,7 @@ use crate::utils::math::clamp;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct CoatedDiffuseMaterial {
pub normal_map: Ptr<Image>,
pub normal_map: Ptr<DeviceImage>,
pub displacement: Ptr<GPUFloatTexture>,
pub reflectance: Ptr<GPUSpectrumTexture>,
pub albedo: Ptr<GPUSpectrumTexture>,
@ -42,7 +42,7 @@ impl CoatedDiffuseMaterial {
g: &GPUFloatTexture,
eta: &Spectrum,
displacement: &GPUFloatTexture,
normal_map: &Image,
normal_map: &DeviceImage,
remap_roughness: bool,
max_depth: usize,
n_samples: usize,
@ -134,7 +134,7 @@ impl MaterialTrait for CoatedDiffuseMaterial {
)
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}
@ -150,7 +150,7 @@ impl MaterialTrait for CoatedDiffuseMaterial {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct CoatedConductorMaterial {
normal_map: Ptr<Image>,
normal_map: Ptr<DeviceImage>,
displacement: Ptr<GPUFloatTexture>,
interface_uroughness: Ptr<GPUFloatTexture>,
interface_vroughness: Ptr<GPUFloatTexture>,
@ -172,7 +172,7 @@ impl CoatedConductorMaterial {
#[allow(clippy::too_many_arguments)]
#[cfg(not(target_os = "cuda"))]
pub fn new(
normal_map: &Image,
normal_map: &DeviceImage,
displacement: &GPUFloatTexture,
interface_uroughness: &GPUFloatTexture,
interface_vroughness: &GPUFloatTexture,
@ -326,7 +326,7 @@ impl MaterialTrait for CoatedConductorMaterial {
tex_eval.can_evaluate(&float_textures, &spectrum_textures)
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}

View file

@ -6,40 +6,40 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::{BSSRDF, BSSRDFTable};
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvaluator};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::textures::GPUSpectrumMixTexture;
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::math::clamp;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct HairMaterial {
pub sigma_a: Ptr<GPUSpectrumTexture>,
pub color: Ptr<GPUSpectrumTexture>,
pub eumelanin: Ptr<GPUFloatTexture>,
pub pheomelanin: Ptr<GPUFloatTexture>,
pub eta: Ptr<GPUFloatTexture>,
pub beta_m: Ptr<GPUFloatTexture>,
pub beta_n: Ptr<GPUFloatTexture>,
pub alpha: Ptr<GPUFloatTexture>,
pub sigma_a: DevicePtr<GPUSpectrumTexture>,
pub color: DevicePtr<GPUSpectrumTexture>,
pub eumelanin: DevicePtr<GPUFloatTexture>,
pub pheomelanin: DevicePtr<GPUFloatTexture>,
pub eta: DevicePtr<GPUFloatTexture>,
pub beta_m: DevicePtr<GPUFloatTexture>,
pub beta_n: DevicePtr<GPUFloatTexture>,
pub alpha: DevicePtr<GPUFloatTexture>,
}
impl HairMaterial {
#[cfg(not(target_os = "cuda"))]
pub fn new(
sigma_a: Ptr<GPUSpectrumTexture>,
color: Ptr<GPUSpectrumTexture>,
eumelanin: Ptr<GPUFloatTexture>,
pheomelanin: Ptr<GPUFloatTexture>,
eta: Ptr<GPUFloatTexture>,
beta_m: Ptr<GPUFloatTexture>,
beta_n: Ptr<GPUFloatTexture>,
alpha: Ptr<GPUFloatTexture>,
sigma_a: DevicePtr<GPUSpectrumTexture>,
color: DevicePtr<GPUSpectrumTexture>,
eumelanin: DevicePtr<GPUFloatTexture>,
pheomelanin: DevicePtr<GPUFloatTexture>,
eta: DevicePtr<GPUFloatTexture>,
beta_m: DevicePtr<GPUFloatTexture>,
beta_n: DevicePtr<GPUFloatTexture>,
alpha: DevicePtr<GPUFloatTexture>,
) -> Self {
Self {
sigma_a,
@ -76,12 +76,12 @@ impl MaterialTrait for HairMaterial {
todo!()
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
todo!()
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
Ptr::null()
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
DevicePtr::null()
}
fn has_subsurface_scattering(&self) -> bool {
@ -92,9 +92,9 @@ impl MaterialTrait for HairMaterial {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct MeasuredMaterial {
pub displacement: Ptr<GPUFloatTexture>,
pub normal_map: Ptr<Image>,
pub brdf: Ptr<MeasuredBxDFData>,
pub displacement: DevicePtr<GPUFloatTexture>,
pub normal_map: DevicePtr<DeviceImage>,
pub brdf: DevicePtr<MeasuredBxDFData>,
}
impl MaterialTrait for MeasuredMaterial {
@ -121,11 +121,11 @@ impl MaterialTrait for MeasuredMaterial {
true
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
self.displacement
}
@ -137,16 +137,16 @@ impl MaterialTrait for MeasuredMaterial {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SubsurfaceMaterial {
pub normal_map: Ptr<Image>,
pub displacement: Ptr<GPUFloatTexture>,
pub sigma_a: Ptr<GPUSpectrumTexture>,
pub sigma_s: Ptr<GPUSpectrumMixTexture>,
pub reflectance: Ptr<GPUSpectrumMixTexture>,
pub mfp: Ptr<GPUSpectrumMixTexture>,
pub normal_map: DevicePtr<DeviceImage>,
pub displacement: DevicePtr<GPUFloatTexture>,
pub sigma_a: DevicePtr<GPUSpectrumTexture>,
pub sigma_s: DevicePtr<GPUSpectrumMixTexture>,
pub reflectance: DevicePtr<GPUSpectrumMixTexture>,
pub mfp: DevicePtr<GPUSpectrumMixTexture>,
pub eta: Float,
pub scale: Float,
pub u_roughness: Ptr<GPUFloatTexture>,
pub v_roughness: Ptr<GPUFloatTexture>,
pub u_roughness: DevicePtr<GPUFloatTexture>,
pub v_roughness: DevicePtr<GPUFloatTexture>,
pub remap_roughness: bool,
pub table: BSSRDFTable,
}
@ -173,11 +173,11 @@ impl MaterialTrait for SubsurfaceMaterial {
todo!()
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
todo!()
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
todo!()
}

View file

@ -4,7 +4,7 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
@ -23,7 +23,7 @@ pub struct ConductorMaterial {
pub u_roughness: Ptr<GPUFloatTexture>,
pub v_roughness: Ptr<GPUFloatTexture>,
pub remap_roughness: bool,
pub normal_map: Ptr<Image>,
pub normal_map: Ptr<DeviceImage>,
}
impl MaterialTrait for ConductorMaterial {
@ -50,7 +50,7 @@ impl MaterialTrait for ConductorMaterial {
)
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
todo!()
}

View file

@ -4,23 +4,23 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvaluator};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::math::clamp;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct DielectricMaterial {
normal_map: Ptr<Image>,
displacement: Ptr<GPUFloatTexture>,
u_roughness: Ptr<GPUFloatTexture>,
v_roughness: Ptr<GPUFloatTexture>,
eta: Ptr<Spectrum>,
normal_map: DevicePtr<DeviceImage>,
displacement: DevicePtr<GPUFloatTexture>,
u_roughness: DevicePtr<GPUFloatTexture>,
v_roughness: DevicePtr<GPUFloatTexture>,
eta: DevicePtr<Spectrum>,
remap_roughness: bool,
}
@ -51,7 +51,7 @@ impl MaterialTrait for DielectricMaterial {
let distrib = TrowbridgeReitzDistribution::new(u_rough, v_rough);
let bxdf = BxDF::Dielectric(DielectricBxDF::new(sampled_eta, distrib));
BSDF::new(ctx.ns, ctx.dpdus, Ptr::from(&bxdf))
BSDF::new(ctx.ns, ctx.dpdus, DevicePtr::from(&bxdf))
}
fn get_bssrdf<T>(
@ -67,11 +67,11 @@ impl MaterialTrait for DielectricMaterial {
tex_eval.can_evaluate(&[self.u_roughness, self.v_roughness], &[])
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
self.displacement
}
@ -83,9 +83,9 @@ impl MaterialTrait for DielectricMaterial {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct ThinDielectricMaterial {
pub displacement: Ptr<GPUFloatTexture>,
pub normal_map: Ptr<Image>,
pub eta: Ptr<Spectrum>,
pub displacement: DevicePtr<GPUFloatTexture>,
pub normal_map: DevicePtr<DeviceImage>,
pub eta: DevicePtr<Spectrum>,
}
impl MaterialTrait for ThinDielectricMaterial {
fn get_bsdf<T: TextureEvaluator>(
@ -109,11 +109,11 @@ impl MaterialTrait for ThinDielectricMaterial {
true
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
self.displacement
}

View file

@ -5,21 +5,21 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvaluator};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::math::clamp;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct DiffuseMaterial {
pub normal_map: Ptr<Image>,
pub displacement: Ptr<GPUFloatTexture>,
pub reflectance: Ptr<GPUSpectrumTexture>,
pub normal_map: DevicePtr<DeviceImage>,
pub displacement: DevicePtr<GPUFloatTexture>,
pub reflectance: DevicePtr<GPUSpectrumTexture>,
}
impl MaterialTrait for DiffuseMaterial {
@ -31,7 +31,7 @@ impl MaterialTrait for DiffuseMaterial {
) -> BSDF {
let r = tex_eval.evaluate_spectrum(&self.reflectance, ctx, lambda);
let bxdf = BxDF::Diffuse(DiffuseBxDF::new(r));
BSDF::new(ctx.ns, ctx.dpdus, Ptr::from(&bxdf))
BSDF::new(ctx.ns, ctx.dpdus, DevicePtr::from(&bxdf))
}
fn get_bssrdf<T>(
@ -47,11 +47,11 @@ impl MaterialTrait for DiffuseMaterial {
tex_eval.can_evaluate(&[], &[self.reflectance])
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.normal_map)
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
self.displacement
}
@ -63,10 +63,10 @@ impl MaterialTrait for DiffuseMaterial {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct DiffuseTransmissionMaterial {
pub image: Ptr<Image>,
pub displacement: Ptr<GPUFloatTexture>,
pub reflectance: Ptr<GPUFloatTexture>,
pub transmittance: Ptr<GPUFloatTexture>,
pub image: DevicePtr<DeviceImage>,
pub displacement: DevicePtr<GPUFloatTexture>,
pub reflectance: DevicePtr<GPUFloatTexture>,
pub transmittance: DevicePtr<GPUFloatTexture>,
pub scale: Float,
}
@ -92,11 +92,11 @@ impl MaterialTrait for DiffuseTransmissionMaterial {
tex_eval.can_evaluate(&[self.reflectance, self.transmittance], &[])
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
Some(&*self.image)
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
self.displacement
}

View file

@ -4,7 +4,7 @@ use crate::bxdfs::{
use crate::core::bsdf::BSDF;
use crate::core::bssrdf::BSSRDF;
use crate::core::bxdf::BxDF;
use crate::core::image::Image;
use crate::core::image::DeviceImage;
use crate::core::material::{Material, MaterialEvalContext, MaterialTrait};
use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
@ -12,13 +12,13 @@ use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvaluator
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::hash::hash_float;
use crate::utils::math::clamp;
use crate::utils::{ArenaPtr, Ptr};
use crate::utils::{DevicePtr, Ptr};
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct MixMaterial {
pub amount: Ptr<GPUFloatTexture>,
pub materials: [ArenaPtr<Material>; 2],
pub amount: DevicePtr<GPUFloatTexture>,
pub materials: [Ptr<Material>; 2],
}
impl MixMaterial {
@ -69,11 +69,11 @@ impl MaterialTrait for MixMaterial {
tex_eval.can_evaluate(&[self.amount], &[])
}
fn get_normal_map(&self) -> Option<&Image> {
fn get_normal_map(&self) -> Option<&DeviceImage> {
None
}
fn get_displacement(&self) -> Ptr<GPUFloatTexture> {
fn get_displacement(&self) -> DevicePtr<GPUFloatTexture> {
panic!(
"MixMaterial::get_displacement() shouldn't be called. \
Displacement is not supported on Mix materials directly."

View file

@ -3,17 +3,17 @@ use crate::core::geometry::Point2f;
use crate::core::pbrt::Float;
use crate::spectra::{DenselySampledSpectrum, SampledSpectrum};
use crate::utils::math::SquareMatrix3f;
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
use std::cmp::{Eq, PartialEq};
#[repr(C)]
#[derive(Copy, Debug, Clone)]
pub struct StandardColorSpaces {
pub srgb: Ptr<RGBColorSpace>,
pub dci_p3: Ptr<RGBColorSpace>,
pub rec2020: Ptr<RGBColorSpace>,
pub aces2065_1: Ptr<RGBColorSpace>,
pub srgb: DevicePtr<RGBColorSpace>,
pub dci_p3: DevicePtr<RGBColorSpace>,
pub rec2020: DevicePtr<RGBColorSpace>,
pub aces2065_1: DevicePtr<RGBColorSpace>,
}
#[repr(C)]
@ -24,7 +24,7 @@ pub struct RGBColorSpace {
pub b: Point2f,
pub w: Point2f,
pub illuminant: DenselySampledSpectrum,
pub rgb_to_spectrum_table: Ptr<RGBToSpectrumTable>,
pub rgb_to_spectrum_table: DevicePtr<RGBToSpectrumTable>,
pub xyz_from_rgb: SquareMatrix3f,
pub rgb_from_xyz: SquareMatrix3f,
}
@ -52,6 +52,14 @@ impl RGBColorSpace {
self.rgb_from_xyz * other.xyz_from_rgb
}
pub fn luminance_vector(&self) -> RGB {
RGB::new(
self.xyz_from_rgb[1][0],
self.xyz_from_rgb[1][1],
self.xyz_from_rgb[1][2],
)
}
}
impl PartialEq for RGBColorSpace {

View file

@ -4,7 +4,7 @@ use super::{
};
use crate::core::color::{RGB, RGBSigmoidPolynomial, XYZ};
use crate::core::spectrum::SpectrumTrait;
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::Float;
@ -69,7 +69,7 @@ impl SpectrumTrait for UnboundedRGBSpectrum {
pub struct RGBIlluminantSpectrum {
pub scale: Float,
pub rsp: RGBSigmoidPolynomial,
pub illuminant: Ptr<DenselySampledSpectrum>,
pub illuminant: DevicePtr<DenselySampledSpectrum>,
}
impl RGBIlluminantSpectrum {
@ -85,7 +85,7 @@ impl RGBIlluminantSpectrum {
Self {
scale,
rsp,
illuminant: Ptr::from(&illuminant),
illuminant: DevicePtr::from(&illuminant),
}
}
}

View file

@ -1,9 +1,10 @@
use super::cie::*;
use super::sampled::{LAMBDA_MAX, LAMBDA_MIN};
use crate::Float;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::spectra::{N_SPECTRUM_SAMPLES, SampledSpectrum, SampledWavelengths};
use crate::utils::ptr::Ptr;
use crate::{Float, find_interval};
use crate::utils::find_interval;
use crate::utils::ptr::DevicePtr;
use core::slice;
use std::hash::{Hash, Hasher};
use std::sync::LazyLock;
@ -35,7 +36,7 @@ impl SpectrumTrait for ConstantSpectrum {
pub struct DenselySampledSpectrum {
pub lambda_min: i32,
pub lambda_max: i32,
pub values: Ptr<Float>,
pub values: DevicePtr<Float>,
}
unsafe impl Send for DenselySampledSpectrum {}
@ -130,8 +131,8 @@ impl SpectrumTrait for DenselySampledSpectrum {
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PiecewiseLinearSpectrum {
pub lambdas: Ptr<Float>,
pub values: Ptr<Float>,
pub lambdas: DevicePtr<Float>,
pub values: DevicePtr<Float>,
pub count: u32,
}

View file

@ -3,7 +3,7 @@ use crate::core::spectrum::Spectrum;
use crate::core::spectrum::SpectrumTrait;
use crate::core::texture::{TextureEvalContext, TextureMapping2D};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::{Ptr, Transform};
use crate::utils::{DevicePtr, Transform};
#[repr(C)]
#[derive(Debug, Copy, Clone)]
@ -48,19 +48,19 @@ impl FloatBilerpTexture {
#[derive(Clone, Copy, Debug)]
pub struct SpectrumBilerpTexture {
pub mapping: TextureMapping2D,
pub v00: Ptr<Spectrum>,
pub v01: Ptr<Spectrum>,
pub v10: Ptr<Spectrum>,
pub v11: Ptr<Spectrum>,
pub v00: DevicePtr<Spectrum>,
pub v01: DevicePtr<Spectrum>,
pub v10: DevicePtr<Spectrum>,
pub v11: DevicePtr<Spectrum>,
}
impl SpectrumBilerpTexture {
pub fn new(
mapping: TextureMapping2D,
v00: Ptr<Spectrum>,
v01: Ptr<Spectrum>,
v10: Ptr<Spectrum>,
v11: Ptr<Spectrum>,
v00: DevicePtr<Spectrum>,
v01: DevicePtr<Spectrum>,
v10: DevicePtr<Spectrum>,
v11: DevicePtr<Spectrum>,
) -> Self {
Self {
mapping,

View file

@ -4,12 +4,12 @@ use crate::core::texture::{
TextureMapping3DTrait,
};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::{ArenaPtr, Ptr, math::square};
use crate::utils::{DevicePtr, Ptr, math::square};
fn checkerboard(
ctx: &TextureEvalContext,
map2d: Ptr<TextureMapping2D>,
map3d: Ptr<TextureMapping3D>,
map2d: DevicePtr<TextureMapping2D>,
map3d: DevicePtr<TextureMapping3D>,
) -> Float {
let d = |x: Float| -> Float {
let y = x / 2. - (x / 2.).floor() - 0.5;
@ -43,9 +43,9 @@ fn checkerboard(
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct FloatCheckerboardTexture {
pub map2d: Ptr<TextureMapping2D>,
pub map3d: Ptr<TextureMapping3D>,
pub tex: [ArenaPtr<GPUFloatTexture>; 2],
pub map2d: DevicePtr<TextureMapping2D>,
pub map3d: DevicePtr<TextureMapping3D>,
pub tex: [Ptr<GPUFloatTexture>; 2],
}
impl FloatCheckerboardTexture {
@ -74,9 +74,9 @@ impl FloatCheckerboardTexture {
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SpectrumCheckerboardTexture {
pub map2d: Ptr<TextureMapping2D>,
pub map3d: Ptr<TextureMapping3D>,
pub tex: [ArenaPtr<GPUSpectrumTexture>; 2],
pub map2d: DevicePtr<TextureMapping2D>,
pub map3d: DevicePtr<TextureMapping3D>,
pub tex: [Ptr<GPUSpectrumTexture>; 2],
}
impl SpectrumCheckerboardTexture {

View file

@ -4,7 +4,7 @@ use crate::core::texture::{
GPUFloatTexture, GPUSpectrumTexture, TextureEvalContext, TextureMapping2D,
};
use crate::spectra::sampled::{SampledSpectrum, SampledWavelengths};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use crate::utils::math::square;
use crate::utils::noise::noise_2d;
@ -28,8 +28,8 @@ fn inside_polka_dot(st: Point2f) -> bool {
#[derive(Debug, Clone, Copy)]
pub struct FloatDotsTexture {
pub mapping: TextureMapping2D,
pub outside_dot: Ptr<GPUFloatTexture>,
pub inside_dot: Ptr<GPUFloatTexture>,
pub outside_dot: DevicePtr<GPUFloatTexture>,
pub inside_dot: DevicePtr<GPUFloatTexture>,
}
impl FloatDotsTexture {
@ -53,8 +53,8 @@ impl FloatDotsTexture {
#[derive(Clone, Copy, Debug)]
pub struct SpectrumDotsTexture {
pub mapping: TextureMapping2D,
pub outside_dot: Ptr<GPUSpectrumTexture>,
pub inside_dot: Ptr<GPUSpectrumTexture>,
pub outside_dot: DevicePtr<GPUSpectrumTexture>,
pub inside_dot: DevicePtr<GPUSpectrumTexture>,
}
impl SpectrumDotsTexture {

View file

@ -95,11 +95,13 @@ impl GPUFloatImageTexture {
let d_p_dy = [c.dsdy, c.dtdy];
let val: Float = unsafe { intrinsics::tex2d_grad(self.tex_obj, u, v, d_p_dx, d_p_dy) };
if self.invert {
return (1. - v).max(0.);
let result = if self.invert {
(1.0 - val).max(0.0) // Invert the pixel intensity
} else {
return v;
}
val
};
return result * self.scale;
}
}
}

View file

@ -6,7 +6,7 @@ use crate::core::texture::{TextureEvalContext, TextureMapping3D};
use crate::spectra::{RGBAlbedoSpectrum, RGBColorSpace, SampledSpectrum, SampledWavelengths};
use crate::utils::math::clamp;
use crate::utils::noise::fbm;
use crate::utils::ptr::Ptr;
use crate::utils::ptr::DevicePtr;
use crate::utils::splines::evaluate_cubic_bezier;
#[repr(C)]
@ -18,7 +18,7 @@ pub struct MarbleTexture {
pub scale: Float,
pub variation: Float,
// TODO: DO not forget to pass StandardColorSpace here!!
pub colorspace: Ptr<RGBColorSpace>,
pub colorspace: DevicePtr<RGBColorSpace>,
}
unsafe impl Send for MarbleTexture {}

View file

@ -2,14 +2,14 @@ use crate::Float;
use crate::core::geometry::{Vector3f, VectorLike};
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvalContext};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::ArenaPtr;
use crate::utils::Ptr;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GPUFloatMixTexture {
pub tex1: ArenaPtr<GPUFloatTexture>,
pub tex2: ArenaPtr<GPUFloatTexture>,
pub amount: ArenaPtr<GPUFloatTexture>,
pub tex1: Ptr<GPUFloatTexture>,
pub tex2: Ptr<GPUFloatTexture>,
pub amount: Ptr<GPUFloatTexture>,
}
impl GPUFloatMixTexture {
@ -34,8 +34,8 @@ impl GPUFloatMixTexture {
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GPUFloatDirectionMixTexture {
pub tex1: ArenaPtr<GPUFloatTexture>,
pub tex2: ArenaPtr<GPUFloatTexture>,
pub tex1: Ptr<GPUFloatTexture>,
pub tex2: Ptr<GPUFloatTexture>,
pub dir: Vector3f,
}
@ -61,9 +61,9 @@ impl GPUFloatDirectionMixTexture {
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GPUSpectrumMixTexture {
pub tex1: ArenaPtr<GPUSpectrumTexture>,
pub tex2: ArenaPtr<GPUSpectrumTexture>,
pub amount: ArenaPtr<GPUFloatTexture>,
pub tex1: Ptr<GPUSpectrumTexture>,
pub tex2: Ptr<GPUSpectrumTexture>,
pub amount: Ptr<GPUFloatTexture>,
}
impl GPUSpectrumMixTexture {
@ -98,8 +98,8 @@ impl GPUSpectrumMixTexture {
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GPUSpectrumDirectionMixTexture {
pub tex1: ArenaPtr<GPUSpectrumTexture>,
pub tex2: ArenaPtr<GPUSpectrumTexture>,
pub tex1: Ptr<GPUSpectrumTexture>,
pub tex2: Ptr<GPUSpectrumTexture>,
pub dir: Vector3f,
}

View file

@ -6,7 +6,7 @@ use crate::spectra::{
RGBAlbedoSpectrum, RGBColorSpace, RGBIlluminantSpectrum, RGBUnboundedSpectrum, SampledSpectrum,
SampledWavelengths, StandardColorSpaces,
};
use crate::utils::ptr::{Ptr, Slice};
use crate::utils::ptr::{DevicePtr, Slice};
#[repr(C)]
#[derive(Debug, Clone, Copy)]

View file

@ -1,13 +1,13 @@
use crate::Float;
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvalContext};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::ArenaPtr;
use crate::utils::Ptr;
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GPUFloatScaledTexture {
pub tex: ArenaPtr<GPUFloatTexture>,
pub scale: ArenaPtr<GPUFloatTexture>,
pub tex: Ptr<GPUFloatTexture>,
pub scale: Ptr<GPUFloatTexture>,
}
impl GPUFloatScaledTexture {
@ -23,8 +23,8 @@ impl GPUFloatScaledTexture {
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GPUSpectrumScaledTexture {
pub tex: ArenaPtr<GPUSpectrumTexture>,
pub scale: ArenaPtr<GPUFloatTexture>,
pub tex: Ptr<GPUSpectrumTexture>,
pub scale: Ptr<GPUFloatTexture>,
}
impl GPUSpectrumScaledTexture {

View file

@ -25,7 +25,7 @@ impl<T> Interpolatable for T where
pub struct Array2D<T> {
pub values: *mut T,
pub extent: Bounds2i,
pub x_stride: i32,
pub stride: i32,
}
unsafe impl<T: Send> Send for Array2D<T> {}
@ -51,7 +51,7 @@ impl<T> Array2D<T> {
fn offset(&self, p: Point2i) -> isize {
let ox = p.x() - self.extent.p_min.x();
let oy = p.y() - self.extent.p_min.y();
(ox + oy * self.x_stride) as isize
(ox + oy * self.stride) as isize
}
#[inline]

View file

@ -5,7 +5,7 @@ use crate::core::pbrt::{Float, FloatBitOps, FloatBits, ONE_MINUS_EPSILON, PI, PI
use crate::utils::hash::{hash_buffer, mix_bits};
use crate::utils::sobol::{SOBOL_MATRICES_32, VDC_SOBOL_MATRICES, VDC_SOBOL_MATRICES_INV};
use crate::utils::Ptr;
use crate::utils::DevicePtr;
use half::f16;
use num_traits::{Float as NumFloat, Num, One, Signed, Zero};
use std::error::Error;
@ -753,7 +753,7 @@ pub fn inverse_radical_inverse(mut inverse: u64, base: u64, n_digits: u64) -> u6
pub struct DigitPermutation {
pub base: u32,
pub n_digits: u32,
pub permutations: Ptr<u16>,
pub permutations: DevicePtr<u16>,
}
impl DigitPermutation {

View file

@ -1,8 +1,8 @@
use crate::Float;
use crate::core::geometry::{Normal3f, Point2f, Point3f, Vector3f};
use crate::utils::Ptr;
use crate::utils::Transform;
use crate::utils::ptr::Ptr;
use crate::utils::sampling::PiecewiseConstant2D;
use crate::utils::sampling::DevicePiecewiseConstant2D;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
@ -30,5 +30,5 @@ pub struct BilinearPatchMesh {
pub p: Ptr<Point3f>,
pub n: Ptr<Normal3f>,
pub uv: Ptr<Point2f>,
pub image_distribution: Ptr<PiecewiseConstant2D>,
pub image_distribution: Ptr<DevicePiecewiseConstant2D>,
}

View file

@ -15,9 +15,33 @@ pub mod sobol;
pub mod splines;
pub mod transform;
pub use ptr::{ArenaPtr, Ptr};
pub use ptr::{DevicePtr, Ptr};
pub use transform::{AnimatedTransform, Transform, TransformGeneric};
#[inline]
pub fn find_interval<F>(sz: u32, pred: F) -> u32
where
F: Fn(u32) -> bool,
{
let mut first = 0;
let mut len = sz;
while len > 0 {
let half = len >> 1;
let middle = first + half;
if pred(middle) {
first = middle + 1;
len -= half + 1;
} else {
len = half;
}
}
let ret = (first as i32 - 1).max(0) as u32;
ret.min(sz.saturating_sub(2))
}
#[inline]
pub fn partition_slice<T, F>(data: &mut [T], predicate: F) -> usize
where

View file

@ -1,190 +1,136 @@
use core::marker::PhantomData;
use core::ops::Index;
#[repr(C)]
#[repr(transparent)]
#[derive(Debug)]
pub struct ArenaPtr<T: ?Sized> {
offset: i32,
_marker: PhantomData<T>,
pub struct Ptr<T: ?Sized> {
ptr: *const T,
}
impl<T: ?Sized> Clone for ArenaPtr<T> {
impl<T: ?Sized> Clone for Ptr<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized> Copy for Ptr<T> {}
impl<T: ?Sized> Copy for ArenaPtr<T> {}
impl<T> ArenaPtr<T> {
pub fn null() -> Self {
Self {
offset: 0xFFFFFFFF,
_marker: PhantomData,
}
}
pub fn is_null(&self) -> bool {
self.offset == 0xFFFFFFFF
}
#[inline(always)]
pub unsafe fn as_ptr(&self, base: *const u8) -> *const T {
if self.is_null() {
core::ptr::null()
} else {
unsafe { base.add(self.offset as usize) as *const T }
}
}
#[inline(always)]
pub unsafe fn as_ref<'a>(&self, base: *const u8) -> &'a T {
unsafe { &*self.as_ptr(base) }
}
#[cfg(not(target_os = "cuda"))]
pub fn new(me: *const Self, target: *const T) -> Self {
if target.is_null() {
return Self::null();
}
let diff = unsafe { (target as *const u8).offset_from(me as *const u8) };
if diff > i32::MAX as isize || diff < i32::MIN as isize {
panic!("RelPtr offset out of i32 range! Are objects too far apart?");
}
Self {
offset: diff as i32,
_marker: PhantomData,
}
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct Ptr<T>(pub *const T);
impl<T> Default for Ptr<T> {
fn default() -> Self {
Self(core::ptr::null())
}
}
impl<T> PartialEq for Ptr<T> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T> Eq for Ptr<T> {}
// Ptr is just a pointer - Send/Sync depends on T
unsafe impl<T: ?Sized + Send> Send for Ptr<T> {}
unsafe impl<T: ?Sized + Sync> Sync for Ptr<T> {}
impl<T> Ptr<T> {
pub fn null() -> Self {
Self::default()
pub const fn null() -> Self {
Self {
ptr: std::ptr::null(),
}
}
pub const fn is_null(self) -> bool {
self.ptr.is_null()
}
pub fn from_raw(ptr: *const T) -> Self {
Self { ptr }
}
pub fn as_raw(self) -> *const T {
self.ptr
}
#[inline(always)]
pub fn is_null(&self) -> bool {
self.0.is_null()
pub unsafe fn as_ref<'a>(self) -> &'a T {
debug_assert!(!self.is_null(), "null Ptr dereference");
unsafe { &*self.ptr }
}
/// Get as Option - safe for optional fields
#[inline(always)]
pub fn get<'a>(self) -> Option<&'a T> {
if self.is_null() {
None
} else {
Some(unsafe { &*self.ptr })
}
}
#[inline(always)]
pub fn as_ref(&self) -> Option<&T> {
unsafe { self.0.as_ref() }
pub unsafe fn at<'a>(self, index: usize) -> &'a T {
debug_assert!(!self.is_null(), "null Ptr array access");
unsafe { &*self.ptr.add(index) }
}
/// UNSTABLE: Casts the const pointer to mutable and returns a mutable reference.
/// THIS IS VERY DANGEROUS
/// The underlying data is not currently borrowed or accessed by any other thread/kernel.
/// The memory is actually writable.
/// No other mutable references exist to this data.
/// Get element at index, returns None if ptr is null
#[inline(always)]
pub unsafe fn as_mut(&mut self) -> &mut T {
debug_assert!(!self.is_null());
unsafe { &mut *(self.0 as *mut T) }
pub fn get_at<'a>(self, index: usize) -> Option<&'a T> {
if self.is_null() {
None
} else {
Some(unsafe { &*self.ptr.add(index) })
}
}
/// Offset the pointer, returning a new Ptr
#[inline(always)]
pub unsafe fn add(self, count: usize) -> Self {
Self {
ptr: unsafe { self.ptr.add(count) },
}
}
/// Convert to slice (requires knowing the length)
#[inline(always)]
pub unsafe fn as_slice<'a>(self, len: usize) -> &'a [T] {
debug_assert!(!self.is_null() || len == 0, "null Ptr to non-empty slice");
if len == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(self.ptr, len) }
}
}
/// Convert to slice, returns None if null
#[inline(always)]
pub fn get_slice<'a>(self, len: usize) -> Option<&'a [T]> {
if self.is_null() {
if len == 0 { Some(&[]) } else { None }
} else {
Some(unsafe { std::slice::from_raw_parts(self.ptr, len) })
}
}
}
unsafe impl<T: Sync> Send for Ptr<T> {}
unsafe impl<T: Sync> Sync for Ptr<T> {}
impl<T> std::ops::Deref for Ptr<T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
fn deref(&self) -> &T {
debug_assert!(!self.is_null(), "Null Ptr dereference");
unsafe { &*self.ptr }
}
}
impl<T> Default for Ptr<T> {
fn default() -> Self {
Self::null()
}
}
impl<T> From<&T> for Ptr<T> {
fn from(r: &T) -> Self {
Self(r as *const T)
Self { ptr: r as *const T }
}
}
impl<T> From<&mut T> for Ptr<T> {
fn from(r: &mut T) -> Self {
Self(r as *const T)
}
}
impl<T> Index<usize> for Ptr<T> {
type Output = T;
#[inline(always)]
fn index(&self, index: usize) -> &Self::Output {
// There is no bounds checking because we dont know the length.
// It is host responsbility to check bounds
unsafe { &*self.0.add(index) }
}
}
impl<T> Index<u32> for Ptr<T> {
type Output = T;
#[inline(always)]
fn index(&self, index: u32) -> &Self::Output {
unsafe { &*self.0.add(index as usize) }
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Slice<T> {
pub ptr: Ptr<T>,
pub len: u32,
pub _marker: PhantomData<T>,
}
unsafe impl<T: Sync> Send for Slice<T> {}
unsafe impl<T: Sync> Sync for Slice<T> {}
impl<T> Slice<T> {
pub fn new(ptr: Ptr<T>, len: u32) -> Self {
impl<T> From<&[T]> for Ptr<T> {
fn from(slice: &[T]) -> Self {
Self {
ptr,
len,
_marker: PhantomData,
ptr: slice.as_ptr(),
}
}
pub fn as_ptr(&self) -> *const T {
self.ptr.0
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
}
impl<T> Index<usize> for Slice<T> {
type Output = T;
#[inline(always)]
fn index(&self, index: usize) -> &Self::Output {
unsafe { &*self.ptr.0.add(index) }
impl<T> From<*const T> for Ptr<T> {
fn from(ptr: *const T) -> Self {
Self { ptr }
}
}

View file

@ -4,15 +4,14 @@ use crate::core::geometry::{
};
use crate::core::pbrt::{RARE_EVENT_CONDITION_MET, RARE_EVENT_TOTAL_CALLS};
use crate::utils::containers::Array2D;
use crate::utils::find_interval;
use crate::utils::math::{
catmull_rom_weights, clamp, difference_of_products, evaluate_polynomial, lerp, logistic,
newton_bisection, safe_sqrt, square, sum_of_products,
};
use crate::utils::ptr::Ptr;
use crate::utils::rng::Rng;
use crate::{
Float, INV_2_PI, INV_4_PI, INV_PI, ONE_MINUS_EPSILON, PI, PI_OVER_2, PI_OVER_4, find_interval,
};
use crate::{Float, INV_2_PI, INV_4_PI, INV_PI, ONE_MINUS_EPSILON, PI, PI_OVER_2, PI_OVER_4};
use num_traits::Num;
pub fn linear_pdf<T>(x: T, a: T, b: T) -> T
@ -702,7 +701,7 @@ pub struct PLSample {
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct PiecewiseConstant1D {
pub struct DevicePiecewiseConstant1D {
pub func: Ptr<Float>,
pub cdf: Ptr<Float>,
pub min: Float,
@ -711,10 +710,10 @@ pub struct PiecewiseConstant1D {
pub func_integral: Float,
}
unsafe impl Send for PiecewiseConstant1D {}
unsafe impl Sync for PiecewiseConstant1D {}
unsafe impl Send for DevicePiecewiseConstant1D {}
unsafe impl Sync for DevicePiecewiseConstant1D {}
impl PiecewiseConstant1D {
impl DevicePiecewiseConstant1D {
pub fn integral(&self) -> Float {
self.func_integral
}
@ -723,39 +722,48 @@ impl PiecewiseConstant1D {
self.n
}
pub fn sample(&self, u: Float) -> (Float, Float, u32) {
let o = find_interval(self.size(), |idx| self.cdf[idx] <= u) as usize;
let mut du = u - self.cdf[o];
if self.cdf[o + 1] - self.cdf[o] > 0. {
du /= self.cdf[o + 1] - self.cdf[o];
}
debug_assert!(!du.is_nan());
let value = lerp((o as Float + du) / self.size() as Float, self.min, self.max);
let pdf_val = if self.func_integral > 0. {
self.func[o] / self.func_integral
pub fn sample(&self, u: Float) -> (Float, Float, usize) {
// Find offset via binary search on CDF
let offset = self.find_interval(u);
let cdf_offset = unsafe { *self.cdf.add(offset) };
let cdf_next = unsafe { *self.cdf.add(offset + 1) };
let du = if cdf_next - cdf_offset > 0.0 {
(u - cdf_offset) / (cdf_next - cdf_offset)
} else {
0.
0.0
};
(value, pdf_val, o as u32)
let delta = (self.max - self.min) / self.n as Float;
let x = self.min + (offset as Float + du) * delta;
let pdf = if self.func_integral > 0.0 {
(unsafe { *self.func.add(offset) }) / self.func_integral
} else {
0.0
};
(x, pdf, offset)
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct PiecewiseConstant2D {
pub domain: Bounds2f,
pub p_marginal: PiecewiseConstant1D,
pub n_conditionals: usize,
pub p_conditional_v: Ptr<PiecewiseConstant1D>,
pub struct DevicePiecewiseConstant2D {
pub conditional: *const DevicePiecewiseConstant1D, // Array of n_v conditionals
pub marginal: DevicePiecewiseConstant1D,
pub n_u: u32,
pub n_v: u32,
}
impl PiecewiseConstant2D {
pub fn resolution(&self) -> Point2i {
Point2i::new(
self.p_conditional_v[0u32].size() as i32,
self.p_conditional_v[1u32].size() as i32,
)
}
impl DevicePiecewiseConstant2D {
// pub fn resolution(&self) -> Point2i {
// Point2i::new(
// self.p_conditional_v[0u32].size() as i32,
// self.p_conditional_v[1u32].size() as i32,
// )
// }
pub fn integral(&self) -> f32 {
self.p_marginal.integral()
@ -769,20 +777,20 @@ impl PiecewiseConstant2D {
(Point2f::new(d0, d1), pdf, offset)
}
pub fn pdf(&self, p: Point2f) -> f32 {
let p_offset = self.domain.offset(&p);
let nu = self.p_conditional_v[0u32].size();
let nv = self.p_marginal.size();
pub fn pdf(&self, p: Point2f) -> Float {
// Find which row
let delta_v = 1.0 / self.n_v as Float;
let v_offset = ((p.y() * self.n_v as Float) as usize).min(self.n_v as usize - 1);
let iu = (p_offset.x() * nu as f32).clamp(0.0, nu as f32 - 1.0) as usize;
let iv = (p_offset.y() * nv as f32).clamp(0.0, nv as f32 - 1.0) as usize;
let conditional = unsafe { &*self.conditional.add(v_offset) };
let integral = self.p_marginal.integral();
if integral == 0.0 {
0.0
} else {
self.p_conditional_v[iv].func[iu] / integral
}
// Find which column
let delta_u = 1.0 / self.n_u as Float;
let u_offset = ((p.x() * self.n_u as Float) as usize).min(self.n_u as usize - 1);
let func_val = unsafe { *conditional.func.add(u_offset) };
func_val / self.marginal.func_integral
}
}

View file

@ -7,7 +7,7 @@ use super::math::{SquareMatrix, radians, safe_acos};
use super::quaternion::Quaternion;
use crate::core::color::{RGB, XYZ};
use crate::core::geometry::{
Bounds3f, Normal, Normal3f, Point, Point3f, Point3fi, Ray, Vector, Vector3f, Vector3fi,
Bounds3f, Frame, Normal, Normal3f, Point, Point3f, Point3fi, Ray, Vector, Vector3f, Vector3fi,
VectorLike,
};
use crate::core::interaction::{
@ -714,6 +714,30 @@ where
}
}
}
impl From<Frame> for TransformGeneric<Float> {
fn from(frame: Frame) -> Self {
let values: &[Float; 16] = &[
frame.x.x(),
frame.x.y(),
frame.x.z(),
0.,
frame.y.x(),
frame.y.y(),
frame.y.z(),
0.,
frame.z.x(),
frame.z.y(),
frame.z.z(),
0.,
0.,
0.,
0.,
1.,
];
Self::from_flat(values).expect("Transform must be inversible")
}
}
impl From<Quaternion> for TransformGeneric<Float> {
fn from(q: Quaternion) -> Self {
let xx = q.v.x() * q.v.x();

View file

@ -1,10 +1,10 @@
use crate::Float;
use crate::core::geometry::{Bounds3f, Point3f, Ray, Vector3f};
use crate::core::pbrt::{Float, find_interval};
use crate::core::primitive::PrimitiveTrait;
use crate::core::shape::ShapeIntersection;
use crate::utils::math::encode_morton_3;
use crate::utils::math::next_float_down;
use crate::utils::partition_slice;
use crate::utils::{find_interval, partition_slice};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::sync::Arc;
@ -13,7 +13,7 @@ use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitMethod {
SAH,
AH,
Hlbvh,
Middle,
EqualCounts,
@ -345,7 +345,6 @@ impl BVHAggregate {
4,
);
// Add thread-local count to global atomic
total_nodes.fetch_add(nodes_created, AtomicOrdering::Relaxed);
root

View file

@ -1,5 +1,5 @@
use crate::core::image::ImageMetadata;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::Float;
use shared::cameras::*;
use shared::core::camera::{Camera, CameraBase, CameraTrait, CameraTransform};
@ -99,6 +99,7 @@ impl CameraFactory for Camera {
medium: Medium,
film: Arc<Film>,
loc: &FileLoc,
arena: &mut Arena,
) -> Result<Self, String> {
match name {
"perspective" => {
@ -143,6 +144,7 @@ impl CameraFactory for Camera {
let fov = params.get_one_float("fov", 90.);
let camera = PerspectiveCamera::new(base, fov, screen, lens_radius, focal_distance);
arena.alloc(camera);
Ok(Camera::Perspective(camera))
}
@ -187,6 +189,7 @@ impl CameraFactory for Camera {
}
}
let camera = OrthographicCamera::new(base, screen, lens_radius, focal_distance);
arena.alloc(camera);
Ok(Camera::Orthographic(camera))
}
"realistic" => {
@ -367,6 +370,7 @@ impl CameraFactory for Camera {
aperture_image,
);
arena.alloc(camera);
Ok(Camera::Realistic(camera))
}
"spherical" => {
@ -423,6 +427,7 @@ impl CameraFactory for Camera {
let camera = SphericalCamera { mapping, base };
arena.alloc(camera);
Ok(Camera::Spherical(camera))
}
_ => Err(format!("Camera type '{}' unknown at {}", name, loc)),

View file

@ -1,4 +1,4 @@
use super::ImageBuffer;
use super::{Image, ImageAndMetadata};
use crate::utils::error::ImageError;
use anyhow::{Context, Result, bail};
use exr::prelude::{read_first_rgba_layer_from_file, write_rgba_file};
@ -6,7 +6,7 @@ use image_rs::ImageReader;
use image_rs::{DynamicImage, ImageBuffer, Rgb, Rgba};
use shared::Float;
use shared::core::color::{ColorEncoding, LINEAR, SRGB};
use shared::core::image::Image;
use shared::core::image::DeviceImage;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path::Path;
@ -21,7 +21,7 @@ pub trait ImageIO {
fn to_u8_buffer(&self) -> Vec<u8>;
}
impl ImageIO for ImageBuffer {
impl ImageIO for Image {
fn read(path: &Path, encoding: Option<ColorEncoding>) -> Result<ImageAndMetadata> {
let ext = path
.extension()

View file

@ -1,5 +1,5 @@
use shared::core::geometry::Point2i;
use shared::core::image::{Image, PixelFormat};
use shared::core::image::{DeviceImage, ImageAccess, ImageBase, PixelFormat, WrapMode};
use shared::utils::math::f16_to_f32;
use std::ops::Deref;
@ -8,6 +8,7 @@ pub mod metadata;
pub mod ops;
pub mod pixel;
pub use io::ImageIO;
pub use metadata::*;
impl std::fmt::Display for PixelFormat {
@ -70,74 +71,75 @@ impl DerefMut for ImageChannelValues {
#[derive(Debug, Clone)]
pub enum PixelStorage {
U8(Vec<u8>),
F16(Vec<f16>),
F32(Vec<f32>),
U8(Box<[u8]>),
F16(Box<[f16]>),
F32(Box<[f32]>),
}
pub struct ImageBuffer {
pub view: Image,
pub channel_names: Vec<String>,
_storage: PixelStorage,
}
impl Deref for ImageBuffer {
type Target = Image;
fn deref(&self) -> &Self::Target {
&self.view
impl PixelStorage {
pub fn as_pixels(&self) -> Pixels {
match self {
PixelStorage::U8(data) => Pixels::U8(data.as_ptr()),
PixelStorage::F16(data) => Pixels::F16(data.as_ptr() as *const u16),
PixelStorage::F32(data) => Pixels::F32(data.as_ptr()),
}
}
pub fn format(&self) -> PixelFormat {
match self {
PixelStorage::U8(_) => PixelFormat::U8,
PixelStorage::F16(_) => PixelFormat::F16,
PixelStorage::F32(_) => PixelFormat::F32,
}
}
pub fn len(&self) -> usize {
match self {
PixelStorage::U8(d) => d.len(),
PixelStorage::F16(d) => d.len(),
PixelStorage::F32(d) => d.len(),
}
}
}
pub struct Image {
storage: PixelStorage,
channel_names: Vec<String>,
device: DeviceImage,
}
#[derive(Debug, Clone)]
pub struct ImageAndMetadata {
pub image: ImageBuffer,
pub image: Image,
pub metadata: ImageMetadata,
}
impl ImageBuffer {
fn resolution(&self) {
self.view.resolution()
}
pub fn new_empty() -> Self {
Self {
channel_names: Vec::new(),
_storage: PixelStorage::U8(Vec::new()),
view: Image {
format: PixelFormat::U256,
resolution: Point2i::new(0, 0),
n_channels: 0,
pixels: Pixels::U8(std::ptr::null()),
encoding: ColorEncoding::default(),
},
}
}
fn from_vector(
format: PixelFormat,
impl Image {
// Constructors
fn from_storage(
storage: PixelStorage,
resolution: Point2i,
channel_names: Vec<String>,
encoding: ColorEncoding,
) -> Self {
let n_channels = channel_names.len() as i32;
let (format, pixels_view) = match &storage {
PixelStorage::U8(vec) => (PixelFormat::U8, ImagePixels::U8(vec.as_ptr())),
PixelStorage::F16(vec) => (PixelFormat::F16, ImagePixels::F16(vec.as_ptr())),
PixelStorage::F32(vec) => (PixelFormat::F32, ImagePixels::F32(vec.as_ptr())),
};
let expected = (resolution.x() * resolution.y()) as usize * n_channels as usize;
assert_eq!(storage.len(), expected, "Pixel data size mismatch");
let view = Image {
format,
resolution,
n_channels,
let device = DeviceImage {
base: ImageBase {
format: storage.format(),
encoding,
pixels: pixels_view,
resolution,
n_channels,
},
pixels: storage.as_pixels(),
};
Self {
view,
_storage: storage,
storage,
channel_names,
device,
}
}
@ -147,37 +149,12 @@ impl ImageBuffer {
channel_names: Vec<String>,
encoding: ColorEncoding,
) -> Self {
let n_channels = channel_names.len() as i32;
let expected_len = (resolution.x * resolution.y) as usize * n_channels as usize;
if data.len() != expected_len {
panic!(
"ImageBuffer::from_u8: Data length {} does not match resolution {:?} * channels {}",
data.len(),
Self::from_storage(
PixelStorage::U8(data.into_boxed_slice()),
resolution,
n_channels
);
}
let storage = PixelStorage::U8(data);
let ptr = match &storage {
PixelStorage::U8(v) => v.as_ptr(),
_ => unreachable!(),
};
let view = Image {
format: PixelFormat::U256,
resolution,
n_channels,
pixels: Pixels::U8(ptr),
encoding: encoding.clone(),
};
Self {
view,
channel_names,
_storage: storage,
}
encoding,
)
}
pub fn from_u8(
@ -186,98 +163,30 @@ impl ImageBuffer {
channel_names: Vec<String>,
encoding: ColorEncoding,
) -> Self {
let n_channels = channel_names.len() as i32;
let expected_len = (resolution.x * resolution.y) as usize * n_channels as usize;
if data.len() != expected_len {
panic!(
"ImageBuffer::from_u8: Data length {} does not match resolution {:?} * channels {}",
data.len(),
Self::from_storage(
PixelStorage::U8(data.into_boxed_slice()),
resolution,
n_channels
);
}
let storage = PixelStorage::U8(data);
let ptr = match &storage {
PixelStorage::U8(v) => v.as_ptr(),
_ => unreachable!(),
};
let view = Image {
format: PixelFormat::U256,
resolution,
n_channels,
pixels: Pixels::U8(ptr),
encoding: encoding.clone(),
};
Self {
view,
channel_names,
_storage: storage,
}
encoding,
)
}
pub fn from_f16(data: Vec<half::f16>, resolution: Point2i, channel_names: Vec<String>) -> Self {
let n_channels = channel_names.len() as i32;
let expected_len = (resolution.x * resolution.y) as usize * n_channels as usize;
if data.len() != expected_len {
panic!("ImageBuffer::from_f16: Data length mismatch");
}
let storage = PixelStorage::F16(data);
let ptr = match &storage {
PixelStorage::F16(v) => v.as_ptr() as *const u16,
_ => unreachable!(),
};
let view = Image {
format: PixelFormat::Half,
Self::from_storage(
PixelStorage::F16(data.into_boxed_slice()),
resolution,
n_channels,
pixels: Pixels::F16(ptr),
encoding: ColorEncoding::default(),
};
Self {
view,
channel_names,
_storage: storage,
}
ColorEncoding::Linear,
)
}
pub fn from_f32(data: Vec<f32>, resolution: Point2i, channel_names: Vec<String>) -> Self {
let n_channels = channel_names.len() as i32;
let expected_len = (resolution.x * resolution.y) as usize * n_channels as usize;
if data.len() != expected_len {
panic!("ImageBuffer::from_f32: Data length mismatch");
}
let storage = PixelStorage::F32(data);
let ptr = match &storage {
PixelStorage::F32(v) => v.as_ptr(),
_ => unreachable!(),
};
let view = Image {
format: PixelFormat::Float,
Self::from_storage(
PixelStorage::F32(data.into_boxed_slice()),
resolution,
n_channels,
pixels: Pixels::F32(ptr),
encoding: ColorEncoding::default(),
};
Self {
view,
channel_names,
_storage: storage,
}
ColorEncoding::Linear,
)
}
pub fn new(
@ -296,7 +205,24 @@ impl ImageBuffer {
PixelFormat::F32 => PixelStorage::F32(vec![0.0; pixel_count]),
};
Self::from_vector(storage, resolution, owned_names, encoding)
Self::from_storage(storage, resolution, owned_names, encoding)
}
// Access
pub fn device_image(&self) -> &DeviceImage {
&self.device
}
pub fn resolution(&self) -> Point2i {
self.base.resolution
}
fn n_channels(&self) -> i32 {
self.base.n_channels
}
pub fn format(&self) -> PixelFormat {
self.device.base.format
}
pub fn channel_names(&self) -> Vec<&str> {
@ -307,60 +233,62 @@ impl ImageBuffer {
self.view.encoding
}
pub fn set_channel(&self, p: Point2i, c: i32, mut value: Float) {
if value.is_nan() {
value = 0.0;
fn pixel_offset(&self, p: Point2i) -> usize {
let width = self.resolution().x() as usize;
let idx = p.y() as usize * width + p.x() as usize;
idx * self.n_channels() as usize
}
if !self.view.resolution.inside_exclusive(p) {
return;
// Read
pub fn get_channel(&self, p: Point2i, c: i32) -> Float {
self.get_channel_with_wrap(p, c, WrapMode::Clamp.into())
}
let offset = self.view.pixel_offset(p) + c as usize;
match &mut self._storage {
pub fn get_channel_with_wrap(&self, mut p: Point2i, c: i32, wrap_mode: WrapMode2D) -> Float {
if !self.device.base.remap_pixel_coords(&mut p, wrap_mode) {
return 0.0;
}
let offset = self.pixel_offset(p) + c as usize;
match &self.storage {
PixelStorage::U8(data) => self.device.base.encoding.to_linear_scalar(data[offset]),
PixelStorage::F16(data) => data[offset].to_f32(),
PixelStorage::F32(data) => data[offset],
}
}
pub fn get_channels(&self, p: Point2i) -> ImageChannelValues {
self.get_channels_with_wrap(p, WrapMode::Clamp.into())
}
pub fn get_channels_with_wrap(
&self,
mut p: Point2i,
wrap_mode: WrapMode2D,
) -> ImageChannelValues {
if !self.device.base.remap_pixel_coords(&mut p, wrap_mode) {
return ImageChannelValues(smallvec![0.0; self.n_channels() as usize]);
}
let offset = self.pixel_offset(p);
let nc = self.n_channels() as usize;
let mut values = SmallVec::with_capacity(nc);
match &self.storage {
PixelStorage::U8(data) => {
if !self.view.encoding.is_null() {
data[offset] = self.view.encoding.from_linear_scalar(value);
} else {
let val = (value * 255.0 + 0.5).clamp(0.0, 255.0);
data[offset] = val as u8;
for i in 0..nc {
values.push(self.device.base.encoding.to_linear_scalar(data[offset + i]));
}
}
PixelStorage::F16(data) => {
data[offset] = f16_to_f32(value);
for i in 0..nc {
values.push(data[offset + i].to_f32());
}
}
PixelStorage::F32(data) => {
data[offset] = value;
}
}
}
pub fn get_channels_with_wrap(&self, p: Point2i, wrap_mode: WrapMode2D) -> ImageChannelValues {
let mut pp = p;
if !self.view.remap_pixel_coords(&mut pp, wrap_mode) {
return ImageChannelValues(smallvec![0.0; desc.offset.len()]);
}
let pixel_offset = self.view.pixel_offset(pp);
let mut values: SmallVec<[Float; 4]> = SmallVec::with_capacity(desc.offset.len());
match &self.pixels {
PixelData::U8(data) => {
for i in 0..self.view.n_channels() {
let raw_val = data[pixel_offset + i];
let linear = self.view.encoding.to_linear_scalar(raw_val);
values.push(linear);
}
}
PixelData::F16(data) => {
for i in 0..self.view.n_channels() {
let raw_val = data[pixel_offset];
values.push(f16_to_f32(raw_val));
}
}
PixelData::F32(data) => {
for i in 0..self.view.n_channels() {
let val = data[pixel_offset + i];
values.push(val);
for i in 0..nc {
values.push(data[offset + i]);
}
}
}
@ -368,43 +296,65 @@ impl ImageBuffer {
ImageChannelValues(values)
}
pub fn get_channels(&self, p: Point2i) -> ImageChannelValues {
self.get_channels_with_wrap(p, WrapMode::Clamp.into())
// Write
pub fn set_channel(&mut self, p: Point2i, c: i32, mut value: Float) {
if value.is_nan() {
value = 0.0;
}
let res = self.resolution();
if p.x() < 0 || p.x() >= res.x() || p.y() < 0 || p.y() >= res.y() {
return;
}
let offset = self.pixel_offset(p) + c as usize;
match &mut self.storage {
PixelStorage::U8(data) => {
let data = Box::as_mut(data);
data[offset] = self.device.base.encoding.from_linear_scalar(value);
}
PixelStorage::F16(data) => {
let data = Box::as_mut(data);
data[offset] = f16::from_f32(value);
}
PixelStorage::F32(data) => {
let data = Box::as_mut(data);
data[offset] = value;
}
}
}
// Descriptions
pub fn get_channels_with_desc(
&self,
p: Point2i,
desc: &ImageChannelDesc,
wrap: WrapMode2D,
wrap_mode: WrapMode2D,
) -> ImageChannelValues {
let mut pp = p;
if !self.view.remap_pixel_coords(&mut pp, wrap) {
if !self.device.base.remap_pixel_coords(&mut pp, wrap_mode) {
return ImageChannelValues(smallvec![0.0; desc.offset.len()]);
}
let pixel_offset = self.view.pixel_offset(pp);
let pixel_offset = self.pixel_offset(pp);
let mut values = SmallVec::with_capacity(desc.offset.len());
let mut values: SmallVec<[Float; 4]> = SmallVec::with_capacity(desc.offset.len());
match &self.pixels {
PixelData::U8(data) => {
for &channel_idx in &desc.offset {
let raw_val = data[pixel_offset + channel_idx as usize];
let linear = self.view.encoding.to_linear_scalar(raw_val);
values.push(linear);
match &self.storage {
PixelStorage::U8(data) => {
for &c in &desc.offset {
let raw = data[pixel_offset + c];
values.push(self.device.base.encoding.to_linear_scalar(raw));
}
}
PixelData::F16(data) => {
for &channel_idx in &desc.offset {
let raw_val = data[pixel_offset + channel_idx as usize];
values.push(f16_to_f32(raw_val));
PixelStorage::F16(data) => {
for &c in &desc.offset {
values.push(data[pixel_offset + c].to_f32());
}
}
PixelData::F32(data) => {
for &channel_idx in &desc.offset {
let val = data[pixel_offset + channel_idx as usize];
values.push(val);
PixelStorage::F32(data) => {
for &c in &desc.offset {
values.push(data[pixel_offset + c]);
}
}
}
@ -432,7 +382,7 @@ impl ImageBuffer {
}
None => {
return Err(format!(
"Image is missing requested channel '{}'. Available channels: {:?}",
"Missing channel '{}'. Available: {:?}",
req, self.channel_names
));
}
@ -444,87 +394,53 @@ impl ImageBuffer {
pub fn all_channels_desc(&self) -> ImageChannelDesc {
ImageChannelDesc {
offset: (0..self.n_channels()).collect(),
offset: (0..self.n_channels() as usize).collect(),
}
}
pub fn select_channels(&self, desc: &ImageChannelDesc) -> Self {
let desc_channel_names: Vec<String> = desc
let new_names: Vec<String> = desc
.offset
.iter()
.map(|&i| self.channel_names[i as usize])
.map(|&i| self.channel_names[i].clone())
.collect();
let new_storage = match &self._storage {
PixelStorage::U8(src_data) => {
// Allocate destination buffer
let mut dst_data = vec![0u8; pixel_count * dst_n_channels];
let res = self.resolution();
let pixel_count = (res.x() * res.y()) as usize;
let src_nc = self.n_channels() as usize;
let dst_nc = desc.offset.len();
// Iterate over every pixel (Flat loop is faster than nested x,y)
let new_storage = match &self.storage {
PixelStorage::U8(src) => {
let mut dst = vec![0u8; pixel_count * dst_nc];
for i in 0..pixel_count {
let src_pixel_start = i * src_n_channels;
let dst_pixel_start = i * dst_n_channels;
// Copy specific channels based on desc
for (out_idx, &in_channel_offset) in desc.offset.iter().enumerate() {
let val = src_data[src_pixel_start + in_channel_offset as usize];
dst_data[dst_pixel_start + out_idx] = val;
for (out_idx, &in_c) in desc.offset.iter().enumerate() {
dst[i * dst_nc + out_idx] = src[i * src_nc + in_c];
}
}
PixelStorage::U8(dst_data)
PixelStorage::U8(dst.into_boxed_slice())
}
PixelStorage::F16(src_data) => {
let mut dst_data = vec![half::f16::ZERO; pixel_count * dst_n_channels];
PixelStorage::F16(src) => {
let mut dst = vec![f16::ZERO; pixel_count * dst_nc];
for i in 0..pixel_count {
let src_pixel_start = i * src_n_channels;
let dst_pixel_start = i * dst_n_channels;
for (out_idx, &in_channel_offset) in desc.offset.iter().enumerate() {
let val = src_data[src_pixel_start + in_channel_offset as usize];
dst_data[dst_pixel_start + out_idx] = val;
for (out_idx, &in_c) in desc.offset.iter().enumerate() {
dst[i * dst_nc + out_idx] = src[i * src_nc + in_c];
}
}
PixelStorage::F16(dst_data)
PixelStorage::F16(dst.into_boxed_slice())
}
PixelStorage::F32(src_data) => {
let mut dst_data = vec![0.0; pixel_count * dst_n_channels];
PixelStorage::F32(src) => {
let mut dst = vec![0.0f32; pixel_count * dst_nc];
for i in 0..pixel_count {
let src_pixel_start = i * src_n_channels;
let dst_pixel_start = i * dst_n_channels;
for (out_idx, &in_channel_offset) in desc.offset.iter().enumerate() {
let val = src_data[src_pixel_start + in_channel_offset as usize];
dst_data[dst_pixel_start + out_idx] = val;
for (out_idx, &in_c) in desc.offset.iter().enumerate() {
dst[i * dst_nc + out_idx] = src[i * src_nc + in_c];
}
}
PixelStorage::F32(dst_data)
PixelStorage::F32(dst.into_boxed_slice())
}
};
let image = Self::new(
self.format,
self.resolution,
desc_channel_names,
self.encoding(),
);
}
pub fn set_channels(
&mut self,
p: Point2i,
desc: &ImageChannelDesc,
mut values: &ImageChannelValues,
) {
assert_eq!(desc.size(), values.len());
for i in 0..desc.size() {
self.view.set_channel(p, desc.offset[i], values[i]);
}
}
pub fn set_channels_all(&mut self, p: Point2i, values: &ImageChannelValues) {
self.set_channels(p, &self.all_channels_desc(), values)
Self::from_storage(new_storage, res, new_names, self.encoding())
}
pub fn get_sampling_distribution<F>(&self, dxd_a: F, domain: Bounds2f) -> Array2D<Float>
@ -633,4 +549,29 @@ impl ImageBuffer {
PixelStorage::F32(vec) => Pixels::F32(vec.as_ptr()),
};
}
pub fn has_any_infinite_pixels(&self) -> bool {
if format == PixelFormat::Float {
return false;
}
for y in 0..self.resolution().y() {
for x in 0..self.resolution().x() {
for c in 0..self.n_channels() {
if self.get_channel(Point2i::new(x, y), c).is_infinite() {
return true;
}
}
}
}
return false;
}
}
impl std::ops::Deref for Image {
type Target = DeviceImage;
fn deref(&self) -> &DeviceImage {
&self.device
}
}

View file

@ -1,5 +1,5 @@
// use rayon::prelude::*;
use super::ImageBuffer;
use super::Image;
use rayon::prelude::*;
use shared::Float;
use shared::core::geometry::{Bounds2i, Point2i};
@ -13,7 +13,7 @@ pub struct ResampleWeight {
pub weight: [Float; 4],
}
impl ImageBuffer {
impl Image {
pub fn flip_y(&mut self) {
let res = self.resolution;
let nc = self.n_channels();

View file

@ -1,31 +1,135 @@
use shared::core::geometry::{Bounds3f, Point2i};
use shared::core::image::Image;
use shared::core::light::LightBase;
use shared::core::medium::MediumInterface;
use shared::core::spectrum::Spectrum;
use shared::spectra::{DenselySampledSpectrum, SampledSpectrum, SampledWavelengths};
use shared::utils::Transform;
use shared::{Float, PI};
use crate::core::spectrum::SPECTRUM_CACHE;
use crate::core::spectrum::{SPECTRUM_CACHE, spectrum_to_photometric};
use crate::core::texture::FloatTexture;
use crate::lights::*;
use crate::utils::containers::InternCache;
use crate::utils::{Arena, FileLoc, ParameterDictionary, Upload, resolve_filename};
use shared::core::camera::CameraTransform;
use shared::core::light::Light;
use shared::core::medium::Medium;
use shared::core::spectrum::Spectrum;
use shared::core::texture::SpectrumType;
use shared::lights::*;
use shared::spectra::{DenselySampledSpectrum, RGBColorSpace};
use shared::utils::{Ptr, Transform};
pub trait LightBaseTrait {
pub fn lookup_spectrum(s: &Spectrum) -> DenselySampledSpectrum {
pub fn lookup_spectrum(s: &Spectrum) -> DenselySampledSpectrum {
let cache = SPECTRUM_CACHE.get_or_init(InternCache::new);
let dense_spectrum = DenselySampledSpectrum::from_spectrum(s);
cache.lookup(dense_spectrum).as_ref()
}
}
impl LightBaseTrait for LightBase {}
pub trait CreateLight {
fn create(
arena: &mut Arena,
render_from_light: Transform,
medium: Medium,
parameters: &ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_text: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light;
}
pub trait LightFactory {
fn new(
fn create(
name: &str,
arena: &mut Arena,
render_from_light: Transform,
medium_interface: MediumInterface,
scale: Float,
iemit: &Spectrum,
image: &Image,
) -> Self;
medium: Medium,
parameters: &ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
camera_transform: CameraTransform,
) -> Result<Self, Error>;
}
impl LightFactory for Light {
fn create(
name: &str,
arena: &mut Arena,
render_from_light: Transform,
medium: Medium,
parameters: &ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
camera_transform: CameraTransform,
) -> Result<Self, Error> {
match name {
"diffuse" => lights::diffuse::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"point" => PointLight::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"spot" => SpotLight::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"goniometric" => GoniometricLight::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"projection" => ProjectionLight::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"distant" => DistantLight::create(
arena,
render_from_light,
medium,
parameters,
loc,
shape,
alpha_tex,
colorspace,
)?,
"infinite" => infinite::create(
arena,
render_from_light,
medium,
camera_transform,
parameters,
colorspace,
loc,
)?,
_ => Err(error!(loc, "unknown light type: \"{}\"", name)),
}
}
}

View file

@ -1,4 +1,4 @@
use crate::core::image::ImageBuffer;
use crate::core::image::Image;
use crate::utils::error::FileLoc;
use crate::utils::parameters::ParameterDictionary;
use shared::core::material::Material;
@ -8,10 +8,10 @@ use std::collections::HashMap;
pub trait CreateMaterial: Sized {
fn create(
parameters: &TextureParameterDictionary,
normal_map: Option<Arc<ImageBuffer>>,
normal_map: Option<Ptr<Image>>,
named_materials: &HashMap<String, Material>,
loc: &FileLoc,
) -> Self;
) -> Result<Self, Error>;
}
macro_rules! make_material_factory {
@ -35,10 +35,10 @@ pub trait MaterialFactory {
fn create(
name: &str,
params: &TextureParameterDictionary,
normal_map: Arc<ImageBuffer>,
normal_map: Ptr<Image>,
named_materials: HashMap<String, Material>,
loc: &FileLoc,
) -> Result<Self, String>;
) -> Result<Self, Error>;
}
impl MaterialFactory for Material {

View file

@ -1,12 +1,14 @@
use crate::core::filter::FilterFactory;
use crate::core::image::{ImageBuffer, io::ImageIO};
use crate::core::image::{Image, io::ImageIO};
use crate::core::texture::SpectrumTexture;
use crate::utils::parallel::{AsyncJob, run_async};
use crate::utils::parameters::{
NamedTextures, ParameterDictionary, ParsedParameterVector, TextureParameterDictionary,
};
use crate::utils::parser::ParserTarget;
use crate::utils::{Arena, Upload};
use crate::utils::{normalize_utf8, resolve_filename};
use image_rs::Primitive;
use parking_lot::Mutex;
use shared::Float;
use shared::core::camera::{Camera, CameraTransform};
@ -16,8 +18,9 @@ use shared::core::filter::Filter;
use shared::core::geometry::{Point3f, Vector3f};
use shared::core::lights::Light;
use shared::core::material::Material;
use shared::core::medium::Medium;
use shared::core::medium::{Medium, MediumInterface};
use shared::core::options::RenderingCoordinateSystem;
use shared::core::primitive::{Primitive, PrimitiveTrait};
use shared::core::sampler::Sampler;
use shared::core::spectrum::{Spectrum, SpectrumType};
use shared::core::texture::{FloatTexture, SpectrumTexture};
@ -26,7 +29,6 @@ use shared::spectra::RGBColorSpace;
use shared::utils::error::FileLoc;
use shared::utils::math::SquareMatrix;
use shared::utils::transform::{AnimatedTransform, Transform, look_at};
use std::char::MAX;
use std::collections::{HashMap, HashSet};
use std::ops::{Index as IndexTrait, IndexMut as IndexMutTrait};
use std::sync::Arc;
@ -172,6 +174,33 @@ pub struct BasicScene {
pub film_state: Mutex<SingletonState<Film>>,
}
struct SceneLookup<'a> {
textures: &'a NamedTextures,
media: &'a HashMap<String, Medium>,
named_materials: &'a HashMap<String, Material>,
materials: &'a Vec<Material>,
shape_lights: &'a HashMap<usize, Vec<Light>>,
}
impl<'a> SceneLookup<'a> {
fn find_medium(&self, name: &str, loc: &FileLoc) -> Option<Medium> {
if name.is_empty() {
return None;
}
self.media.get(name).cloned().or_else(|| {
panic!("{}: medium '{}' not defined", loc, name);
})
}
fn resolve_material(&self, name: &str, loc: &FileLoc) -> Material {
if !name.is_empty() {
*self.named_materials.get(name).expect("Material not found")
} else {
self.materials[index]
}
}
}
impl BasicScene {
fn set_options(
self: &Arc<Self>,
@ -374,7 +403,7 @@ impl BasicScene {
pub fn add_light(&self, light: LightSceneEntity) {
if light.transformed_base.render_from_object.is_animated() {
log::info!(
log::warn!(
"{}: Animated world to texture not supported, using start",
light.transformed_base.base.loc
);
@ -530,6 +559,190 @@ impl BasicScene {
(named_materials_out, materials_out)
}
pub fn create_aggregate(
&self,
arena: &mut Arena,
textures: &NamedTextures,
shape_lights: &HashMap<usize, Vec<Light>>,
) -> Arc<dyn PrimitiveTrait> {
let shapes_guard = self.shapes.lock().unwrap();
let animated_shapes_guard = self.animated_shapes.lock().unwrap();
let media_guard = self.media_state.lock().unwrap();
let mat_guard = self.material_state.lock().unwrap();
let lookup = SceneLookup {
textures: &textures.float_textures,
media: &media_guard.map,
named_materials: &mat_guard.named_materials.iter().cloned().collect(),
materials: &mat_guard.materials,
shape_lights,
};
let mut all_primitives = Vec::new();
// Parallel CPU Load
let loaded_static = self.load_shapes_parallel(&shapes_guard, &lookup);
// Serial Arena Upload
let static_prims = self.upload_shapes(arena, &shapes_guard, loaded_static, &lookup);
all_primitives.extend(static_prims);
// Parallel CPU Load
let loaded_animated = self.load_animated_shapes_parallel(&animated_shapes_guard, &lookup);
// Serial Arena Upload
let anim_prims =
self.upload_animated_shapes(arena, &animated_shapes_guard, loaded_animated, &lookup);
all_primitives.extend(anim_prims);
// (Similar pattern: Lock definitions, load parallel, upload serial)
// Call a helper `create_instance_primitives` here.
if !all_primitives.is_empty() {
todo!("Build BVH or KD-Tree")
} else {
todo!("Return empty")
}
}
fn load_shapes_parallel(
&self,
entities: &[ShapeSceneEntity],
lookup: &SceneLookup,
) -> Vec<Vec<Shape>> {
entities
.par_iter()
.map(|sh| {
Shape::create(
&sh.base.name,
sh.render_from_object.as_ref(),
sh.object_from_render.as_ref(),
sh.reverse_orientation,
&sh.base.parameters,
lookup.float_textures,
&sh.base.loc,
)
})
.collect()
}
fn load_animated_shapes_parallel(
&self,
entities: &[AnimatedShapeSceneEntity],
lookup: &SceneLookup,
) -> Vec<Vec<Shape>> {
entities
.par_iter()
.map(|sh| {
Shape::create(
&sh.transformed_base.base.name,
&sh.identity,
&sh.identity,
sh.reverse_orientation,
&sh.transformed_base.base.parameters,
lookup.float_textures,
&sh.transformed_base.base.loc,
)
})
.collect()
}
fn upload_shapes(
&self,
arena: &mut Arena,
entities: &[ShapeSceneEntity],
loaded_shapes: Vec<Vec<Shape>>,
lookup: &SceneLookup,
) -> Vec<Primitive> {
let mut primitives = Vec::new();
for (i, (entity, shapes)) in entities.iter().zip(loaded_shapes).enumerate() {
if shapes.is_empty() {
continue;
}
let alpha_tex = self.get_alpha_texture(
&entity.base.parameters,
&entity.base.loc,
arena,
lookup.float_textures,
);
let mtl = lookup.resolve_material(&entity.material, &entity.base.loc);
let mi = MediumInterface::new(
lookup.find_medium(&entity.inside_medium, &entity.base.loc),
lookup.find_medium(&entity.outside_medium, &entity.base.loc),
);
let shape_lights_opt = lookup.shape_lights.get(&i);
for (j, shape_host) in shapes.into_iter().enumerate() {
let mut area_light = None;
if entity.light_index.is_some() {
if let Some(lights) = shape_lights_opt {
if j < lights.len() {
area_light = Some(lights[j]);
}
}
}
let shape_ptr = shape_host.upload(arena);
let prim = if area_light.is_none()
&& !mi.is_medium_transition()
&& alpha_tex.is_none()
{
let p = SimplePrimitive::new(shape_ptr, mtl.unwrap());
Primitive::Simple(arena.alloc(p))
} else {
let p =
GeometricPrimitive::new(shape_ptr, mtl.unwrap(), area_light, mi, alpha_tex);
Primitive::Geometric(arena.alloc(p))
};
primitives.push(prim);
}
}
primitives
}
fn upload_animated_shapes(
&self,
arena: &mut Arena,
entities: &[AnimatedShapeSceneEntity],
loaded_shapes: Vec<Vec<Shape>>,
lookup: &SceneLookup,
) -> Vec<Primitive> {
// Logic mirrors upload_shapes, but constructs AnimatedPrimitive or BVH
// ...
// Note: For AnimatedPrimitives, you wrap the result in `arena.alloc(AnimatedPrimitive::new(...))`
Vec::new()
}
fn get_alpha_texture(
&self,
params: &ParameterDictionary,
loc: &FileLoc,
arena: &mut Arena,
textures: &HashMap<String, FloatTexture>,
) -> Option<FloatTexture> {
let alpha_name = params.get_texture("alpha");
if let Some(name) = alpha_name {
match textures.get(&name) {
Some(tex) => Some(*tex),
None => panic!("{:?}: Alpha texture '{}' not found", loc, name),
}
} else {
let alpha_val = params.get_one_float("alpha", 1.0);
if alpha_val < 1.0 {
let tex = FloatConstantTexture::new(alpha_val);
let ptr = arena.alloc(tex);
Some(FloatTexture::Constant(ptr))
} else {
None
}
}
}
pub fn get_camera(&self) -> Arc<Camera> {
self.get_singleton(&self.camera_state, "Camera")
}
@ -650,7 +863,6 @@ impl BasicScene {
}
// PRIVATE METHODS
fn get_singleton<T: Send + Sync + 'static>(
&self,
mutex: &Mutex<SingletonState<T>>,
@ -694,7 +906,7 @@ impl BasicScene {
let job = crate::parallel::run_async(move || {
let path = std::path::Path::new(&filename_clone);
let immeta = ImageBuffer::read(path, Some(ColorEncoding::Linear))
let immeta = Image::read(path, Some(ColorEncoding::Linear))
.unwrap_or_else(|e| panic!("{}: unable to read normal map: {}", filename_clone, e));
let image = &immeta.image;
@ -852,7 +1064,6 @@ impl BasicSceneBuilder {
named_coordinate_systems: HashMap::new(),
active_instance_definition: None,
shapes: Vec::new(),
instances: Vec::new(),
named_material_names: HashSet::new(),
medium_names: HashSet::new(),

View file

@ -1,6 +1,6 @@
use crate::core::texture::FloatTexture;
use crate::shapes::TriQuadMesh;
use crate::utils::{FileLoc, ParameterDictionary, resolve_filename};
use crate::utils::{Arena, FileLoc, ParameterDictionary, resolve_filename};
use shared::core::options::get_options;
use shared::core::shape::*;
use shared::shapes::*;
@ -21,6 +21,7 @@ pub trait CreateShape {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Vec<Shape>;
}
@ -33,6 +34,7 @@ pub trait ShapeFactory {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Vec<Shape>;
}
@ -45,6 +47,7 @@ impl ShapeFactory for Shape {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Vec<Shape> {
match name {
"sphere" => SphereShape::create(
@ -55,6 +58,7 @@ impl ShapeFactory for Shape {
parameters,
float_textures,
loc,
arena,
),
"cylinder" => CylinderShape::create(
name,
@ -64,6 +68,7 @@ impl ShapeFactory for Shape {
parameters,
float_textures,
loc,
arena,
),
"disk" => DiskShape::create(
name,
@ -73,6 +78,7 @@ impl ShapeFactory for Shape {
parameters,
float_textures,
loc,
arena,
),
"bilinearmesh" => BilinearPatchShape::create(
name,
@ -82,6 +88,7 @@ impl ShapeFactory for Shape {
parameters,
float_textures,
loc,
arena,
),
"trianglemesh" => TriangleShape::create(
name,
@ -91,6 +98,7 @@ impl ShapeFactory for Shape {
parameters,
float_textures,
loc,
arena,
),
"plymesh" => {
let filename = resolve_filename(parameters.get_one_string("filename", ""));

View file

@ -1,4 +1,9 @@
use crate::core::light::LightBaseTrait;
use crate::spectra::cie_y;
use crate::utils::containers::InternCache;
use shared::Float;
use shared::core::light::LightBase;
use shared::core::spectrum::Spectrum;
pub static SPECTRUM_CACHE: Lazy<Mutex<HashMap<String, Spectrum>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
@ -6,3 +11,11 @@ pub static SPECTRUM_CACHE: Lazy<Mutex<HashMap<String, Spectrum>>> =
fn get_spectrum_cache() -> &'static InternCache<DenselySampledSpectrum> {
SPECTRUM_CACHE.get_or_init(InternCache::new)
}
pub fn spectrum_to_photometric(s: Spectrum) -> Float {
let effective_spectrum = match s {
Spectrum::RGBIlluminant(ill) => &Spectrum::Dense(ill.illuminant),
_ => s,
};
effective_spectrum.inner_product(cie_y)
}

View file

@ -6,6 +6,7 @@ use shared::core::spectrum::{Spectrum, SpectrumTrait};
use shared::core::texture::SpectrumType;
use shared::lights::DiffuseAreaLight;
use shared::spectra::RGBColorSpace;
use shared::utils::Transform;
use std::sync::Arc;
use crate::core::image::{Image, ImageIO};
@ -17,18 +18,33 @@ use crate::core::texture::{
};
use crate::utils::{Arena, FileLoc, ParameterDictionary, Upload, resolve_filename};
impl CreateLight for DiffuseAreaLight {
pub trait CreateDiffuseLight {
fn new(
render_from_light: shared::utils::Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<Float>,
shape: Ptr<Shape>,
alpha: Ptr<FloatTexture>,
image: Ptr<Image>,
colorspace: Option<RGBColorSpace>,
two_sided: bool,
fov: Float,
) -> Self;
}
impl CreateDiffuseLight for DiffuseAreaLight {
fn new(
render_from_light: shared::utils::Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
shape: Ptr<Shape>,
alpha: Ptr<FloatTexture>,
image: Ptr<Image>,
colorspace: Option<RGBColorSpace>,
two_sided: bool,
fov: Float,
) -> Self {
let is_constant_zero = match &alpha {
FloatTexture::FloatConstant(tex) => tex.evaluate(&TextureEvalContext::default()) == 0.0,
@ -56,7 +72,7 @@ impl CreateLight for DiffuseAreaLight {
);
assert!(
image_color_space.is_some(),
colorspace.is_some(),
"Image provided but ColorSpace is missing"
);
}
@ -74,7 +90,7 @@ impl CreateLight for DiffuseAreaLight {
base,
area: shape.area(),
image,
image_color_space,
colorspace,
shape: Ptr::from(&*storage.shape),
alpha: stored_alpha,
lemit,
@ -82,7 +98,9 @@ impl CreateLight for DiffuseAreaLight {
scale,
}
}
}
impl CreateLight for DiffuseAreaLight {
fn create(
arena: &mut Arena,
render_from_light: Transform,
@ -92,40 +110,44 @@ impl CreateLight for DiffuseAreaLight {
shape: &Shape,
alpha_text: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
) -> Result<Light, Error> {
let mut l = params.get_one_spectrum("l", None, SpectrumType::Illuminant);
let mut scale = params.get_one_float("scale", 1.);
let two_sided = params.get_one_bool("twosided", false);
let filename = resolve_filename(params.get_one_string("filename", ""));
let mut image_color_space = colorspace.clone();
if !filename.is_empty() {
let (image, image_color_space) = if !filename.is_empty() {
if l.is_some() {
panic!(
"{}: Both \"L\" and \"filename\" specified for DiffuseAreaLight.",
loc
);
}
let im = Image::read(filename, None);
let image: Image = im.image;
if image.has_any_infinite_pixels() {
panic!(
"{:?}: Image '{}' has NaN pixels. Not suitable for light.",
loc, filename
);
}
let channel_desc = image.get_channel_desc(&["R", "G", "B"]).expect(&format!(
"{:?}: Image '{}' must have R, G, B channels",
loc, filename
));
let selected_image = image.select_channels(channel_desc);
image_color_space = im.metadata.colorspace;
} else if l.is_none() {
l = Some(colorpace.unwrap().Illuminant.clone());
return Err(error!(loc, "both \"L\" and \"filename\" specified"));
}
let im = Image::read(&filename, None)?;
if im.image.has_any_infinite_pixels() {
return Err(error!(loc, "{}: image has infinite pixel values", filename));
}
if im.image.has_any_nan_pixels() {
return Err(error!(loc, "{}: image has NaN pixel values", filename));
}
let channel_desc = im
.image
.get_channel_desc(&["R", "G", "B"])
.ok_or_else(|| error!(loc, "{}: image must have R, G, B channels", filename))?;
let image = im.image.select_channels(&channel_desc);
let cs = im.metadata.get_color_space();
(Some(image), Some(cs))
} else {
if l.is_none() {
l = Some(colorspace.illuminant.clone());
}
(None, None)
};
let l_for_scale = l.as_ref().unwrap_or(&colorspace.illuminant);
let lemit_data = lookup_spectrum(l_for_scale);
scale /= spectrum_to_photometric(lemit_data);
scale /= spectrum_to_photometric(l_for_scale);
let phi_v = parameters.get_one_float("power", -1.0);
if phi_v > 0.0 {
@ -165,16 +187,16 @@ impl CreateLight for DiffuseAreaLight {
let specific = DiffuseAreaLight::new(
render_from_light,
medium.into(),
l,
l.as_ref(),
scale,
shape.upload(arena),
alpha.upload(arena),
image.upload(arena),
image_color_space.upload(arena),
Some(true),
true,
shape.area(),
);
Light::DiffuseArea(specific)
Ok(Light::DiffuseArea(specific))
}
}

View file

@ -8,21 +8,14 @@ use shared::core::medium::{Medium, MediumInterface};
use shared::core::shape::Shape;
use shared::lights::DistantLight;
use shared::spectra::RGBColorSpace;
use shared::utils::Transform;
use shared::utils::{Ptr, Transform};
impl CreateLight for DistantLight {
fn new(
render_from_light: Transform,
medium_interface: shared::core::medium::MediumInterface,
le: shared::core::spectrum::Spectrum,
scale: shared::Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<shared::Float>,
) -> Self {
pub trait CreateDistantLight {
fn new(render_from_light: Transform, le: Spectrum, scale: Float) -> Self;
}
impl CreateDistantLight for DistantLight {
fn new(render_from_light: Transform, le: Spectrum, scale: Float) -> Self {
let base = LightBase::new(
LightType::DeltaDirection,
render_from_light,
@ -37,7 +30,9 @@ impl CreateLight for DistantLight {
scene_radius: 0.,
}
}
}
impl CreateLight for DistantLight {
fn create(
arena: &mut Arena,
render_from_light: Transform,
@ -47,7 +42,7 @@ impl CreateLight for DistantLight {
shape: &Shape,
alpha_text: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
) -> Result<Light, Error> {
let l = parameters
.get_one_spectrum(
"L",
@ -55,7 +50,6 @@ impl CreateLight for DistantLight {
SpectrumType::Illuminant,
)
.unwrap();
let lemit = lookup_spectrum(l);
let mut scale = parameters.get_one_float("scale", 1);
let from = parameters.get_one_point3f("from", Point3f::new(0., 0., 0.));
@ -90,19 +84,9 @@ impl CreateLight for DistantLight {
if e_v > 0. {
sc *= e_v;
}
let specific = DistantLight::new(
final_render,
medium.into(),
le,
scale,
None,
None,
None,
None,
None,
None,
);
Light::Distant(specific)
let specific = DistantLight::new(final_render, l, scale);
Ok(Light::Distant(specific))
}
}

View file

@ -2,8 +2,10 @@ use crate::core::image::{Image, ImageIO, ImageMetadata};
use crate::core::light::{CreateLight, lookup_spectrum};
use crate::core::spectrum::spectrum_to_photometric;
use crate::core::texture::FloatTexture;
use crate::lights::distant::CreateDistantLight;
use crate::utils::sampling::PiecewiseConstant2D;
use crate::utils::{Arena, FileLoc, ParameterDictionary, resolve_filename};
use shared::Float;
use shared::core::image::ImageBase;
use shared::core::light::{Light, LightBase, LightType};
use shared::core::medium::{Medium, MediumInterface};
@ -11,21 +13,26 @@ use shared::core::spectrum::Spectrum;
use shared::core::texture::SpectrumType;
use shared::lights::GoniometricLight;
use shared::spectra::RGBColorSpace;
use shared::utils::Transform;
use shared::utils::containers::Array2D;
use shared::utils::{Ptr, Transform};
impl CreateLight for GoniometricLight {
pub trait CreateGoniometricLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: shared::Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<shared::Float>,
scale: Float,
image: Ptr<Image>,
) -> Self;
}
impl CreateGoniometricLight for GoniometricLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
image: Ptr<Image>,
) -> Self {
let base = LightBase::new(
LightType::DeltaPosition,
@ -44,7 +51,9 @@ impl CreateLight for GoniometricLight {
distrib,
}
}
}
impl CreateLight for GoniometricLight {
fn create(
arena: &mut Arena,
render_from_light: Transform,
@ -54,96 +63,50 @@ impl CreateLight for GoniometricLight {
shape: &Shape,
alpha_text: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
) -> Result<Light, Error> {
let i = params.get_one_spectrum(
"I",
colorspace.unwrap().illuminant,
SpectrumType::Illuminant,
);
let lemit_data = lookup_spectrum(&i_spectrum_def);
let sc = params.get_one_float("scale", 1.);
let filename = resolve_filename(params.get_one_string("filename", ""));
let mut image: Option<Image> = None;
if filename.is_empty() {
println!(
"{}: Both \"L\" and \"filename\" specified for DiffuseAreaLight.",
loc
)
let image = if filename.is_empty() {
None
} else {
let im = Image::read(filename, None).expect("Could not load image");
let loaded_img: Image = im.image;
let res = loaded_img.resolution();
let metadata: ImageMetadata = im.metadata;
if loaded_img.has_any_infinite_pixels() {
panic!(
"{:?}: Image '{}' has NaN pixels. Not suitable for light.",
loc, filename
);
}
if res.x() != res.y() {
panic!(
"{:?}: Image resolution ({}, {}) is non square. Unlikely that this is an equal area map.",
let im = Image::read(&filename, None)
.map_err(|e| error!(loc, "could not load image '{}': {}", filename, e))?;
let loaded = im.image;
let res = loaded.resolution();
if loaded.has_any_infinite_pixels() {
return Err(error!(
loc,
res.x(),
res.y(),
y()
);
}
let rgb_desc = loaded_img.get_channel_desc(&["R", "G", "B"]);
let y_desc = loaded_img.get_channel_desc(&["Y"]);
if let Ok(rgb) = rgb_desc {
if y_desc.is_ok() {
panic!(
"{:?}: Image '{}' has both RGB and Y channels. Ambiguous.",
loc, filename
);
}
let mut y_pixels = Vec::with_capacity((res.x * res.y) as usize);
for y in 0..res.y {
for x in 0..res.x {
let r = loaded_img.get_channel(Point2i::new(x, y), 0);
let g = loaded_img.get_channel(Point2i::new(x, y), 1);
let b = loaded_img.get_channel(Point2i::new(x, y), 2);
y_pixels.push((r + g + b) / 3.0);
}
}
loaded_img = Some(Image::new(
PixelFormat::F32,
res,
&["Y"],
ColorEncoding::Linear,
"image '{}' has infinite pixels, not suitable for light", filename
));
} else if y_desc.is_ok() {
image = Some(loaded_img);
} else {
panic!(
"{:?}: Image '{}' has neither RGB nor Y channels.",
loc, filename
);
}
if res.x != res.y {
return Err(error!(
loc,
"image resolution ({}, {}) is non-square; unlikely to be an equal-area map",
res.x,
res.y
));
}
Some(convert_to_luminance_image(&loaded, &filename, loc)?)
};
scale /= spectrum_to_photometric(&lemit_data);
let phi_v = params.get_one_float("power", -1.0);
if phi_v > 0.0 {
if let Some(ref img) = image {
let mut sum_y = 0.0;
let res = img.resolution();
for y in 0..res.y {
for x in 0..res.x {
sum_y += img.get_channel(Point2i::new(x, y), 0);
}
}
let k_e = 4.0 * PI * sum_y / (res.x * res.y) as Float;
scale *= phi_v / k_e;
let k_e = compute_emissive_power(image);
scale *= phi_v / phi_e;
}
}
@ -153,22 +116,71 @@ impl CreateLight for GoniometricLight {
let t = Transform::from_flat(swap_yz);
let final_render_from_light = render_from_light * t;
let d: Array2D<Float> = image.get_sampling_distribution();
distrib = PiecewiseConstant2D::new_with_data(d);
let specific =
GoniometricLight::new(final_render_from_light, medium.into(), le, scale, image);
let specific = GoniometricLight::new(
render_from_light,
medium_interface,
le,
scale,
None,
None,
Some(image),
None,
None,
None,
);
Light::Goniometric(specific)
Ok(Light::Goniometric(specific))
}
}
fn convert_to_luminance_image(
image: &Image,
filename: &str,
loc: &FileLoc,
) -> Result<Image, Error> {
let res = image.resolution();
let rgb_desc = image.get_channel_desc(&["R", "G", "B"]);
let y_desc = image.get_channel_desc(&["Y"]);
match (rgb_desc, y_desc) {
(Ok(_), Ok(_)) => Err(error!(
loc,
"image '{}' has both RGB and Y channels; ambiguous", filename
)),
(Ok(_), Err(_)) => {
// Convert RGB to Y (luminance)
let mut y_pixels = Vec::with_capacity((res.x * res.y) as usize);
for y in 0..res.y {
for x in 0..res.x {
let r = image.get_channel(Point2i::new(x, y), 0);
let g = image.get_channel(Point2i::new(x, y), 1);
let b = image.get_channel(Point2i::new(x, y), 2);
y_pixels.push((r + g + b) / 3.0);
}
}
Ok(Image::from_pixels(
PixelFormat::F32,
res,
&["Y"],
ColorEncoding::Linear,
&y_pixels,
))
}
(Err(_), Ok(_)) => {
// Already has Y channel, use as-is
Ok(image.clone())
}
(Err(_), Err(_)) => Err(error!(
loc,
"image '{}' has neither RGB nor Y channels", filename
)),
}
}
fn compute_emissive_power(image: &Image) -> Float {
let res = image.resolution();
let mut sum_y = 0.0;
for y in 0..res.y {
for x in 0..res.x {
sum_y += image.get_channel(Point2i::new(x, y), 0);
}
}
4.0 * PI * sum_y / (res.x * res.y) as Float
}

View file

@ -2,26 +2,32 @@ use shared::Float;
use shared::core::geometry::{Bounds3f, Point2f};
use shared::core::light::{CreateLight, Light, LightBase, LightType};
use shared::core::medium::MediumInterface;
use shared::lights::{InfiniteImageLight, InfinitePortalLight, InfiniteUniformLight};
use shared::core::spectrum::Spectrum;
use shared::lights::{ImageInfiniteLight, PortalInfiniteLight, UniformInfiniteLight};
use shared::spectra::RGBColorSpace;
use shared::utils::Transform;
use shared::utils::sampling::DevicePiecewiseConstant2D;
use shared::utils::{Ptr, Transform};
use std::sync::Arc;
use crate::core::light::{LightBaseTrait, lookup_spectrum};
impl CreateLight for InfiniteImageLight {
pub trait CreateImageInfiniteLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: shared::core::spectrum::Spectrum,
scale: Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<Float>,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
) -> Self;
}
impl CreateImageInfiniteLight for ImageInfiniteLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
scale: Float,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
) -> Self {
let base = LightBase::new(
LightType::Infinite,
@ -65,7 +71,7 @@ impl CreateLight for InfiniteImageLight {
let compensated_distrib = DevicePiecewiseConstant2D::new_with_bounds(&d, domain);
InfiniteImageLight {
ImageInfiniteLight {
base,
image: &image,
image_color_space: &storage.image_color_space,
@ -76,19 +82,6 @@ impl CreateLight for InfiniteImageLight {
compensated_distrib: &compensated_distrib,
};
}
fn create(
arena: &mut crate::utils::Arena,
render_from_light: Transform,
medium: Medium,
parameters: &crate::utils::ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> shared::core::light::Light {
todo!()
}
}
#[derive(Debug)]
@ -99,24 +92,29 @@ struct InfinitePortalLightStorage {
}
#[derive(Clone, Debug)]
pub struct InfinitePortalLightHost {
pub view: InfinitePortalLight,
pub struct PortalInfiniteLightHost {
pub view: PortalInfiniteLight,
pub filename: String,
_storage: Arc<InfinitePortalLightStorage>,
}
impl CreateLight for InfinitePortalLightHost {
pub trait CreatePortalInfiniteLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: shared::core::spectrum::Spectrum,
scale: Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<Float>,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
points: Ptr<Point3f>,
) -> Self;
}
impl CreatePortalInfiniteLight for PortalInfiniteLight {
fn new(
render_from_light: Transform,
scale: Float,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
points: Ptr<Point3f>,
) -> Self {
let base = LightBase::new(
LightType::Infinite,
@ -124,7 +122,7 @@ impl CreateLight for InfinitePortalLightHost {
&MediumInterface::default(),
);
let desc = equal_area_image
let desc = image
.get_channel_desc(&["R", "G", "B"])
.unwrap_or_else(|_| {
panic!(
@ -225,16 +223,10 @@ impl CreateLight for InfinitePortalLightHost {
let distribution = WindowedPiecewiseConstant2D::new(d);
let storage = Arc::new(InfinitePortalLightStorage {
image,
distribution,
image_color_space,
});
InfinitePortalLight {
PortalInfiniteLight {
base,
image,
image_color_space: &storage.image_color_space,
image_color_space: &image_color_space,
scale,
scene_center: Point3f::default(),
scene_radius: 0.,
@ -243,36 +235,14 @@ impl CreateLight for InfinitePortalLightHost {
distribution,
}
}
fn create(
arena: &mut crate::utils::Arena,
render_from_light: Transform,
medium: Medium,
parameters: &crate::utils::ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
todo!()
}
}
impl CreateLight for InfiniteUniformLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: shared::core::spectrum::Spectrum,
scale: Float,
shape: Option<shared::utils::Ptr<Shape>>,
alpha: Option<shared::utils::Ptr<FloatTexture>>,
image: Option<shared::utils::Ptr<Image>>,
image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<Float>,
cos_fallof_start: Option<Float>,
total_width: Option<Float>,
) -> Self {
pub trait CreateUniformInfiniteLight {
fn new(render_from_light: Transform, le: Spectrum, scale: Float) -> Self;
}
impl CreateUniformInfiniteLight for UniformInfiniteLight {
fn new(render_from_light: Transform, le: Spectrum, scale: Float) -> Self {
let base = LightBase::new(
LightType::Infinite,
&render_from_light,
@ -287,17 +257,135 @@ impl CreateLight for InfiniteUniformLight {
scene_radius: 0.,
}
}
}
fn create(
arena: &mut crate::utils::Arena,
pub fn create(
arena: &mut Arena,
render_from_light: Transform,
medium: Medium,
parameters: &crate::utils::ParameterDictionary,
medium: MediumInterface,
camera_transform: CameraTransform,
parameters: &ParameterDictionary,
colorspace: &RGBColorSpace,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
todo!()
) -> Result<Light, Error> {
let l = parameters.get_spectrum_array("L", SpectrumType::Illuminant);
let mut scale = parameters.get_one_float("scale", 1.0);
let portal = parameters.get_point3f_array("portal");
let filename = resolve_filename(parameters.get_one_string("filename", ""));
let e_v = parameters.get_one_float("illuminance", -1.0);
let has_spectrum = !l.is_empty();
let has_file = !filename.is_empty();
let has_portal = !portal.is_empty();
if has_spectrum && has_file {
return Err(error!(loc, "cannot specify both \"L\" and \"filename\""));
}
if !has_file && !has_portal {
let spectrum = if has_spectrum {
scale /= spectrum_to_photometric(&l[0]);
&l[0]
} else {
&colorspace.illuminant
};
if e_v > 0.0 {
scale *= e_v / PI;
}
let light = UniformInfiniteLight::new(render_from_light, lookup_spectrum(spectrum), scale);
return Ok(Light::InfiniteUniform(light));
}
// Image based
let (image, image_cs) = load_image_or_constant(&filename, &l, colorspace, loc)?;
scale /= spectrum_to_photometric(&image_cs.illuminant);
if e_v > 0.0 {
let k_e = compute_hemisphere_illuminance(&image, &image_cs);
scale *= e_v / k_e;
}
let image_ptr = image.upload(arena);
let cs_ptr = image_cs.upload(arena);
if has_portal {
let portal_render: Vec<Point3f> = portal
.iter()
.map(|p| camera_transform.render_from_world(*p))
.collect();
let light = PortalInfiniteLight::new(
render_from_light,
scale,
image_ptr,
cs_ptr,
arena.alloc_slice(&portal_render),
);
Ok(Light::InfinitePortal(light))
} else {
let light = ImageInfiniteLight::new(render_from_light, medium, scale, image_ptr, cs_ptr);
Ok(Light::InfiniteImage(light))
}
}
fn load_image_or_constant(
filename: &str,
l: &[Spectrum],
colorspace: &RGBColorSpace,
loc: &FileLoc,
) -> Result<(Image, RGBColorSpace), Error> {
if filename.is_empty() {
let rgb = spectrum_to_rgb(&l[0], colorspace);
let image = Image::new_constant(Point2i::new(1, 1), &["R", "G", "B"], &rgb);
Ok((image, colorspace.clone()))
} else {
let im = Image::read(filename, None)
.map_err(|e| error!(loc, "failed to load '{}': {}", filename, e))?;
if im.image.has_any_infinite_pixels() || im.image.has_any_nan_pixels() {
return Err(error!(loc, "image '{}' has invalid pixels", filename));
}
im.image
.get_channel_desc(&["R", "G", "B"])
.map_err(|_| error!(loc, "image '{}' must have R, G, B channels", filename))?;
let cs = im
.metadata
.color_space
.unwrap_or_else(|| colorspace.clone());
let selected = im.image.select_channels(&["R", "G", "B"])?;
Ok((selected, cs))
}
}
fn compute_hemisphere_illuminance(image: &Image, cs: &RGBColorSpace) -> Float {
let lum = cs.luminance_vector();
let res = image.resolution();
let mut sum = 0.0;
for y in 0..res.y {
let v = (y as Float + 0.5) / res.y as Float;
for x in 0..res.x {
let u = (x as Float + 0.5) / res.x as Float;
let w = equal_area_square_to_sphere(Point2f::new(u, v));
if w.z <= 0.0 {
continue;
}
let r = image.get_channel(Point2i::new(x, y), 0);
let g = image.get_channel(Point2i::new(x, y), 1);
let b = image.get_channel(Point2i::new(x, y), 2);
sum += (r * lum[0] + g * lum[1] + b * lum[2]) * cos_theta(&w);
}
}
sum * 2.0 * PI / (res.x * res.y) as Float
}

View file

@ -6,3 +6,13 @@ pub mod point;
pub mod projection;
pub mod sampler;
pub mod spot;
pub use diffuse::CreateDiffuseLight;
pub use distant::CreateDistantLight;
pub use goniometric::CreateGoniometricLight;
pub use infinite::{
CreateImageInfiniteLight, CreatePortalInfiniteLight, CreateUniformInfiniteLight,
};
pub use point::CreatePointLight;
pub use projection::CreateProjectionLight;
pub use spot::CreateSpotLight;

View file

@ -2,27 +2,31 @@ use crate::core::light::{CreateLight, LightBaseTrait, lookup_spectrum};
use crate::core::spectrum::spectrum_to_photometric;
use crate::core::texture::FloatTexture;
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::PI;
use shared::core::geometry::VectorLike;
use shared::core::light::{Light, LightBase, LightType};
use shared::core::medium::Medium;
use shared::core::medium::{Medium, MediumInterface};
use shared::core::shape::Shape;
use shared::core::spectrum::Spectrum;
use shared::lights::PointLight;
use shared::spectra::RGBColorSpace;
use shared::utils::Transform;
use shared::{Float, PI};
impl CreateLight for PointLight {
pub trait CreatePointLight {
fn new(
render_from_light: Transform,
medium_interface: shared::core::medium::MediumInterface,
le: shared::core::spectrum::Spectrum,
scale: shared::Float,
_shape: Option<shared::utils::Ptr<Shape>>,
_alpha: Option<shared::utils::Ptr<FloatTexture>>,
_image: Option<shared::utils::Ptr<Image>>,
_image_color_space: Option<shared::utils::Ptr<RGBColorSpace>>,
_two_sided: Option<bool>,
_fov: Option<shared::Float>,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
) -> Self;
}
impl CreatePointLight for PointLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
) -> Self {
let base = LightBase::new(
LightType::DeltaPosition,
@ -33,7 +37,9 @@ impl CreateLight for PointLight {
Self { base, scale, i }
}
}
impl CreateLight for PointLight {
fn create(
arena: &mut Arena,
render_from_light: Transform,
@ -43,7 +49,7 @@ impl CreateLight for PointLight {
shape: &Shape,
alpha_text: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
) -> Result<Light, Error> {
let l = parameters
.get_one_spectrum(
"L",
@ -51,7 +57,6 @@ impl CreateLight for PointLight {
SpectrumType::Illuminant,
)
.unwrap();
let lemit = lookup_spectrum(l);
let mut scale = parameters.get_one_float("scale", 1);
scale /= spectrum_to_photometric(l.unwrap());
let phi_v = parameters.get_one_float("power", 1.);
@ -63,12 +68,7 @@ impl CreateLight for PointLight {
let from = parameters.get_one_point3f("from", Point3f::zero());
let tf = Transform::translate(from.into());
let final_render = render_from_light * tf;
let base = LightBase::new(LightType::DeltaPosition, render_from_light, medium.into());
let specific = PointLight {
base,
scale,
i: arena.alloc(lemit),
};
Light::Point(specific)
let specific = PointLight::new(final_render, medium.into(), l, scale);
Ok(Light::Point(specific))
}
}

View file

@ -2,7 +2,8 @@ use crate::core::image::{Image, ImageIO, ImageMetadata};
use crate::core::light::CreateLight;
use crate::core::spectrum::spectrum_to_photometric;
use crate::spectra::colorspace::new;
use crate::utils::{Ptr, Upload, resolve_filename};
use crate::utils::{Arena, ParameterDictionary, Ptr, Upload, resolve_filename};
use shared::Float;
use shared::core::geometry::{Bounds2f, VectorLike};
use shared::core::image::ImageAccess;
use shared::core::light::{Light, LightBase};
@ -13,18 +14,27 @@ use shared::spectra::RGBColorSpace;
use shared::utils::math::{radians, square};
use shared::utils::{Ptr, Transform};
impl CreateLight for ProjectionLight {
pub trait CreateProjectionLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: shared::Float,
shape: Option<Ptr<Shape>>,
alpha: Option<Ptr<FloatTexture>>,
image: Option<Ptr<Image>>,
image_color_space: Option<Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<shared::Float>,
scale: Float,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
fov: Float,
) -> Self;
}
impl CreateProjectionLight for ProjectionLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: Float,
image: Ptr<Image>,
image_color_space: Ptr<RGBColorSpace>,
fov: Float,
) -> Self {
let base = LightBase::new(
LightType::DeltaPosition,
@ -69,96 +79,122 @@ impl CreateLight for ProjectionLight {
a,
}
}
}
impl CreateLight for ProjectionLight {
fn create(
arena: &mut crate::utils::Arena,
render_from_light: shared::utils::Transform,
arena: &mut Arena,
render_from_light: Transform,
medium: Medium,
parameters: &crate::utils::ParameterDictionary,
parameters: &ParameterDictionary,
loc: &FileLoc,
_shape: &Shape,
_alpha_text: &FloatTexture,
_colorspace: Option<&shared::spectra::RGBColorSpace>,
) -> Light {
colorspace: Option<&RGBColorSpace>,
) -> Result<Light, Error> {
let mut scale = parameters.get_one_float("scale", 1.);
let power = parameters.get_one_float("power", -1.);
let fov = parameters.get_one_float("fov", 90.);
let filename = resolve_filename(parameters.get_one_string("filename", ""));
if filename.is_empty() {
panic!(
"{}: Must provide filename for projection light source.",
loc
);
return Err(error!(loc, "must provide filename for projection light"));
}
let im = Image::read(filename, None).unwrap();
let image: Image = im.image;
let metadata: ImageMetadata = im.metadata;
if image.has_any_infinite_pixels() {
panic!(
"{:?}: Image '{}' has NaN pixels. Not suitable for light.",
loc, filename
);
let im = Image::read(&filename, None)
.map_err(|e| error!(loc, "could not load image '{}': {}", filename, e))?;
if im.image.has_any_infinite_pixels() {
return Err(error!(
loc,
"image '{}' has infinite pixels, not suitable for light", filename
));
}
let colorspace: RGBColorSpace = metadata.colorspace.unwrap();
let channel_desc = image
if im.image.has_any_nan_pixels() {
return Err(error!(
loc,
"image '{}' has NaN pixels, not suitable for light", filename
));
}
let channel_desc = im
.image
.get_channel_desc(&["R", "G", "B"])
.unwrap_or_else(|_| {
panic!(
"{:?}: Image '{}' must have R, G and B channels.",
loc, filename
)
});
let image = image.select_channels(channel_desc);
.map_err(|_| error!(loc, "image '{}' must have R, G, B channels", filename))?;
let image = im.image.select_channels(&channel_desc);
let colorspace = im
.metadata
.colorspace
.ok_or_else(|| error!(loc, "image '{}' missing colorspace metadata", filename))?;
scale /= spectrum_to_photometric(colorspace.illuminant);
if power > 0. {
let hither = 1e-3;
let aspect = image.resolution().x() as Float / image.resolution().y() as Float;
let screen_bounds = if aspect > 1. {
Bounds2f::from_poins(Point2f::new(-aspect, -1.), Point2f::new(aspect, 1.))
} else {
Bounds2f::from_points(
Point2f::new(-1., -1. / aspect),
Point2f::new(1., 1. / aspect),
)
};
let screen_from_light = Transform::perspective(fov, hither, 1e30);
let light_from_screen = screen_from_light.inverse();
let opposite = (radians(fov) / 2.).tan();
let aspect_factor = if aspect > 1. { aspect } else { 1. / aspect };
let a = 4. * square(aspect_factor);
let mut sum = 0;
let luminance = colorspace.luminance_vector();
let res = image.resolution();
for y in 0..res.y() {
for x in 0..res.x() {
let lerp_factor = Point2f::new((x + 0.5) / res.x(), (y + 0.5) / res.y());
let ps = screen_bounds.lerp(lerp_factor);
let w_point =
light_from_screen.apply_to_point(Point3f::new(ps.x(), ps.y(), 0.));
let w = Vector3f::from(w_point).normalize();
let dwda = w.z().powi(3);
for c in 0..3 {
sum += image.get_channel(Point2f::new(x, y), c) * luminance[c] * dwda;
}
}
}
scale *= power / (a * sum / (res.x() + res.y()));
let k_e = compute_emissive_power(&image, colorspace, fov);
}
let flip = Transform::scale(1., -1., 1.);
let render_from_light_flip = render_from_light * flip;
let specific = Self::new(
render_from_light,
let specific = ProjectionLight::new(
render_from_light_flip,
medium_interface,
le,
scale,
None,
None,
image.upload(arena),
None,
None,
None,
colorspace.upload(arena),
fov,
);
Light::Projection(specific)
Ok(Light::Projection(specific))
}
}
fn compute_screen_bounds(aspect: Float) -> Bounds2f {
if aspect > 1.0 {
Bounds2f::from_points(Point2f::new(-aspect, -1.0), Point2f::new(aspect, 1.0))
} else {
Bounds2f::from_points(
Point2f::new(-1.0, -1.0 / aspect),
Point2f::new(1.0, 1.0 / aspect),
)
}
}
fn compute_emissive_power(image: &Image, colorspace: &RGBColorSpace, fov: Float) -> Float {
let res = image.resolution();
let aspect = res.x() as Float / res.y() as Float;
let screen_bounds = compute_screen_bounds(aspect);
let hither = 1e-3;
let screen_from_light =
Transform::perspective(fov, hither, 1e30).expect("Failed to create perspective transform");
let light_from_screen = screen_from_light.inverse();
let opposite = (radians(fov) / 2.0).tan();
let aspect_factor = if aspect > 1.0 { aspect } else { 1.0 / aspect };
let a = 4.0 * square(opposite) * aspect_factor;
let luminance = colorspace.luminance_vector();
let mut sum: Float = 0.0;
for y in 0..res.y() {
for x in 0..res.x() {
let lerp_factor = Point2f::new(
(x as Float + 0.5) / res.x() as Float,
(y as Float + 0.5) / res.y() as Float,
);
let ps = screen_bounds.lerp(lerp_factor);
let w_point = light_from_screen.apply_to_point(Point3f::new(ps.x(), ps.y(), 0.0));
let w = Vector3f::from(w_point).normalize();
let dwda = w.z().powi(3);
for c in 0..3 {
sum += image.get_channel(Point2i::new(x, y), c) * luminance[c] * dwda;
}
}
}
a * sum / (res.x() * res.y()) as Float
}

View file

@ -2,8 +2,7 @@ use crate::core::image::{Image, ImageIO, ImageMetadata};
use crate::core::light::CreateLight;
use crate::core::spectrum::spectrum_to_photometric;
use crate::spectra::colorspace::new;
use crate::utils::{Ptr, Upload, resolve_filename};
use shared::PI;
use crate::utils::{Arena, ParameterDictionary, Ptr, Upload, resolve_filename};
use shared::core::geometry::{Bounds2f, Frame, VectorLike};
use shared::core::image::ImageAccess;
use shared::core::light::{Light, LightBase, LightType};
@ -14,21 +13,28 @@ use shared::lights::{ProjectionLight, SpotLight};
use shared::spectra::RGBColorSpace;
use shared::utils::math::{radians, square};
use shared::utils::{Ptr, Transform};
use shared::{Float, PI};
impl CreateLight for SpotLight {
pub trait CreateSpotLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: shared::Float,
shape: Option<Ptr<Shape>>,
alpha: Option<Ptr<FloatTexture>>,
image: Option<Ptr<Image>>,
image_color_space: Option<Ptr<RGBColorSpace>>,
two_sided: Option<bool>,
fov: Option<shared::Float>,
cos_falloff_start: Option<shared::Float>,
total_width: Option<shared::Float>,
cos_falloff_start: Float,
total_width: Float,
) -> Self;
}
impl CreateSpotLight for SpotLight {
fn new(
render_from_light: Transform,
medium_interface: MediumInterface,
le: Spectrum,
scale: shared::Float,
image: Ptr<Image>,
cos_falloff_start: Float,
total_width: Float,
) -> Self {
let base = LightBase::new(
LightType::DeltaPosition,
@ -41,21 +47,23 @@ impl CreateLight for SpotLight {
base,
iemit,
scale,
cos_falloff_end: radians(total_width.unwrap().cos()),
cos_falloff_start: radians(cos_falloff_start.unwrap().cos()),
cos_falloff_end: radians(total_width).cos(),
cos_falloff_start: radians(cos_falloff_start).cos(),
}
}
}
impl CreateLight for SpotLight {
fn create(
arena: &mut crate::utils::Arena,
arena: &mut Arena,
render_from_light: Transform,
medium: Medium,
parameters: &crate::utils::ParameterDictionary,
parameters: &ParameterDictionary,
loc: &FileLoc,
shape: &Shape,
alpha_tex: &FloatTexture,
colorspace: Option<&RGBColorSpace>,
) -> Light {
) -> Result<Light, Error> {
let i = parameters
.get_one_spectrum(
"I",
@ -87,14 +95,9 @@ impl CreateLight for SpotLight {
medium.into(),
le,
scale,
None,
None,
None,
None,
None,
None,
Some(coneangle),
Some(coneangle - conedelta),
coneangle,
coneangle - conedelta,
);
Ok(Light::Spot(specific))
}
}

View file

@ -1,6 +1,6 @@
use crate::core::image::ImageBuffer;
use crate::core::image::Image;
use crate::core::material::CreateMaterial;
use crate::utils::parameters::ParameterDictionary;
use crate::utils::{Arena, ParameterDictionary};
use shared::core::spectrum::Spectrum;
use shared::core::texture::SpectrumType;
use shared::materials::coated::*;
@ -10,9 +10,10 @@ use shared::textures::SpectrumConstantTexture;
impl CreateMaterial for CoatedDiffuseMaterial {
fn create(
parameters: &TextureParameterDictionary,
normal_map: Option<Arc<ImageBuffer>>,
normal_map: Option<Arc<Image>>,
named_materials: &HashMap<String, Material>,
loc: &FileLoc,
area: &mut Arena,
) -> Self {
let reflectance = parameters
.get_spectrum_texture("reflectance", None, SpectrumType::Albedo)
@ -45,15 +46,30 @@ impl CreateMaterial for CoatedDiffuseMaterial {
});
let displacement = parameters.get_float_texture("displacement");
let remap_roughness = parameters.get_one_bool("remaproughness", true);
arena.alloc(Self::new(
reflectance,
u_roughness,
v_roughness,
thickness,
albedo,
g,
eta,
displacement,
normal_map,
remap_roughness,
max_depth,
n_samples,
));
}
}
impl CreateMaterial for CoatedConductorMaterial {
fn create(
parameters: &TextureParameterDictionary,
normal_map: Option<Arc<ImageBuffer>>,
normal_map: Option<Arc<Image>>,
named_materials: &HashMap<String, Material>,
loc: &FileLoc,
arena: &mut Arena,
) -> Result<Self, String> {
let interface_u_roughness = parameters
.get_float_texture_or_null("interface.uroughness")
@ -106,7 +122,7 @@ impl CreateMaterial for CoatedConductorMaterial {
});
let displacement = parameters.get_float_texture_or_null("displacement");
let remap_roughness = parameters.get_one_bool("remaproughness", true);
Self::new(
let material = Self::new(
displacement,
normal_map,
interface_u_roughness,
@ -123,6 +139,8 @@ impl CreateMaterial for CoatedConductorMaterial {
remap_roughness,
max_depth,
n_samples,
)
);
arena.alloc(material);
return material;
}
}

View file

@ -1,4 +1,5 @@
use crate::core::material::CreateMaterial;
use crate::utils::{Arena, FileLoc, TextureParameterDictionary};
use shared::core::bxdf::HairBxDF;
use shared::core::spectrum::Spectrum;
use shared::core::texture::{GPUFloatTexture, GPUSpectrumTexture};
@ -10,6 +11,7 @@ impl CreateMaterial for HairMaterial {
normal_map: Option<Arc<ImageBuffer>>,
named_materials: &HashMap<String, Material>,
loc: &FileLoc,
arena: &mut Arena,
) -> Result<Self, String> {
let sigma_a = parameters.get_spectrum_texture_or_null("sigma_a", SpectrumType::Unbounded);
let reflectance = parameters
@ -57,7 +59,7 @@ impl CreateMaterial for HairMaterial {
let beta_m = parameters.get_float_texture("beta_m", 0.3);
let beta_n = parameters.get_float_texture("beta_n", 0.3);
let alpha = parameters.get_float_texture("alpha", 2.);
HairMaterial::new(
let material = HairMaterial::new(
sigma_a,
reflectance,
eumelanin,
@ -66,7 +68,10 @@ impl CreateMaterial for HairMaterial {
beta_m,
beta_n,
alpha,
)
);
arena.alloc(material);
return material;
}
}

View file

@ -9,8 +9,8 @@ use crate::core::scattering::TrowbridgeReitzDistribution;
use crate::core::spectrum::{Spectrum, SpectrumTrait};
use crate::core::texture::{GPUFloatTexture, GPUSpectrumTexture, TextureEvaluator};
use crate::spectra::{SampledSpectrum, SampledWavelengths};
use crate::utils::Ptr;
use crate::utils::math::clamp;
use shared::utils::Ptr;
#[repr(C)]
#[derive(Clone, Copy, Debug)]

View file

@ -1,11 +1,12 @@
use crate::core::shape::{ALL_BILINEAR_MESHES, CreateShape};
use crate::core::shape::{ALL_BILINEAR_MESHES, CreateMesh, CreateShape};
use crate::core::texture::FloatTexture;
use crate::shapes::mesh::BilinearPatchMeshHost;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::shapes::mesh::Mesh;
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::shapes::BilinearPatchShape;
use shared::utils::Transform;
use std::collections::HashMap;
impl CreateShape for BilinearPatchShape {
impl CreateMesh for BilinearPatchShape {
fn create(
render_from_object: &Transform,
_object_from_render: &Transform,
@ -13,6 +14,7 @@ impl CreateShape for BilinearPatchShape {
parameters: &ParameterDictionary,
_float_textures: &HashMap<String, FloatTexture>,
_loc: &FileLoc,
arena: &mut Arena,
) -> Result<Mesh, String> {
let mut vertex_indices = parameters.get_int_array("indices");
let mut p = parameters.get_point3f_array("P");
@ -128,6 +130,7 @@ impl CreateShape for BilinearPatchShape {
rectangle: false,
}));
}
arena.alloc(shapes);
Ok(shapes)
}
}

View file

@ -194,6 +194,7 @@ impl CreateShape for CurveShape {
curves.extend(new_curves);
}
arena.alloc(curves);
Ok(curves)
}
}

View file

@ -1,6 +1,6 @@
use crate::core::shape::CreateShape;
use crate::core::texture::FloatTexture;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::core::shape::Shape;
use shared::shapes::CylinderShape;
use shared::utils::Transform;
@ -15,6 +15,7 @@ impl CreateShape for CylinderShape {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Result<Vec<Shape>, String> {
let radius = parameters.get_one_float("radius", 1.);
let z_min = parameters.get_one_float("zmin", -1.);
@ -30,6 +31,7 @@ impl CreateShape for CylinderShape {
phi_max,
);
arena.alloc(Shape::Cylinder(shape));
Ok(vec![Shape::Cylinder(shape)])
}
}

View file

@ -1,6 +1,6 @@
use crate::core::shape::CreateShape;
use crate::core::texture::FloatTexture;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::core::shape::Shape;
use shared::shapes::DiskShape;
use shared::utils::Transform;
@ -15,6 +15,7 @@ impl CreateShape for DiskShape {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Result<Vec<Shape>, String> {
let height = parameters.get_one_float("height", 0.);
let radius = parameters.get_one_float("radius", 1.);
@ -30,6 +31,7 @@ impl CreateShape for DiskShape {
reverse_orientation,
);
arena.alloc(Shape::Disk(shape));
Ok(vec![Shape::Disk(shape)])
}
}

View file

@ -3,7 +3,7 @@ use ply_rs::parser::Parser;
use ply_rs::ply::{DefaultElement, Property};
use shared::utils::Transform;
use shared::utils::mesh::{BilinearPatchMesh, TriangleMesh};
use shared::utils::sampling::PiecewiseConstant2D;
use shared::utils::sampling::DevicePiecewiseConstant2D;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
@ -211,40 +211,32 @@ impl TriQuadMesh {
}
}
#[derive(Debug, Clone, Copy)]
pub struct TriangleMeshStorage {
pub trait TriangleMeshFactory {
fn create(
arena: &mut Arena,
render_from_object: &Transform,
reverse_orientation: bool,
vertex_indices: Vec<u32>,
p: Vec<Point3f>,
n: Vec<Normal3f>,
s: Vec<Vector3f>,
uv: Vec<Point2f>,
face_indices: Vec<u32>,
) -> ArenaPtr<TriangleMesh>;
}
#[derive(Debug, Clone, Copy)]
pub struct TriangleMeshHost {
pub view: TriangleMesh,
_storage: Arc<TriangleMeshStorage>,
}
impl Deref for TriangleMeshHost {
type Target = TriangleMesh;
fn deref(&self) -> &Self::Target {
&self.view
}
}
impl TriangleMeshHost {
pub fn new(
render_from_object: Transform,
impl TriangleMeshFactory for TriangleMesh {
fn create(
arena: &mut Arena,
render_from_object: &Transform,
reverse_orientation: bool,
vertex_indices: Vec<usize>,
mut p: Vec<Point3f>,
mut s: Vec<Vector3f>,
mut n: Vec<Normal3f>,
vertex_indices: Vec<u32>,
p: Vec<Point3f>,
n: Vec<Normal3f>,
s: Vec<Vector3f>,
uv: Vec<Point2f>,
face_indices: Vec<usize>,
) -> Self {
face_indices: Vec<u32>,
) -> ArenaPtr<TriangleMesh> {
let n_triangles = indices.len() / 3;
let n_vertices = p.len();
for pt in p.iter_mut() {
@ -342,7 +334,7 @@ pub struct BilinearMeshStorage {
p: Vec<Point3f>,
n: Vec<Normal3f>,
uv: Vec<Point2f>,
image_distribution: Option<PiecewiseConstant2D>,
image_distribution: Option<DevicePiecewiseConstant2D>,
}
#[derive(Debug, Clone, Copy)]
@ -366,7 +358,7 @@ impl BilinearPatchMeshHost {
mut p: Vec<Point3f>,
mut n: Vec<Normal3f>,
uv: Vec<Point2f>,
image_distribution: Option<PiecewiseConstant2D>,
image_distribution: Option<DevicePiecewiseConstant2D>,
) -> Self {
let n_patches = indices.len() / 3;
let n_vertices = p.len();

View file

@ -1,6 +1,6 @@
use crate::core::shape::CreateShape;
use crate::core::texture::FloatTexture;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::core::shape::Shape;
use shared::shapes::SphereShape;
use shared::utils::Transform;
@ -14,6 +14,7 @@ impl CreateShape for SphereShape {
parameters: ParameterDictionary,
float_textures: HashMap<String, FloatTexture>,
loc: FileLoc,
arena: &mut Arena,
) -> Result<Vec<Shape>, String> {
let radius = parameters.get_one_float("radius", 1.);
let zmin = parameters.get_one_float("zmin", -radius);
@ -28,6 +29,7 @@ impl CreateShape for SphereShape {
zmax,
phimax,
);
arena.alloc(vec![Shape::Sphere(SphereShape)]);
Ok(vec![Shape::Sphere(SphereShape)])
}
}

View file

@ -1,7 +1,7 @@
use crate::core::shape::{ALL_TRIANGLE_MESHES, CreateShape};
use crate::core::texture::FloatTexture;
use crate::shapes::mesh::TriangleMeshHost;
use crate::utils::{FileLoc, ParameterDictionary};
use crate::utils::{Arena, FileLoc, ParameterDictionary};
use shared::shapes::TriangleShape;
use shared::utils::Transform;
@ -12,6 +12,7 @@ impl CreateShape for TriangleShape {
reverse_orientation: bool,
parameters: ParameterDictionary,
loc: FileLoc,
arena: &mut Arena,
) -> Result<Mesh, String> {
let mut vertex_indices = parameters.get_int_array("indices");
let mut p = parameters.get_point3f_array("P");
@ -104,6 +105,8 @@ impl CreateShape for TriangleShape {
tri_index: i,
}));
}
arena.alloc(shapes);
Ok(shapes)
}
}

View file

@ -134,7 +134,7 @@ impl SpectrumTextureTrait for SpectrumImageTexture {
#[derive(Debug, Clone)]
pub struct FloatImageTexture {
base: ImageTextureBase,
pub base: ImageTextureBase,
}
impl FloatImageTexture {

View file

@ -1,16 +1,16 @@
use crate::core::texture::{
FloatTexture, FloatTextureTrait, SpectrumTexture, SpectrumTextureTrait,
};
use crate::utils::{FileLoc, TextureParameterDictionary};
use crate::utils::{Arena, FileLoc, TextureParameterDictionary};
use shared::core::geometry::Vector3f;
use shared::utils::Transform;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct FloatMixTexture {
tex1: Arc<FloatTexture>,
tex2: Arc<FloatTexture>,
amount: Arc<FloatTexture>,
pub tex1: Arc<FloatTexture>,
pub tex2: Arc<FloatTexture>,
pub amount: Arc<FloatTexture>,
}
impl FloatMixTexture {
@ -26,11 +26,12 @@ impl FloatMixTexture {
_render_from_texture: &Transform,
params: &TextureParameterDictionary,
_loc: &FileLoc,
arena: &mut Arena,
) -> Self {
let tex1 = params.get_float_texture("tex1", 0.);
let tex2 = params.get_float_texture("tex2", 1.);
let amount = params.get_float_texture("amount", 0.5);
Self::new(tex1, tex2, amount)
arena.alloc(Self::new(tex1, tex2, amount))
}
}
@ -51,9 +52,9 @@ impl FloatTextureTrait for FloatMixTexture {
#[derive(Debug, Clone)]
pub struct FloatDirectionMixTexture {
tex1: Arc<FloatTexture>,
tex2: Arc<FloatTexture>,
dir: Vector3f,
pub tex1: Arc<FloatTexture>,
pub tex2: Arc<FloatTexture>,
pub dir: Vector3f,
}
impl FloatDirectionMixTexture {
@ -65,12 +66,13 @@ impl FloatDirectionMixTexture {
render_from_texture: &Transform,
params: &TextureParameterDictionary,
_loc: &FileLoc,
arena: &mut Arena,
) -> Self {
let dir_raw = params.get_one_vector3f("dir", Vector3f::new(0., 1., 0.));
let dir = render_from_texture.apply_to_vector(dir_raw).normalize();
let tex1 = params.get_float_texture("tex1", 0.);
let tex2 = params.get_float_texture("tex2", 1.);
Self::new(tex1, tex2, dir)
arena.alloc(Self::new(tex1, tex2, dir))
}
}

View file

@ -1,4 +1,4 @@
use crate::utils::{FileLoc, TextureParameterDictionary};
use crate::utils::{Arena, FileLoc, TextureParameterDictionary};
use shared::core::texture::{SpectrumType, TextureEvalContext};
use shared::spectra::ColorEncoding;
use shared::spectra::color::RGB;

View file

@ -1,15 +1,15 @@
use crate::core::texture::{
FloatTexture, FloatTextureTrait, SpectrumTexture, SpectrumTextureTrait,
};
use crate::utils::{FileLoc, TextureParameterDictionary};
use crate::utils::{Arena, FileLoc, TextureParameterDictionary};
use shared::core::texture::TextureEvalContext;
use shared::spectra::{SampledSpectrum, SampledWavelengths};
use shared::utils::Transform;
#[derive(Debug, Clone)]
pub struct FloatScaledTexture {
tex: Arc<FloatTexture>,
scale: Arc<FloatTexture>,
pub tex: Arc<FloatTexture>,
pub scale: Arc<FloatTexture>,
}
impl FloatScaledTexture {
@ -21,6 +21,7 @@ impl FloatScaledTexture {
_render_from_texture: &Transform,
params: &TextureParameterDictionary,
_loc: &FileLoc,
arena: &mut Arena,
) -> FloatTexture {
let mut tex = params.get_float_texture("tex", 1.);
let mut scale = params.get_float_texture("scale", 1.);
@ -40,6 +41,7 @@ impl FloatScaledTexture {
std::mem::swap(&mut tex, &mut scale);
}
std::mem::swap(&mut tex, &mut scale);
arena.alloc(FloatScaledTexture::new(tex, scale));
FloatTexture::FloatScaled(FloatScaledTexture::new(tex, scale))
}
}
@ -56,8 +58,8 @@ impl FloatTextureTrait for FloatScaledTexture {
#[derive(Clone, Debug)]
pub struct SpectrumScaledTexture {
tex: Arc<SpectrumTexture>,
scale: Arc<FloatTexture>,
pub tex: Arc<SpectrumTexture>,
pub scale: Arc<FloatTexture>,
}
impl SpectrumTextureTrait for SpectrumScaledTexture {

View file

@ -1,7 +1,6 @@
use crate::core::image::Image;
use crate::core::texture::FloatTexture;
use crate::utils::sampling::PiecewiseConstant2D;
use core::alloc::Layout;
use shared::Float;
use shared::core::color::RGBToSpectrumTable;
use shared::core::image::DeviceImage;
@ -11,61 +10,75 @@ use shared::spectra::{RGBColorSpace, StandardColorSpaces};
use shared::textures::*;
use shared::utils::Ptr;
use shared::utils::sampling::DevicePiecewiseConstant2D;
use std::alloc::Layout;
pub struct Arena {
buffer: Vec<u8>,
buffer: Vec<(*mut u8, Layout)>,
}
impl Arena {
pub fn new() -> Self {
Self {
buffer: Vec::with_capacity(64 * 1024 * 1024),
}
Self { buffer: Vec::new() }
}
pub fn alloc<T: Copy>(&mut self, value: T) -> Ptr<T> {
pub fn alloc<T>(&mut self, value: T) -> Ptr<T> {
let layout = Layout::new::<T>();
let offset = self.alloc_raw(layout);
let ptr = unsafe { self.alloc_unified(layout) } as *mut T;
// Write the value
unsafe {
let ptr = self.buffer.as_mut_ptr().add(offset) as *mut T;
std::ptr::write(ptr, value);
ptr.write(value);
}
Ptr {
offset: offset as i32,
_marker: std::marker::PhantomData,
Ptr::from_raw(ptr)
}
pub fn alloc_opt<T>(&mut self, value: Option<T>) -> Ptr<T> {
match value {
Some(v) => self.alloc(v),
None => Ptr::null(),
}
}
pub fn alloc_slice<T: Copy>(&mut self, values: &[T]) -> Ptr<T> {
pub fn alloc_slice<T: Copy>(&mut self, values: &[T]) -> (Ptr<T>, usize) {
if values.is_empty() {
return (Ptr::null(), 0);
}
let layout = Layout::array::<T>(values.len()).unwrap();
let offset = self.alloc_raw(layout);
let ptr = unsafe { self.alloc_unified(layout) } as *mut T;
unsafe {
let ptr = self.buffer.as_mut_ptr().add(offset) as *mut T;
std::ptr::copy_nonoverlapping(values.as_ptr(), ptr, values.len());
}
Ptr {
offset: offset as i32,
_marker: std::marker::PhantomData,
}
(Ptr::from_raw(ptr), values.len())
}
fn alloc_raw(&mut self, layout: Layout) -> usize {
let len = self.buffer.len();
let align_offset = (len + layout.align() - 1) & !(layout.align() - 1);
let new_len = align_offset + layout.size();
#[cfg(feature = "cuda")]
unsafe fn alloc_unified(&mut self, layout: Layout) -> *mut u8 {
use cuda_runtime_sys::*;
if new_len > self.buffer.capacity() {
// Growth strategy: Double capacity to reduce frequency of resizing
let new_cap = std::cmp::max(self.buffer.capacity() * 2, new_len);
self.buffer.reserve(new_cap - self.buffer.len());
let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut();
let size = layout.size().max(layout.align());
let result = cudaMallocManaged(&mut ptr, size, cudaMemAttachGlobal);
if result != cudaError::cudaSuccess {
panic!("cudaMallocManaged failed: {:?}", result);
}
self.buffer.resize(new_len, 0);
align_offset
self.allocations.push((ptr as *mut u8, layout));
ptr as *mut u8
}
#[cfg(not(feature = "cuda"))]
unsafe fn alloc_unified(&mut self, layout: Layout) -> *mut u8 {
// Fallback: regular allocation for CPU-only testing
let ptr = std::alloc::alloc(layout);
self.allocations.push((ptr, layout));
ptr
}
pub fn raw_data(&self) -> &[u8] {
@ -73,6 +86,23 @@ impl Arena {
}
}
impl Drop for UnifiedArena {
fn drop(&mut self) {
for (ptr, layout) in self.allocations.drain(..) {
unsafe {
#[cfg(feature = "cuda")]
{
cuda_runtime_sys::cudaFree(ptr as *mut _);
}
#[cfg(not(feature = "cuda"))]
{
std::alloc::dealloc(ptr, layout);
}
}
}
}
}
pub trait Upload {
type Target: Copy;
@ -87,10 +117,10 @@ impl Upload for Shape {
}
impl Upload for Image {
type Target = DeviceImage;
type Target = Image;
fn upload(&self, arena: &mut Arena) -> Ptr<Self::Target> {
let pixels_ptr = arena.alloc_slice(&self.storage_as_slice());
let device_img = DeviceImage {
let device_img = Image {
base: self.base,
pixels: pixels_ptr,
};

View file

@ -1,5 +1,5 @@
use crate::core::geometry::{Bounds2i, Point2i};
use crate::shared::utils::containers::Array2D;
use shared::utils::containers::Array2D;
use std::ops::{Deref, DerefMut};
pub struct InternCache<T> {
@ -20,7 +20,7 @@ where
let mut lock = self.cache.lock().unwrap();
if let Some(existing) = lock.get(&value) {
return existing.clone(); // Returns a cheap Arc copy
return existing.clone();
}
let new_item = Arc::new(value);

View file

@ -1,6 +1,6 @@
use half::f16;
use shared::Float;
use shared::utils::Ptr;
use shared::utils::DevicePtr;
use shared::utils::math::{DigitPermutation, PRIMES};
pub fn new_digit_permutation(base: u32, seed: u64) -> Vec<u16> {
@ -56,7 +56,7 @@ pub fn compute_radical_inverse_permutations(seed: u64) -> (Vec<u16>, Vec<DigitPe
views.push(DigitPermutation::new(
base as u32,
n_digits,
Ptr(ptr_to_data),
DevicePtr(ptr_to_data),
));
}

View file

@ -1,3 +1,4 @@
pub mod arena;
pub mod containers;
pub mod error;
pub mod file;
@ -8,7 +9,9 @@ pub mod parallel;
pub mod parameters;
pub mod parser;
pub mod sampling;
pub mod strings;
pub use arena::{Arena, Upload};
pub use error::FileLoc;
pub use file::{read_float_file, resolve_filename};
pub use parameters::{

View file

@ -1,128 +1,186 @@
use shared::Float;
use shared::core::geometry::{Bounds2f, Point2f};
use shared::utils::Ptr;
use shared::utils::DevicePtr;
use shared::utils::sampling::{
AliasTable, PiecewiseConstant1D, PiecewiseConstant2D, PiecewiseLinear2D,
AliasTable, DevicePiecewiseConstant1D, DevicePiecewiseConstant2D, PiecewiseLinear2D,
};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct PiecewiseConstant1DHost {
pub view: PiecewiseConstant1D,
_func: Vec<Float>,
_cdf: Vec<Float>,
pub struct PiecewiseConstant1D {
func: Box<[Float]>,
cdf: Box<[Float]>,
pub device: DevicePiecewiseConstant1D,
}
impl std::ops::Deref for PiecewiseConstant1DHost {
type Target = PiecewiseConstant1D;
fn deref(&self) -> &Self::Target {
&self.view
}
}
impl PiecewiseConstant1DHost {
impl PiecewiseConstant1D {
// Constructors
pub fn new(f: &[Float]) -> Self {
Self::new_with_bounds(f, 0.0, 1.0)
}
pub fn new_with_bounds(f: &[Float], min: Float, max: Float) -> Self {
pub fn to_shared(&self, arena: &mut Arena) -> DevicePiecewiseConstant1D {
let func_ptr = arena.alloc_slice(&self.func);
let cdf_ptr = arena.alloc_slice(&self.cdf);
DevicePiecewiseConstant1D {
func: func_ptr,
cdf: cdf_ptr,
func_integral: self.func_integral,
n: func.len(),
min: self.min,
max: self.max,
}
}
pub fn from_func<F>(f: F, min: Float, max: Float, n: usize) -> Self
where
F: Fn(Float) -> Float,
{
let delta = (max - min) / n as Float;
let values: Vec<Float> = (0..n)
.map(|i| {
let x = min + (i as Float + 0.5) * delta;
f(x)
})
.collect();
Self::new_with_bounds(values, min, max)
}
pub fn new_with_bounds(f: Vec<Float>, min: Float, max: Float) -> Self {
let n = f.len();
let mut cdf = Vec::with_capacity(n + 1);
cdf.push(0.0);
let mut func_vec = f.to_vec();
let mut cdf_vec = vec![0.0; n + 1];
cdf_vec[0] = 0.0;
for i in 1..=n {
cdf_vec[i] = cdf_vec[i - 1] + func_vec[i - 1] / n as Float;
let delta = (max - min) / n as Float;
for i in 0..n {
cdf.push(cdf[i] + f[i] * delta);
}
let func_integral = cdf_vec[n];
let func_integral = cdf[n];
if func_integral > 0.0 {
for i in 1..=n {
cdf_vec[i] /= func_integral;
}
} else {
for i in 1..=n {
cdf_vec[i] = i as Float / n as Float;
for c in &mut cdf {
*c /= func_integral;
}
}
let view = PiecewiseConstant1D {
func: Ptr(func_vec.as_ptr()),
cdf: Ptr(cdf_vec.as_ptr()),
// Convert to boxed slices (no more reallocation possible)
let func: Box<[Float]> = f.into_boxed_slice();
let cdf: Box<[Float]> = cdf.into_boxed_slice();
let device = DevicePiecewiseConstant1D {
func: func.as_ptr(),
cdf: cdf.as_ptr(),
min,
max,
n: n as u32,
func_integral,
};
Self {
view,
_func: func_vec,
_cdf: cdf_vec,
Self { func, cdf, device }
}
// Accessors
pub fn min(&self) -> Float {
self.device.min
}
pub fn max(&self) -> Float {
self.device.max
}
pub fn n(&self) -> usize {
self.device.n as usize
}
pub fn integral(&self) -> Float {
self.device.func_integral
}
pub fn func(&self) -> &[Float] {
&self.func
}
pub fn cdf(&self) -> &[Float] {
&self.cdf
}
}
#[derive(Debug, Clone)]
pub struct PiecewiseConstant2DHost {
pub view: PiecewiseConstant2D,
_p_conditional_v: Vec<PiecewiseConstant1D>,
}
impl std::ops::Deref for PiecewiseConstant1D {
type Target = DevicePiecewiseConstant1D;
impl std::ops::Deref for PiecewiseConstant2DHost {
type Target = PiecewiseConstant2D;
fn deref(&self) -> &Self::Target {
&self.view
&self.device
}
}
impl PiecewiseConstant2DHost {
pub fn new(data: &Array2D<Float>, x_size: u32, y_size: u32, domain: Bounds2f) -> Self {
let nu = x_size as usize;
let nv = y_size as usize;
let mut conditionals = Vec::with_capacity(nv);
for v in 0..nv {
let row = unsafe { core::slice::from_raw_parts(data.values.add(v * nu), nu) };
conditionals.push(PiecewiseConstant1D::new_with_bounds(
row,
domain.p_min.x(),
domain.p_max.x(),
));
pub struct PiecewiseConstant2D {
conditionals: Vec<PiecewiseConstant1D>,
marginal: PiecewiseConstant1D,
conditional_devices: Box<[DevicePiecewiseConstant1D]>,
pub device: DevicePiecewiseConstant2D,
}
impl PiecewiseConstant2D {
pub fn new(data: &[Float], n_u: usize, n_v: usize) -> Self {
assert_eq!(data.len(), n_u * n_v);
// Build conditional distributions p(u|v) for each row
let mut conditionals = Vec::with_capacity(n_v);
let mut marginal_func = Vec::with_capacity(n_v);
for v in 0..n_v {
let row_start = v * n_u;
let row: Vec<Float> = data[row_start..row_start + n_u].to_vec();
let conditional = PiecewiseConstant1D::new_with_bounds(row, 0.0, 1.0);
marginal_func.push(conditional.integral());
conditionals.push(conditional);
}
let marginal_funcs: Vec<Float> = conditionals.iter().map(|c| c.func_integral).collect();
let p_marginal = PiecewiseConstant1D::new_with_bounds(
&marginal_funcs,
domain.p_min.y(),
domain.p_max.y(),
);
// Build marginal distribution p(v)
let marginal = PiecewiseConstant1D::new_with_bounds(marginal_func, 0.0, 1.0);
let p_conditional_v = conditionals.as_mut_ptr();
std::mem::forget(conditionals);
let view = PiecewiseConstant2D {
domain,
p_marginal,
n_conditionals: nv,
p_conditional_v: Ptr(p_conditional_v),
// Create array of device structs
let conditional_devices: Box<[DevicePiecewiseConstant1D]> = conditionals
.iter()
.map(|c| c.device)
.collect::<Vec<_>>()
.into_boxed_slice();
let device = DevicePiecewiseConstant2D {
conditional: conditional_devices.as_ptr(),
marginal: marginal.device,
n_u: n_u as u32,
n_v: n_v as u32,
};
Self {
view,
_p_conditional_v: p_conditional_v,
conditionals,
marginal,
conditional_devices,
device,
}
}
pub fn new_with_bounds(data: &Array2D<Float>, domain: Bounds2f) -> Self {
Self::new(data, data.x_size(), data.y_size(), domain)
pub fn from_image(image: &Image) -> Self {
let res = image.resolution();
let n_u = res.x() as usize;
let n_v = res.y() as usize;
let mut data = Vec::with_capacity(n_u * n_v);
for v in 0..n_v {
for u in 0..n_u {
let p = Point2i::new(u as i32, v as i32);
let luminance = image.get_channels(p).average();
data.push(luminance);
}
}
pub fn new_with_data(data: &Array2D<Float>) -> Self {
let nx = data.x_size();
let ny = data.y_size();
let domain = Bounds2f::from_points(Point2f::new(0.0, 0.0), Point2f::new(1.0, 1.0));
Self::new(&data, n_u, n_v)
}
Self::new(data, nx, ny, domain)
pub fn integral(&self) -> Float {
self.marginal.integral()
}
}