45 #ifndef OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED 46 #define OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED 48 #include <openvdb/Types.h> 49 #include <openvdb/math/BBox.h> 50 #include <openvdb/math/Ray.h> 51 #include <openvdb/math/Math.h> 52 #include <openvdb/tools/RayIntersector.h> 53 #include <openvdb/tools/Interpolation.h> 54 #include <boost/scoped_ptr.hpp> 55 #include <boost/scoped_array.hpp> 60 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR 61 #include <OpenEXR/ImfPixelType.h> 62 #include <OpenEXR/ImfChannelList.h> 63 #include <OpenEXR/ImfOutputFile.h> 64 #include <OpenEXR/ImfHeader.h> 65 #include <OpenEXR/ImfFrameBuffer.h> 78 template<
typename Gr
idT>
82 size_t pixelSamples = 1,
83 unsigned int seed = 0,
84 bool threaded =
true);
87 template<
typename Gr
idT,
typename IntersectorT>
92 size_t pixelSamples = 1,
93 unsigned int seed = 0,
94 bool threaded =
true);
101 template<
typename Gr
idT,
typename IntersectorT = tools::LevelSetRayIntersector<Gr
idT> >
107 typedef typename IntersectorT::RayType
RayType;
113 size_t pixelSamples = 1,
114 unsigned int seed = 0);
121 size_t pixelSamples = 1,
122 unsigned int seed = 0);
131 void setGrid(
const GridT& grid);
135 void setIntersector(
const IntersectorT& inter);
153 void setPixelSamples(
size_t pixelSamples,
unsigned int seed = 0);
156 void render(
bool threaded =
true)
const;
160 void operator()(
const tbb::blocked_range<size_t>& range)
const;
163 const bool mIsMaster;
166 boost::scoped_ptr<const BaseShader> mShader;
178 template <
typename IntersectorT,
typename SamplerT = tools::BoxSampler>
184 typedef typename IntersectorT::RayType
RayType;
188 BOOST_STATIC_ASSERT(boost::is_floating_point<ValueType>::value);
197 void render(
bool threaded=
true)
const;
204 void setIntersector(
const IntersectorT& inter);
236 void print(std::ostream& os = std::cout,
int verboseLevel = 1);
240 void operator()(
const tbb::blocked_range<size_t>& range)
const;
244 AccessorType mAccessor;
246 boost::scoped_ptr<IntersectorT> mPrimary, mShadow;
247 Real mPrimaryStep, mShadowStep, mCutOff, mLightGain;
248 Vec3R mLightDir, mLightColor, mAbsorption, mScattering;
264 RGBA() : r(0), g(0), b(0), a(1) {}
265 explicit RGBA(ValueT intensity) : r(intensity), g(intensity), b(intensity), a(1) {}
266 RGBA(ValueT _r, ValueT _g, ValueT _b, ValueT _a = static_cast<ValueT>(1.0)):
267 r(_r), g(_g), b(_b), a(_a)
277 const float s = rhs.
a*(1.0f-a);
288 Film(
size_t width,
size_t height)
289 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
293 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
302 return mPixels[w + h*mWidth];
309 return mPixels[w + h*mWidth];
312 void fill(
const RGBA& rgb=
RGBA(0)) {
for (
size_t i=0; i<mSize; ++i) mPixels[i] = rgb; }
315 RGBA *p = mPixels.get();
316 for (
size_t j = 0; j < mHeight; ++j) {
317 for (
size_t i = 0; i < mWidth; ++i, ++p) {
318 *p = ((i & size) ^ (j & size)) ? c1 : c2;
325 std::string name(fileName);
326 if (name.find_last_of(
".") == std::string::npos) name.append(
".ppm");
328 boost::scoped_array<unsigned char> buffer(
new unsigned char[3*mSize]);
329 unsigned char *tmp = buffer.get(), *q = tmp;
330 RGBA* p = mPixels.get();
333 *q++ =
static_cast<unsigned char>(255.0f*(*p ).r);
334 *q++ =
static_cast<unsigned char>(255.0f*(*p ).g);
335 *q++ =
static_cast<unsigned char>(255.0f*(*p++).b);
338 std::ofstream os(name.c_str(), std::ios_base::binary);
340 std::cerr <<
"Error opening PPM file \"" << name <<
"\"" << std::endl;
344 os <<
"P6\n" << mWidth <<
" " << mHeight <<
"\n255\n";
345 os.write((
const char *)&(*tmp), 3*mSize*
sizeof(
unsigned char));
348 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR 349 void saveEXR(
const std::string& fileName,
size_t compression = 2,
size_t threads = 8)
351 std::string name(fileName);
352 if (name.find_last_of(
".") == std::string::npos) name.append(
".exr");
354 if (threads>0) Imf::setGlobalThreadCount(threads);
355 Imf::Header header(mWidth, mHeight);
356 if (compression==0) header.compression() = Imf::NO_COMPRESSION;
357 if (compression==1) header.compression() = Imf::RLE_COMPRESSION;
358 if (compression>=2) header.compression() = Imf::ZIP_COMPRESSION;
359 header.channels().insert(
"R", Imf::Channel(Imf::FLOAT));
360 header.channels().insert(
"G", Imf::Channel(Imf::FLOAT));
361 header.channels().insert(
"B", Imf::Channel(Imf::FLOAT));
362 header.channels().insert(
"A", Imf::Channel(Imf::FLOAT));
364 Imf::FrameBuffer framebuffer;
365 framebuffer.insert(
"R", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].r),
366 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
367 framebuffer.insert(
"G", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].g),
368 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
369 framebuffer.insert(
"B", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].b),
370 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
371 framebuffer.insert(
"A", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].a),
372 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
374 Imf::OutputFile file(name.c_str(), header);
375 file.setFrameBuffer(framebuffer);
376 file.writePixels(mHeight);
380 size_t width()
const {
return mWidth; }
381 size_t height()
const {
return mHeight; }
386 size_t mWidth, mHeight, mSize;
387 boost::scoped_array<RGBA> mPixels;
398 double frameWidth,
double nearPlane,
double farPlane)
400 , mScaleWidth(frameWidth)
401 , mScaleHeight(frameWidth * double(film.height()) / double(film.width()))
403 assert(nearPlane > 0 && farPlane > nearPlane);
404 mScreenToWorld.accumPostRotation(
math::X_AXIS, rotation[0] * M_PI / 180.0);
405 mScreenToWorld.accumPostRotation(
math::Y_AXIS, rotation[1] * M_PI / 180.0);
406 mScreenToWorld.accumPostRotation(
math::Z_AXIS, rotation[2] * M_PI / 180.0);
407 mScreenToWorld.accumPostTranslation(translation);
408 this->initRay(nearPlane, farPlane);
415 size_t width()
const {
return mFilm->width(); }
416 size_t height()
const {
return mFilm->height(); }
424 const Vec3R orig = mScreenToWorld.applyMap(
Vec3R(0.0));
425 const Vec3R dir = orig - xyz;
427 Mat4d xform = math::aim<Mat4d>(dir, up);
430 this->initRay(mRay.t0(), mRay.t1());
436 return Vec3R( (2 * i /
double(mFilm->width()) - 1) * mScaleWidth,
437 (1 - 2 * j / double(mFilm->height())) * mScaleHeight, z );
444 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const = 0;
449 mRay.setTimes(t0, t1);
450 mRay.setEye(mScreenToWorld.applyMap(
Vec3R(0.0)));
451 mRay.setDir(mScreenToWorld.applyJacobian(
Vec3R(0.0, 0.0, -1.0)));
482 double focalLength = 50.0,
483 double aperture = 41.2136,
484 double nearPlane = 1e-3,
486 :
BaseCamera(film,
rotation, translation, 0.5*aperture/focalLength, nearPlane, farPlane)
496 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const 499 Vec3R dir = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, -1.0);
500 dir = BaseCamera::mScreenToWorld.applyJacobian(dir);
511 return 360.0 / M_PI * atan(aperture/(2.0*length));
517 return aperture/(2.0*(tan(fov * M_PI / 360.0)));
540 double frameWidth = 1.0,
541 double nearPlane = 1e-3,
549 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const 552 Vec3R eye = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, 0.0);
553 ray.
setEye(BaseCamera::mScreenToWorld.applyMap(eye));
589 MatteShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
593 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
594 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
596 static_cast<Film::RGBA::ValueT>(v[0]),
597 static_cast<Film::RGBA::ValueT>(v[1]),
598 static_cast<Film::RGBA::ValueT>(v[2]));
603 typename GridT::ConstAccessor mAcc;
607 template <
typename SamplerType>
636 NormalShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
640 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
641 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
642 return Film::RGBA(v[0]*(normal[0]+1.0f), v[1]*(normal[1]+1.0f), v[2]*(normal[2]+1.0f));
647 typename GridT::ConstAccessor mAcc;
651 template <
typename SamplerType>
659 return mRGBA*
Film::RGBA(normal[0]+1.0f, normal[1]+1.0f, normal[2]+1.0f);
682 , mInvDim(1.0/bbox.extents())
683 , mAcc(grid.getAccessor())
684 , mXform(&grid.transform())
690 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
691 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
692 const Vec3R rgb = (xyz - mMin)*mInvDim;
698 const Vec3R mMin, mInvDim;
699 typename GridT::ConstAccessor mAcc;
703 template <
typename SamplerType>
708 : mMin(bbox.
min()), mInvDim(1.0/bbox.extents()), mRGBA(c) {}
712 const Vec3R rgb = (xyz - mMin)*mInvDim;
713 return mRGBA*
Film::RGBA(rgb[0], rgb[1], rgb[2]);
718 const Vec3R mMin, mInvDim;
736 DiffuseShader(
const GridT& grid): mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
740 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
741 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
749 typename GridT::ConstAccessor mAcc;
753 template <
typename SamplerType>
780 template<
typename Gr
idT>
789 tracer(grid, shader, camera, pixelSamples, seed);
794 template<
typename Gr
idT,
typename IntersectorT>
796 const IntersectorT& inter,
811 template<
typename Gr
idT,
typename IntersectorT>
821 mShader(shader.copy()),
827 template<
typename Gr
idT,
typename IntersectorT>
837 mShader(shader.copy()),
843 template<
typename Gr
idT,
typename IntersectorT>
848 mInter(other.mInter),
849 mShader(other.mShader->copy()),
850 mCamera(other.mCamera),
851 mSubPixels(other.mSubPixels)
855 template<
typename Gr
idT,
typename IntersectorT>
859 if (mIsMaster)
delete [] mRand;
862 template<
typename Gr
idT,
typename IntersectorT>
867 mInter = IntersectorT(grid);
870 template<
typename Gr
idT,
typename IntersectorT>
878 template<
typename Gr
idT,
typename IntersectorT>
883 mShader.reset(shader.
copy());
886 template<
typename Gr
idT,
typename IntersectorT>
894 template<
typename Gr
idT,
typename IntersectorT>
899 if (pixelSamples == 0) {
902 mSubPixels = pixelSamples - 1;
904 if (mSubPixels > 0) {
905 mRand =
new double[16];
907 for (
size_t i=0; i<16; ++i) mRand[i] = rand();
913 template<
typename Gr
idT,
typename IntersectorT>
917 tbb::blocked_range<size_t> range(0, mCamera->
height());
918 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
921 template<
typename Gr
idT,
typename IntersectorT>
927 const float frac = 1.0f / (1.0f + mSubPixels);
928 for (
size_t j=range.begin(), n=0, je = range.end(); j<je; ++j) {
929 for (
size_t i=0, ie = mCamera->
width(); i<ie; ++i) {
932 Film::RGBA c = mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
933 for (
size_t k=0; k<mSubPixels; ++k, n +=2 ) {
934 ray = mCamera->
getRay(i, j, mRand[n & 15], mRand[(n+1) & 15]);
935 c += mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
944 template<
typename IntersectorT,
typename SampleT>
947 : mAccessor(inter.grid().getConstAccessor())
949 , mPrimary(new IntersectorT(inter))
950 , mShadow(new IntersectorT(inter))
956 , mLightColor(0.7, 0.7, 0.7)
962 template<
typename IntersectorT,
typename SampleT>
965 : mAccessor(other.mAccessor)
966 , mCamera(other.mCamera)
967 , mPrimary(new IntersectorT(*(other.mPrimary)))
968 , mShadow(new IntersectorT(*(other.mShadow)))
969 , mPrimaryStep(other.mPrimaryStep)
970 , mShadowStep(other.mShadowStep)
971 , mCutOff(other.mCutOff)
972 , mLightGain(other.mLightGain)
973 , mLightDir(other.mLightDir)
974 , mLightColor(other.mLightColor)
975 , mAbsorption(other.mAbsorption)
976 , mScattering(other.mScattering)
980 template<
typename IntersectorT,
typename SampleT>
982 print(std::ostream& os,
int verboseLevel)
984 if (verboseLevel>0) {
985 os <<
"\nPrimary step: " << mPrimaryStep
986 <<
"\nShadow step: " << mShadowStep
987 <<
"\nCutoff: " << mCutOff
988 <<
"\nLightGain: " << mLightGain
989 <<
"\nLightDir: " << mLightDir
990 <<
"\nLightColor: " << mLightColor
991 <<
"\nAbsorption: " << mAbsorption
992 <<
"\nScattering: " << mScattering << std::endl;
994 mPrimary->print(os, verboseLevel);
997 template<
typename IntersectorT,
typename SampleT>
1001 mPrimary.reset(
new IntersectorT(inter));
1002 mShadow.reset(
new IntersectorT(inter));
1005 template<
typename IntersectorT,
typename SampleT>
1009 tbb::blocked_range<size_t> range(0, mCamera->
height());
1010 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
1013 template<
typename IntersectorT,
typename SampleT>
1017 SamplerType sampler(mAccessor, mShadow->grid().transform());
1020 const Vec3R extinction = -mScattering-mAbsorption, One(1.0);
1021 const Vec3R albedo = mLightColor*mScattering/(mScattering+mAbsorption);
1022 const Real sGain = mLightGain;
1023 const Real pStep = mPrimaryStep;
1024 const Real sStep = mShadowStep;
1025 const Real cutoff = mCutOff;
1034 std::vector<typename RayType::TimeSpan> pTS, sTS;
1039 for (
size_t j=range.begin(), je = range.end(); j<je; ++j) {
1040 for (
size_t i=0, ie = mCamera->
width(); i<ie; ++i) {
1042 bg.
a = bg.
r = bg.
g = bg.
b = 0;
1044 if( !mPrimary->setWorldRay(pRay))
continue;
1045 Vec3R pTrans(1.0), pLumi(0.0);
1048 while (mPrimary->march(pT0, pT1)) {
1049 for (
Real pT = pStep*ceil(pT0/pStep); pT <= pT1; pT += pStep) {
1051 mPrimary->hits(pTS);
1052 for (
size_t k=0; k<pTS.size(); ++k) {
1053 Real pT = pStep*ceil(pTS[k].t0/pStep), pT1=pTS[k].t1;
1054 for (; pT <= pT1; pT += pStep) {
1056 Vec3R pPos = mPrimary->getWorldPos(pT);
1057 const Real density = sampler.wsSample(pPos);
1058 if (density < cutoff)
continue;
1062 if( !mShadow->setWorldRay(sRay))
continue;
1065 while (mShadow->march(sT0, sT1)) {
1066 for (
Real sT = sStep*ceil(sT0/sStep); sT <= sT1; sT+= sStep) {
1069 for (
size_t l=0; l<sTS.size(); ++l) {
1070 Real sT = sStep*ceil(sTS[l].t0/sStep), sT1=sTS[l].t1;
1071 for (; sT <= sT1; sT+= sStep) {
1073 const Real d = sampler.wsSample(mShadow->getWorldPos(sT));
1074 if (d < cutoff)
continue;
1075 sTrans *=
math::Exp(extinction * d * sStep/(1.0+sT*sGain));
1076 if (sTrans.
lengthSqr()<cutoff)
goto Luminance;
1080 pLumi += albedo * sTrans * pTrans * (One-dT);
1082 if (pTrans.lengthSqr()<cutoff)
goto Pixel;
1098 #endif // OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED
T lengthSqr() const
Definition: Vec3.h:223
Coord Abs(const Coord &xyz)
Definition: Coord.h:247
const Vec3T & dir() const
Definition: Ray.h:121
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:97
MatType rotation(const Quat< typename MatType::value_type > &q, typename MatType::value_type eps=static_cast< typename MatType::value_type >(1.0e-8))
Return the rotation matrix specified by the given quaternion.
Definition: Mat.h:153
Simple generator of random numbers over the range [0, 1)
Definition: Math.h:143
Mat3< typename promote< T0, T1 >::type > operator*(const Mat3< T0 > &m0, const Mat3< T1 > &m1)
Matrix multiplication.
Definition: Mat3.h:658
Axis-aligned bounding box.
Definition: BBox.h:47
Vec3< T > unit(T eps=0) const
return normalized this, throws if null vector
Definition: Vec3.h:360
Vec3< typename promote< T, typename Coord::ValueType >::type > operator+(const Vec3< T > &v0, const Coord &v1)
Allow a Coord to be added to or subtracted from a Vec3.
Definition: Coord.h:494
double Real
Definition: Types.h:64
Type Exp(const Type &x)
Return .
Definition: Math.h:676
void setEye(const Vec3Type &eye)
Definition: Ray.h:88
T dot(const Vec3< T > &v) const
Dot product.
Definition: Vec3.h:203
#define OPENVDB_VERSION_NAME
Definition: version.h:43
A general linear transform using homogeneous coordinates to perform rotation, scaling, shear and translation.
Definition: Maps.h:324
Definition: Exceptions.h:39
MatType scale(const Vec3< typename MatType::value_type > &s)
Return a matrix that scales by s.
Definition: Mat.h:594
bool normalize(T eps=T(1.0e-7))
this = normalized this
Definition: Vec3.h:348
Definition: Exceptions.h:88
void scaleTimes(RealT scale)
Definition: Ray.h:107
math::Vec3< Real > Vec3R
Definition: Types.h:76
void setDir(const Vec3Type &dir)
Definition: Ray.h:90
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:71
void postTranslate(const Vec3< T0 > &tr)
Right multiplies by the specified translation matrix, i.e. (*this) * Trans.
Definition: Mat4.h:756
MatType unit(const MatType &mat, typename MatType::value_type eps=1.0e-8)
Return a copy of the given matrix with its upper 3x3 rows normalized.
Definition: Mat.h:627