<commit_before>
/*
    pbrt source code is Copyright(c) 1998-2017
                        <NAME>, <NAME>, and <NAME>.

    This file is part of pbrt.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */

/*

Implementation of the Disney BSDF with Subsurface Scattering, as described in:
http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf.

That model is based on the Disney BRDF, described in:
https://disney-animation.s3.amazonaws.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf

Many thanks for <NAME> and <NAME> for answering many questions about
the details of the implementation.

The initial implementation of the BRDF was adapted from
https://github.com/wdas/brdf/blob/master/src/brdfs/disney.brdf, which is
licensed under a slightly-modified Apache 2.0 license.

*/

// materials/disney.cpp*
#include "materials/disney.h"
#include "bssrdf.h"
#include "interaction.h"
#include "paramset.h"
#include "reflection.h"
#include "stats.h"
#include "stringprint.h"
#include "texture.h"
#include "rng.h"

namespace pbrt {

inline Float sqr(Float x) { return x * x; }

// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/
//
// The Schlick Fresnel approximation is:
//
// R = R(0) + (1 - R(0)) (1 - cos theta)^5,
//
// where R(0) is the reflectance at normal indicence.
inline Float SchlickWeight(Float cosTheta) {
    Float m = Clamp(1 - cosTheta, 0, 1);
    return (m * m) * (m * m) * m;
}

inline Float FrSchlick(Float R0, Float cosTheta) {
    return Lerp(SchlickWeight(cosTheta), R0, 1);
}

inline Spectrum FrSchlick(const Spectrum &R0, Float cosTheta) {
    return Lerp(SchlickWeight(cosTheta), R0, Spectrum(1.));
}

// For a dielectric, R(0) = (eta - 1)^2 / (eta + 1)^2, assuming we're
// coming from air..
inline Float SchlickR0FromEta(Float eta) { return sqr(eta - 1) / sqr(eta + 1); }

///////////////////////////////////////////////////////////////////////////
// DisneyDiffuse

class DisneyDiffuse : public BxDF {
  public:
    DisneyDiffuse(const Spectrum &R)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)), R(R) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
};

Spectrum DisneyDiffuse::f(const Vector3f &wo, const Vector3f &wi) const {
    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));

    // Diffuse fresnel - go from 1 at normal incidence to .5 at grazing.
    // Burley 2015, eq (4).
    return R * InvPi * (1 - Fo / 2) * (1 - Fi / 2);
}

std::string DisneyDiffuse::ToString() const {
    return StringPrintf("[ DisneyDiffuse R: %s ]", R.ToString().c_str());
}

///////////////////////////////////////////////////////////////////////////
// DisneyFakeSS

// "Fake" subsurface scattering lobe, based on the Hanrahan-Krueger BRDF
// approximation of the BSSRDF.
class DisneyFakeSS : public BxDF {
  public:
    DisneyFakeSS(const Spectrum &R, Float roughness)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)),
          R(R),
          roughness(roughness) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
    Float roughness;
};

Spectrum DisneyFakeSS::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    // Fss90 used to "flatten" retroreflection based on roughness
    Float Fss90 = cosThetaD * cosThetaD * roughness;
    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));
    Float Fss = Lerp(Fo, 1.0, Fss90) * Lerp(Fi, 1.0, Fss90);
    // 1.25 scale is used to (roughly) preserve albedo
    Float ss =
        1.25f * (Fss * (1 / (AbsCosTheta(wo) + AbsCosTheta(wi)) - .5f) + .5f);

    return R * InvPi * ss;
}

std::string DisneyFakeSS::ToString() const {
    return StringPrintf("[ DisneyFakeSS R: %s roughness: %f ]",
                        R.ToString().c_str(), roughness);
}

///////////////////////////////////////////////////////////////////////////
// DisneyRetro

class DisneyRetro : public BxDF {
  public:
    DisneyRetro(const Spectrum &R, Float roughness)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)),
          R(R),
          roughness(roughness) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
    Float roughness;
};

Spectrum DisneyRetro::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));
    Float Rr = 2 * roughness * cosThetaD * cosThetaD;

    // Burley 2015, eq (4).
    return R * InvPi * Rr * (Fo + Fi + Fo * Fi * (Rr - 1));
}

std::string DisneyRetro::ToString() const {
    return StringPrintf("[ DisneyRetro R: %s roughness: %f ]",
                        R.ToString().c_str(), roughness);
}

///////////////////////////////////////////////////////////////////////////
// DisneySheen

class DisneySheen : public BxDF {
  public:
    DisneySheen(const Spectrum &R)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)), R(R) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
};

Spectrum DisneySheen::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    return R * SchlickWeight(cosThetaD);
}

std::string DisneySheen::ToString() const {
    return StringPrintf("[ DisneySheen R: %s]", R.ToString().c_str());
}

///////////////////////////////////////////////////////////////////////////
// DisneyClearcoat

class DisneyClearcoat : public BxDF {
  public:
    DisneyClearcoat(Float weight, Float gloss)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_GLOSSY)),
          weight(weight),
          gloss(gloss) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u,
                      Float *pdf, BxDFType *sampledType) const;
    Float Pdf(const Vector3f &wo, const Vector3f &wi) const;
    std::string ToString() const;

  private:
    Float weight, gloss;
};

inline Float GTR1(Float cosTheta, Float alpha) {
    Float alpha2 = alpha * alpha;
    return (alpha2 - 1) /
           (Pi * std::log(alpha2) * (1 + (alpha2 - 1) * cosTheta * cosTheta));
}

// Smith masking/shadowing term.
inline Float smithG_GGX(Float cosTheta, Float alpha) {
    Float alpha2 = alpha * alpha;
    Float cosTheta2 = cosTheta * cosTheta;
    return 1 / (cosTheta + sqrt(alpha2 + cosTheta2 - alpha2 * cosTheta2));
}

Spectrum DisneyClearcoat::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);

    // Clearcoat has ior = 1.5 hardcoded -> F0 = 0.04. It then uses the
    // GTR1 distribution, which has even fatter tails than Trowbridge-Reitz
    // (which is GTR2).
    Float Dr = GTR1(AbsCosTheta(wh), gloss);
    Float Fr = FrSchlick(.04, Dot(wo, wh));
    // The geometric term always based on alpha = 0.25.
    Float Gr =
        smithG_GGX(AbsCosTheta(wo), .25) * smithG_GGX(AbsCosTheta(wi), .25);

    // Ad-hoc 0.25 term to match Disney implementation (unpublished, via
    // Brent Burley.)
    return .25 * weight * Gr * Fr * Dr / (AbsCosTheta(wo) * AbsCosTheta(wi));
}

Spectrum DisneyClearcoat::Sample_f(const Vector3f &wo, Vector3f *wi,
                                   const Point2f &u, Float *pdf,<commit_msg>Remove excess cos theta terms from DisneyClearCoat::f()<commit_after>
/*
    pbrt source code is Copyright(c) 1998-2017
                        <NAME>, <NAME>, and <NAME>.

    This file is part of pbrt.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */

/*

Implementation of the Disney BSDF with Subsurface Scattering, as described in:
http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf.

That model is based on the Disney BRDF, described in:
https://disney-animation.s3.amazonaws.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf

Many thanks for <NAME> and <NAME> for answering many questions about
the details of the implementation.

The initial implementation of the BRDF was adapted from
https://github.com/wdas/brdf/blob/master/src/brdfs/disney.brdf, which is
licensed under a slightly-modified Apache 2.0 license.

*/

// materials/disney.cpp*
#include "materials/disney.h"
#include "bssrdf.h"
#include "interaction.h"
#include "paramset.h"
#include "reflection.h"
#include "stats.h"
#include "stringprint.h"
#include "texture.h"
#include "rng.h"

namespace pbrt {

inline Float sqr(Float x) { return x * x; }

// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/
//
// The Schlick Fresnel approximation is:
//
// R = R(0) + (1 - R(0)) (1 - cos theta)^5,
//
// where R(0) is the reflectance at normal indicence.
inline Float SchlickWeight(Float cosTheta) {
    Float m = Clamp(1 - cosTheta, 0, 1);
    return (m * m) * (m * m) * m;
}

inline Float FrSchlick(Float R0, Float cosTheta) {
    return Lerp(SchlickWeight(cosTheta), R0, 1);
}

inline Spectrum FrSchlick(const Spectrum &R0, Float cosTheta) {
    return Lerp(SchlickWeight(cosTheta), R0, Spectrum(1.));
}

// For a dielectric, R(0) = (eta - 1)^2 / (eta + 1)^2, assuming we're
// coming from air..
inline Float SchlickR0FromEta(Float eta) { return sqr(eta - 1) / sqr(eta + 1); }

///////////////////////////////////////////////////////////////////////////
// DisneyDiffuse

class DisneyDiffuse : public BxDF {
  public:
    DisneyDiffuse(const Spectrum &R)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)), R(R) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
};

Spectrum DisneyDiffuse::f(const Vector3f &wo, const Vector3f &wi) const {
    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));

    // Diffuse fresnel - go from 1 at normal incidence to .5 at grazing.
    // Burley 2015, eq (4).
    return R * InvPi * (1 - Fo / 2) * (1 - Fi / 2);
}

std::string DisneyDiffuse::ToString() const {
    return StringPrintf("[ DisneyDiffuse R: %s ]", R.ToString().c_str());
}

///////////////////////////////////////////////////////////////////////////
// DisneyFakeSS

// "Fake" subsurface scattering lobe, based on the Hanrahan-Krueger BRDF
// approximation of the BSSRDF.
class DisneyFakeSS : public BxDF {
  public:
    DisneyFakeSS(const Spectrum &R, Float roughness)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)),
          R(R),
          roughness(roughness) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
    Float roughness;
};

Spectrum DisneyFakeSS::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    // Fss90 used to "flatten" retroreflection based on roughness
    Float Fss90 = cosThetaD * cosThetaD * roughness;
    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));
    Float Fss = Lerp(Fo, 1.0, Fss90) * Lerp(Fi, 1.0, Fss90);
    // 1.25 scale is used to (roughly) preserve albedo
    Float ss =
        1.25f * (Fss * (1 / (AbsCosTheta(wo) + AbsCosTheta(wi)) - .5f) + .5f);

    return R * InvPi * ss;
}

std::string DisneyFakeSS::ToString() const {
    return StringPrintf("[ DisneyFakeSS R: %s roughness: %f ]",
                        R.ToString().c_str(), roughness);
}

///////////////////////////////////////////////////////////////////////////
// DisneyRetro

class DisneyRetro : public BxDF {
  public:
    DisneyRetro(const Spectrum &R, Float roughness)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)),
          R(R),
          roughness(roughness) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
    Float roughness;
};

Spectrum DisneyRetro::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    Float Fo = SchlickWeight(AbsCosTheta(wo)),
          Fi = SchlickWeight(AbsCosTheta(wi));
    Float Rr = 2 * roughness * cosThetaD * cosThetaD;

    // Burley 2015, eq (4).
    return R * InvPi * Rr * (Fo + Fi + Fo * Fi * (Rr - 1));
}

std::string DisneyRetro::ToString() const {
    return StringPrintf("[ DisneyRetro R: %s roughness: %f ]",
                        R.ToString().c_str(), roughness);
}

///////////////////////////////////////////////////////////////////////////
// DisneySheen

class DisneySheen : public BxDF {
  public:
    DisneySheen(const Spectrum &R)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_DIFFUSE)), R(R) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum rho(const Vector3f &, int, const Point2f *) const { return R; }
    Spectrum rho(int, const Point2f *, const Point2f *) const { return R; }
    std::string ToString() const;

  private:
    Spectrum R;
};

Spectrum DisneySheen::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);
    Float cosThetaD = Dot(wi, wh);

    return R * SchlickWeight(cosThetaD);
}

std::string DisneySheen::ToString() const {
    return StringPrintf("[ DisneySheen R: %s]", R.ToString().c_str());
}

///////////////////////////////////////////////////////////////////////////
// DisneyClearcoat

class DisneyClearcoat : public BxDF {
  public:
    DisneyClearcoat(Float weight, Float gloss)
        : BxDF(BxDFType(BSDF_REFLECTION | BSDF_GLOSSY)),
          weight(weight),
          gloss(gloss) {}
    Spectrum f(const Vector3f &wo, const Vector3f &wi) const;
    Spectrum Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u,
                      Float *pdf, BxDFType *sampledType) const;
    Float Pdf(const Vector3f &wo, const Vector3f &wi) const;
    std::string ToString() const;

  private:
    Float weight, gloss;
};

inline Float GTR1(Float cosTheta, Float alpha) {
    Float alpha2 = alpha * alpha;
    return (alpha2 - 1) /
           (Pi * std::log(alpha2) * (1 + (alpha2 - 1) * cosTheta * cosTheta));
}

// Smith masking/shadowing term.
inline Float smithG_GGX(Float cosTheta, Float alpha) {
    Float alpha2 = alpha * alpha;
    Float cosTheta2 = cosTheta * cosTheta;
    return 1 / (cosTheta + sqrt(alpha2 + cosTheta2 - alpha2 * cosTheta2));
}

Spectrum DisneyClearcoat::f(const Vector3f &wo, const Vector3f &wi) const {
    Vector3f wh = wi + wo;
    if (wh.x == 0 && wh.y == 0 && wh.z == 0) return Spectrum(0.);
    wh = Normalize(wh);

    // Clearcoat has ior = 1.5 hardcoded -> F0 = 0.04. It then uses the
    // GTR1 distribution, which has even fatter tails than Trowbridge-Reitz
    // (which is GTR2).
    Float Dr = GTR1(AbsCosTheta(wh), gloss);
    Float Fr = FrSchlick(.04, Dot(wo, wh));
    // The geometric term always based on alpha = 0.25.
    Float Gr =
        smithG_GGX(AbsCosTheta(wo), .25) * smithG_GGX(AbsCosTheta(wi), .25);

    // Ad-hoc 0.25 term to match Disney implementation (unpublished, via
    // <NAME>.)
    return .25 * weight * Gr * Fr * Dr;
}

Spectrum DisneyClearcoat::Sample_f(const Vector3f &wo, Vector3f *wi,
                                   const Point2f &u, Float *pdf,
{'fraction_non_alphanumeric': 0.1516076516076516, 'fraction_numerical': 0.020146520146520148, 'mean_word_length': 2.7179875165500285, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 16, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5969284', 'n_tokens_mistral': 6675, 'n_tokens_neox': 6232, 'n_words': 1992}