PathtraceBase.fs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. #ifdef _MSC_VER
  2. #define PATH_TRACING // just for editing in MS VS
  3. #define in
  4. #define out
  5. #define inout
  6. typedef struct { float x; float y; } vec2;
  7. typedef struct { float x; float y; float z; } vec3;
  8. typedef struct { float x; float y; float z; float w; } vec4;
  9. #endif
  10. #ifdef PATH_TRACING
  11. ///////////////////////////////////////////////////////////////////////////////////////
  12. // Specific data types
  13. //! Describes local space at the hit point (visualization space).
  14. struct SLocalSpace
  15. {
  16. //! Local X axis.
  17. vec3 AxisX;
  18. //! Local Y axis.
  19. vec3 AxisY;
  20. //! Local Z axis.
  21. vec3 AxisZ;
  22. };
  23. //! Describes material properties (BSDF).
  24. struct SBSDF
  25. {
  26. //! Weight of coat specular/glossy BRDF.
  27. vec4 Kc;
  28. //! Weight of base diffuse BRDF + base color texture index in W.
  29. vec4 Kd;
  30. //! Weight of base specular/glossy BRDF.
  31. vec4 Ks;
  32. //! Weight of base specular/glossy BTDF + metallic-roughness texture index in W.
  33. vec4 Kt;
  34. //! Fresnel coefficients of coat layer.
  35. vec3 FresnelCoat;
  36. //! Fresnel coefficients of base layer + normal map texture index in W.
  37. vec4 FresnelBase;
  38. };
  39. ///////////////////////////////////////////////////////////////////////////////////////
  40. // Support subroutines
  41. //=======================================================================
  42. // function : buildLocalSpace
  43. // purpose : Generates local space for the given normal
  44. //=======================================================================
  45. SLocalSpace buildLocalSpace (in vec3 theNormal)
  46. {
  47. vec3 anAxisX = vec3 (theNormal.z, 0.f, -theNormal.x);
  48. vec3 anAxisY = vec3 (0.f, -theNormal.z, theNormal.y);
  49. float aSqrLenX = dot (anAxisX, anAxisX);
  50. float aSqrLenY = dot (anAxisY, anAxisY);
  51. if (aSqrLenX > aSqrLenY)
  52. {
  53. anAxisX *= inversesqrt (aSqrLenX);
  54. anAxisY = cross (anAxisX, theNormal);
  55. }
  56. else
  57. {
  58. anAxisY *= inversesqrt (aSqrLenY);
  59. anAxisX = cross (anAxisY, theNormal);
  60. }
  61. return SLocalSpace (anAxisX, anAxisY, theNormal);
  62. }
  63. //=======================================================================
  64. // function : toLocalSpace
  65. // purpose : Transforms the vector to local space from world space
  66. //=======================================================================
  67. vec3 toLocalSpace (in vec3 theVector, in SLocalSpace theSpace)
  68. {
  69. return vec3 (dot (theVector, theSpace.AxisX),
  70. dot (theVector, theSpace.AxisY),
  71. dot (theVector, theSpace.AxisZ));
  72. }
  73. //=======================================================================
  74. // function : fromLocalSpace
  75. // purpose : Transforms the vector from local space to world space
  76. //=======================================================================
  77. vec3 fromLocalSpace (in vec3 theVector, in SLocalSpace theSpace)
  78. {
  79. return theVector.x * theSpace.AxisX +
  80. theVector.y * theSpace.AxisY +
  81. theVector.z * theSpace.AxisZ;
  82. }
  83. //=======================================================================
  84. // function : convolve
  85. // purpose : Performs a linear convolution of the vector components
  86. //=======================================================================
  87. float convolve (in vec3 theVector, in vec3 theFactor)
  88. {
  89. return dot (theVector, theFactor) * (1.f / max (theFactor.x + theFactor.y + theFactor.z, 1e-15f));
  90. }
  91. //=======================================================================
  92. // function : fresnelSchlick
  93. // purpose : Computes the Fresnel reflection formula using
  94. // Schlick's approximation.
  95. //=======================================================================
  96. vec3 fresnelSchlick (in float theCosI, in vec3 theSpecularColor)
  97. {
  98. return theSpecularColor + (UNIT - theSpecularColor) * pow (1.f - theCosI, 5.f);
  99. }
  100. //=======================================================================
  101. // function : fresnelDielectric
  102. // purpose : Computes the Fresnel reflection formula for dielectric in
  103. // case of circularly polarized light (Based on PBRT code).
  104. //=======================================================================
  105. float fresnelDielectric (in float theCosI,
  106. in float theCosT,
  107. in float theEtaI,
  108. in float theEtaT)
  109. {
  110. float aParl = (theEtaT * theCosI - theEtaI * theCosT) /
  111. (theEtaT * theCosI + theEtaI * theCosT);
  112. float aPerp = (theEtaI * theCosI - theEtaT * theCosT) /
  113. (theEtaI * theCosI + theEtaT * theCosT);
  114. return (aParl * aParl + aPerp * aPerp) * 0.5f;
  115. }
  116. #define ENVIRONMENT_IOR 1.f
  117. //=======================================================================
  118. // function : fresnelDielectric
  119. // purpose : Computes the Fresnel reflection formula for dielectric in
  120. // case of circularly polarized light (based on PBRT code)
  121. //=======================================================================
  122. float fresnelDielectric (in float theCosI, in float theIndex)
  123. {
  124. float aFresnel = 1.f;
  125. float anEtaI = theCosI > 0.f ? 1.f : theIndex;
  126. float anEtaT = theCosI > 0.f ? theIndex : 1.f;
  127. float aSinT2 = (anEtaI * anEtaI) / (anEtaT * anEtaT) * (1.f - theCosI * theCosI);
  128. if (aSinT2 < 1.f)
  129. {
  130. aFresnel = fresnelDielectric (abs (theCosI), sqrt (1.f - aSinT2), anEtaI, anEtaT);
  131. }
  132. return aFresnel;
  133. }
  134. //=======================================================================
  135. // function : fresnelConductor
  136. // purpose : Computes the Fresnel reflection formula for conductor in case
  137. // of circularly polarized light (based on PBRT source code)
  138. //=======================================================================
  139. float fresnelConductor (in float theCosI, in float theEta, in float theK)
  140. {
  141. float aTmp = 2.f * theEta * theCosI;
  142. float aTmp1 = theEta * theEta + theK * theK;
  143. float aSPerp = (aTmp1 - aTmp + theCosI * theCosI) /
  144. (aTmp1 + aTmp + theCosI * theCosI);
  145. float aTmp2 = aTmp1 * theCosI * theCosI;
  146. float aSParl = (aTmp2 - aTmp + 1.f) /
  147. (aTmp2 + aTmp + 1.f);
  148. return (aSPerp + aSParl) * 0.5f;
  149. }
  150. #define FRESNEL_SCHLICK -0.5f
  151. #define FRESNEL_CONSTANT -1.5f
  152. #define FRESNEL_CONDUCTOR -2.5f
  153. #define FRESNEL_DIELECTRIC -3.5f
  154. //=======================================================================
  155. // function : fresnelMedia
  156. // purpose : Computes the Fresnel reflection formula for general medium
  157. // in case of circularly polarized light.
  158. //=======================================================================
  159. vec3 fresnelMedia (in float theCosI, in vec3 theFresnel)
  160. {
  161. vec3 aFresnel;
  162. if (theFresnel.x > FRESNEL_SCHLICK)
  163. {
  164. aFresnel = fresnelSchlick (abs (theCosI), theFresnel);
  165. }
  166. else if (theFresnel.x > FRESNEL_CONSTANT)
  167. {
  168. aFresnel = vec3 (theFresnel.z);
  169. }
  170. else if (theFresnel.x > FRESNEL_CONDUCTOR)
  171. {
  172. aFresnel = vec3 (fresnelConductor (abs (theCosI), theFresnel.y, theFresnel.z));
  173. }
  174. else
  175. {
  176. aFresnel = vec3 (fresnelDielectric (theCosI, theFresnel.y));
  177. }
  178. return aFresnel;
  179. }
  180. //=======================================================================
  181. // function : transmitted
  182. // purpose : Computes transmitted direction in tangent space
  183. // (in case of TIR returned result is undefined!)
  184. //=======================================================================
  185. void transmitted (in float theIndex, in vec3 theIncident, out vec3 theTransmit)
  186. {
  187. // Compute relative index of refraction
  188. float anEta = (theIncident.z > 0.f) ? 1.f / theIndex : theIndex;
  189. // Handle total internal reflection (TIR)
  190. float aSinT2 = anEta * anEta * (1.f - theIncident.z * theIncident.z);
  191. // Compute direction of transmitted ray
  192. float aCosT = sqrt (1.f - min (aSinT2, 1.f)) * sign (-theIncident.z);
  193. theTransmit = normalize (vec3 (-anEta * theIncident.x,
  194. -anEta * theIncident.y,
  195. aCosT));
  196. }
  197. //////////////////////////////////////////////////////////////////////////////////////////////
  198. // Handlers and samplers for materials
  199. //////////////////////////////////////////////////////////////////////////////////////////////
  200. //=======================================================================
  201. // function : EvalLambertianReflection
  202. // purpose : Evaluates Lambertian BRDF, with cos(N, PSI)
  203. //=======================================================================
  204. float EvalLambertianReflection (in vec3 theWi, in vec3 theWo)
  205. {
  206. return (theWi.z <= 0.f || theWo.z <= 0.f) ? 0.f : theWi.z * (1.f / M_PI);
  207. }
  208. #define FLT_EPSILON 1.0e-5f
  209. //=======================================================================
  210. // function : SmithG1
  211. // purpose :
  212. //=======================================================================
  213. float SmithG1 (in vec3 theDirection, in vec3 theM, in float theRoughness)
  214. {
  215. float aResult = 0.f;
  216. if (dot (theDirection, theM) * theDirection.z > 0.f)
  217. {
  218. float aTanThetaM = sqrt (1.f - theDirection.z * theDirection.z) / theDirection.z;
  219. if (aTanThetaM == 0.f)
  220. {
  221. aResult = 1.f;
  222. }
  223. else
  224. {
  225. float aVal = 1.f / (theRoughness * aTanThetaM);
  226. // Use rational approximation to shadowing-masking function (from Mitsuba)
  227. aResult = (3.535f + 2.181f * aVal) / (1.f / aVal + 2.276f + 2.577f * aVal);
  228. }
  229. }
  230. return min (aResult, 1.f);
  231. }
  232. //=======================================================================
  233. // function : EvalBlinnReflection
  234. // purpose : Evaluates Blinn glossy BRDF, with cos(N, PSI)
  235. //=======================================================================
  236. vec3 EvalBlinnReflection (in vec3 theWi, in vec3 theWo, in vec3 theFresnel, in float theRoughness)
  237. {
  238. // calculate the reflection half-vec
  239. vec3 aH = normalize (theWi + theWo);
  240. // roughness value -> Blinn exponent
  241. float aPower = max (2.f / (theRoughness * theRoughness) - 2.f, 0.f);
  242. // calculate microfacet distribution
  243. float aD = (aPower + 2.f) * (1.f / M_2_PI) * pow (aH.z, aPower);
  244. // calculate shadow-masking function
  245. float aG = SmithG1 (theWo, aH, theRoughness) *
  246. SmithG1 (theWi, aH, theRoughness);
  247. // return total amount of reflection
  248. return (theWi.z <= 0.f || theWo.z <= 0.f) ? ZERO :
  249. aD * aG / (4.f * theWo.z) * fresnelMedia (dot (theWo, aH), theFresnel);
  250. }
  251. //=======================================================================
  252. // function : EvalBsdfLayered
  253. // purpose : Evaluates BSDF for specified material, with cos(N, PSI)
  254. //=======================================================================
  255. vec3 EvalBsdfLayered (in SBSDF theBSDF, in vec3 theWi, in vec3 theWo)
  256. {
  257. #ifdef TWO_SIDED_BXDF
  258. theWi.z *= sign (theWi.z);
  259. theWo.z *= sign (theWo.z);
  260. #endif
  261. vec3 aBxDF = theBSDF.Kd.rgb * EvalLambertianReflection (theWi, theWo);
  262. if (theBSDF.Ks.w > FLT_EPSILON)
  263. {
  264. aBxDF += theBSDF.Ks.rgb * EvalBlinnReflection (theWi, theWo, theBSDF.FresnelBase.rgb, theBSDF.Ks.w);
  265. }
  266. aBxDF *= UNIT - fresnelMedia (theWo.z, theBSDF.FresnelCoat);
  267. if (theBSDF.Kc.w > FLT_EPSILON)
  268. {
  269. aBxDF += theBSDF.Kc.rgb * EvalBlinnReflection (theWi, theWo, theBSDF.FresnelCoat, theBSDF.Kc.w);
  270. }
  271. return aBxDF;
  272. }
  273. //=======================================================================
  274. // function : SampleLambertianReflection
  275. // purpose : Samples Lambertian BRDF, W = BRDF * cos(N, PSI) / PDF(PSI)
  276. //=======================================================================
  277. vec3 SampleLambertianReflection (in vec3 theWo, out vec3 theWi, inout float thePDF)
  278. {
  279. float aKsi1 = RandFloat();
  280. float aKsi2 = RandFloat();
  281. theWi = vec3 (cos (M_2_PI * aKsi1),
  282. sin (M_2_PI * aKsi1),
  283. sqrt (1.f - aKsi2));
  284. theWi.xy *= sqrt (aKsi2);
  285. #ifdef TWO_SIDED_BXDF
  286. theWi.z *= sign (theWo.z);
  287. #endif
  288. thePDF *= theWi.z * (1.f / M_PI);
  289. #ifdef TWO_SIDED_BXDF
  290. return UNIT;
  291. #else
  292. return UNIT * step (0.f, theWo.z);
  293. #endif
  294. }
  295. //=======================================================================
  296. // function : SampleGlossyBlinnReflection
  297. // purpose : Samples Blinn BRDF, W = BRDF * cos(N, PSI) / PDF(PSI)
  298. // The BRDF is a product of three main terms, D, G, and F,
  299. // which is then divided by two cosine terms. Here we perform
  300. // importance sample the D part of the Blinn model; trying to
  301. // develop a sampling procedure that accounted for all of the
  302. // terms would be complex, and it is the D term that accounts
  303. // for most of the variation.
  304. //=======================================================================
  305. vec3 SampleGlossyBlinnReflection (in vec3 theWo, out vec3 theWi, in vec3 theFresnel, in float theRoughness, inout float thePDF)
  306. {
  307. float aKsi1 = RandFloat();
  308. float aKsi2 = RandFloat();
  309. // roughness value --> Blinn exponent
  310. float aPower = max (2.f / (theRoughness * theRoughness) - 2.f, 0.f);
  311. // normal from microface distribution
  312. float aCosThetaM = pow (aKsi1, 1.f / (aPower + 2.f));
  313. vec3 aM = vec3 (cos (M_2_PI * aKsi2),
  314. sin (M_2_PI * aKsi2),
  315. aCosThetaM);
  316. aM.xy *= sqrt (1.f - aCosThetaM * aCosThetaM);
  317. // calculate PDF of sampled direction
  318. thePDF *= (aPower + 2.f) * (1.f / M_2_PI) * pow (aCosThetaM, aPower + 1.f);
  319. #ifdef TWO_SIDED_BXDF
  320. bool toFlip = theWo.z < 0.f;
  321. if (toFlip)
  322. theWo.z = -theWo.z;
  323. #endif
  324. float aCosDelta = dot (theWo, aM);
  325. // pick input based on half direction
  326. theWi = -theWo + 2.f * aCosDelta * aM;
  327. if (theWi.z <= 0.f || theWo.z <= 0.f)
  328. {
  329. return ZERO;
  330. }
  331. // Jacobian of half-direction mapping
  332. thePDF /= 4.f * aCosDelta;
  333. // compute shadow-masking coefficient
  334. float aG = SmithG1 (theWo, aM, theRoughness) *
  335. SmithG1 (theWi, aM, theRoughness);
  336. #ifdef TWO_SIDED_BXDF
  337. if (toFlip)
  338. theWi.z = -theWi.z;
  339. #endif
  340. return (aG * aCosDelta) / (theWo.z * aM.z) * fresnelMedia (aCosDelta, theFresnel);
  341. }
  342. //=======================================================================
  343. // function : BsdfPdfLayered
  344. // purpose : Calculates BSDF of sampling input knowing output
  345. //=======================================================================
  346. float BsdfPdfLayered (in SBSDF theBSDF, in vec3 theWo, in vec3 theWi, in vec3 theWeight)
  347. {
  348. float aPDF = 0.f; // PDF of sampling input direction
  349. // We choose whether the light is reflected or transmitted
  350. // by the coating layer according to the Fresnel equations
  351. vec3 aCoatF = fresnelMedia (theWo.z, theBSDF.FresnelCoat);
  352. // Coat BRDF is scaled by its Fresnel reflectance term. For
  353. // reasons of simplicity we scale base BxDFs only by coat's
  354. // Fresnel transmittance term
  355. vec3 aCoatT = UNIT - aCoatF;
  356. float aPc = dot (theBSDF.Kc.rgb * aCoatF, theWeight);
  357. float aPd = dot (theBSDF.Kd.rgb * aCoatT, theWeight);
  358. float aPs = dot (theBSDF.Ks.rgb * aCoatT, theWeight);
  359. float aPt = dot (theBSDF.Kt.rgb * aCoatT, theWeight);
  360. if (theWi.z * theWo.z > 0.f)
  361. {
  362. vec3 aH = normalize (theWi + theWo);
  363. aPDF = aPd * abs (theWi.z / M_PI);
  364. if (theBSDF.Kc.w > FLT_EPSILON)
  365. {
  366. float aPower = max (2.f / (theBSDF.Kc.w * theBSDF.Kc.w) - 2.f, 0.f); // roughness --> exponent
  367. aPDF += aPc * (aPower + 2.f) * (0.25f / M_2_PI) * pow (abs (aH.z), aPower + 1.f) / dot (theWi, aH);
  368. }
  369. if (theBSDF.Ks.w > FLT_EPSILON)
  370. {
  371. float aPower = max (2.f / (theBSDF.Ks.w * theBSDF.Ks.w) - 2.f, 0.f); // roughness --> exponent
  372. aPDF += aPs * (aPower + 2.f) * (0.25f / M_2_PI) * pow (abs (aH.z), aPower + 1.f) / dot (theWi, aH);
  373. }
  374. }
  375. return aPDF / (aPc + aPd + aPs + aPt);
  376. }
  377. //! Tool macro to handle sampling of particular BxDF
  378. #define PICK_BXDF_LAYER(p, k) aPDF = p / aTotalR; theWeight *= k / aPDF;
  379. //=======================================================================
  380. // function : SampleBsdfLayered
  381. // purpose : Samples specified composite material (BSDF)
  382. //=======================================================================
  383. float SampleBsdfLayered (in SBSDF theBSDF, in vec3 theWo, out vec3 theWi, inout vec3 theWeight, inout bool theInside)
  384. {
  385. // NOTE: OCCT uses two-layer material model. We have base diffuse, glossy, or transmissive
  386. // layer, covered by one glossy/specular coat. In the current model, the layers themselves
  387. // have no thickness; they can simply reflect light or transmits it to the layer under it.
  388. // We use actual BRDF model only for direct reflection by the coat layer. For transmission
  389. // through this layer, we approximate it as a flat specular surface.
  390. float aPDF = 0.f; // PDF of sampled direction
  391. // We choose whether the light is reflected or transmitted
  392. // by the coating layer according to the Fresnel equations
  393. vec3 aCoatF = fresnelMedia (theWo.z, theBSDF.FresnelCoat);
  394. // Coat BRDF is scaled by its Fresnel term. According to
  395. // Wilkie-Weidlich layered BSDF model, transmission term
  396. // for light passing through the coat at direction I and
  397. // leaving it in O is T = ( 1 - F (O) ) x ( 1 - F (I) ).
  398. // For reasons of simplicity, we discard the second term
  399. // and scale base BxDFs only by the first term.
  400. vec3 aCoatT = UNIT - aCoatF;
  401. float aPc = dot (theBSDF.Kc.rgb * aCoatF, theWeight);
  402. float aPd = dot (theBSDF.Kd.rgb * aCoatT, theWeight);
  403. float aPs = dot (theBSDF.Ks.rgb * aCoatT, theWeight);
  404. float aPt = dot (theBSDF.Kt.rgb * aCoatT, theWeight);
  405. // Calculate total reflection probability
  406. float aTotalR = (aPc + aPd) + (aPs + aPt);
  407. // Generate random variable to select BxDF
  408. float aKsi = aTotalR * RandFloat();
  409. if (aKsi < aPc) // REFLECTION FROM COAT
  410. {
  411. PICK_BXDF_LAYER (aPc, theBSDF.Kc.rgb)
  412. if (theBSDF.Kc.w < FLT_EPSILON)
  413. {
  414. theWeight *= aCoatF;
  415. theWi = vec3 (-theWo.x,
  416. -theWo.y,
  417. theWo.z);
  418. }
  419. else
  420. {
  421. theWeight *= SampleGlossyBlinnReflection (theWo, theWi, theBSDF.FresnelCoat, theBSDF.Kc.w, aPDF);
  422. }
  423. aPDF = mix (aPDF, MAXFLOAT, theBSDF.Kc.w < FLT_EPSILON);
  424. }
  425. else if (aKsi < aTotalR) // REFLECTION FROM BASE
  426. {
  427. theWeight *= aCoatT;
  428. if (aKsi < aPc + aPd) // diffuse BRDF
  429. {
  430. PICK_BXDF_LAYER (aPd, theBSDF.Kd.rgb)
  431. theWeight *= SampleLambertianReflection (theWo, theWi, aPDF);
  432. }
  433. else if (aKsi < (aPc + aPd) + aPs) // specular/glossy BRDF
  434. {
  435. PICK_BXDF_LAYER (aPs, theBSDF.Ks.rgb)
  436. if (theBSDF.Ks.w < FLT_EPSILON)
  437. {
  438. theWeight *= fresnelMedia (theWo.z, theBSDF.FresnelBase.rgb);
  439. theWi = vec3 (-theWo.x,
  440. -theWo.y,
  441. theWo.z);
  442. }
  443. else
  444. {
  445. theWeight *= SampleGlossyBlinnReflection (theWo, theWi, theBSDF.FresnelBase.rgb, theBSDF.Ks.w, aPDF);
  446. }
  447. aPDF = mix (aPDF, MAXFLOAT, theBSDF.Ks.w < FLT_EPSILON);
  448. }
  449. else // specular transmission
  450. {
  451. PICK_BXDF_LAYER (aPt, theBSDF.Kt.rgb)
  452. // refracted direction should exist if we are here
  453. transmitted (theBSDF.FresnelCoat.y, theWo, theWi);
  454. theInside = !theInside; aPDF = MAXFLOAT;
  455. }
  456. }
  457. // path termination for extra small weights
  458. theWeight = mix (ZERO, theWeight, step (FLT_EPSILON, aTotalR));
  459. return aPDF;
  460. }
  461. //////////////////////////////////////////////////////////////////////////////////////////////
  462. // Handlers and samplers for light sources
  463. //////////////////////////////////////////////////////////////////////////////////////////////
  464. //=======================================================================
  465. // function : SampleLight
  466. // purpose : General sampling function for directional and point lights
  467. //=======================================================================
  468. vec3 SampleLight (in vec3 theToLight, inout float theDistance, in bool isInfinite, in float theSmoothness, inout float thePDF)
  469. {
  470. SLocalSpace aSpace = buildLocalSpace (theToLight * (1.f / theDistance));
  471. // for point lights smoothness defines radius
  472. float aCosMax = isInfinite ? theSmoothness :
  473. inversesqrt (1.f + theSmoothness * theSmoothness / (theDistance * theDistance));
  474. float aKsi1 = RandFloat();
  475. float aKsi2 = RandFloat();
  476. float aTmp = 1.f - aKsi2 * (1.f - aCosMax);
  477. vec3 anInput = vec3 (cos (M_2_PI * aKsi1),
  478. sin (M_2_PI * aKsi1),
  479. aTmp);
  480. anInput.xy *= sqrt (1.f - aTmp * aTmp);
  481. thePDF = (aCosMax < 1.f) ? (thePDF / M_2_PI) / (1.f - aCosMax) : MAXFLOAT;
  482. return normalize (fromLocalSpace (anInput, aSpace));
  483. }
  484. //=======================================================================
  485. // function : HandlePointLight
  486. // purpose :
  487. //=======================================================================
  488. float HandlePointLight (in vec3 theInput, in vec3 theToLight, in float theRadius, in float theDistance, inout float thePDF)
  489. {
  490. float aCosMax = inversesqrt (1.f + theRadius * theRadius / (theDistance * theDistance));
  491. float aVisibility = step (aCosMax, dot (theInput, theToLight));
  492. thePDF *= step (-1.f, -aCosMax) * aVisibility * (1.f / M_2_PI) / (1.f - aCosMax);
  493. return aVisibility;
  494. }
  495. //=======================================================================
  496. // function : HandleDistantLight
  497. // purpose :
  498. //=======================================================================
  499. float HandleDistantLight (in vec3 theInput, in vec3 theToLight, in float theCosMax, inout float thePDF)
  500. {
  501. float aVisibility = step (theCosMax, dot (theInput, theToLight));
  502. thePDF *= step (-1.f, -theCosMax) * aVisibility * (1.f / M_2_PI) / (1.f - theCosMax);
  503. return aVisibility;
  504. }
  505. // =======================================================================
  506. // function: IntersectLight
  507. // purpose : Checks intersections with light sources
  508. // =======================================================================
  509. vec3 IntersectLight (in SRay theRay, in int theDepth, in float theHitDistance, out float thePDF)
  510. {
  511. vec3 aTotalRadiance = ZERO;
  512. thePDF = 0.f; // PDF of sampling light sources
  513. for (int aLightIdx = 0; aLightIdx < uLightCount; ++aLightIdx)
  514. {
  515. vec4 aLight = texelFetch (uRaytraceLightSrcTexture, LIGHT_POS (aLightIdx));
  516. vec4 aParam = texelFetch (uRaytraceLightSrcTexture, LIGHT_PWR (aLightIdx));
  517. // W component: 0 for infinite light and 1 for point light
  518. aLight.xyz -= mix (ZERO, theRay.Origin, aLight.w);
  519. float aPDF = 1.0 / float(uLightCount);
  520. if (aLight.w != 0.f) // point light source
  521. {
  522. float aCenterDst = length (aLight.xyz);
  523. if (aCenterDst < theHitDistance)
  524. {
  525. float aVisibility = HandlePointLight (
  526. theRay.Direct, normalize (aLight.xyz), aParam.w /* radius */, aCenterDst, aPDF);
  527. if (aVisibility > 0.f)
  528. {
  529. theHitDistance = aCenterDst;
  530. aTotalRadiance = aParam.rgb;
  531. thePDF = aPDF;
  532. }
  533. }
  534. }
  535. else if (theHitDistance == MAXFLOAT) // directional light source
  536. {
  537. aTotalRadiance += aParam.rgb * HandleDistantLight (
  538. theRay.Direct, aLight.xyz, aParam.w /* angle cosine */, aPDF);
  539. thePDF += aPDF;
  540. }
  541. }
  542. if (thePDF == 0.f && theHitDistance == MAXFLOAT) // light source not found
  543. {
  544. if (theDepth + uEnvMapForBack == 0) // view ray and map is hidden
  545. {
  546. aTotalRadiance = BackgroundColor().rgb;
  547. }
  548. else
  549. {
  550. #ifdef BACKGROUND_CUBEMAP
  551. if (theDepth == 0)
  552. {
  553. vec2 aPixel = uEyeSize * (vPixel - vec2 (0.5)) * 2.0;
  554. vec2 anAperturePnt = sampleUniformDisk() * uApertureRadius;
  555. vec3 aLocalDir = normalize (vec3 (aPixel * uFocalPlaneDist - anAperturePnt, uFocalPlaneDist));
  556. vec3 aDirect = uEyeView * aLocalDir.z +
  557. uEyeSide * aLocalDir.x +
  558. uEyeVert * aLocalDir.y;
  559. aTotalRadiance = FetchEnvironment (aDirect, 1.0, true).rgb;
  560. }
  561. else
  562. {
  563. aTotalRadiance = FetchEnvironment (theRay.Direct, 1.0, false).rgb;
  564. }
  565. #else
  566. aTotalRadiance = FetchEnvironment (theRay.Direct, 1.0, theDepth == 0).rgb;
  567. #endif
  568. }
  569. #ifdef THE_SHIFT_sRGB
  570. aTotalRadiance = pow (aTotalRadiance, vec3 (2.f));
  571. #endif
  572. }
  573. return aTotalRadiance;
  574. }
  575. #define MIN_THROUGHPUT vec3 (1.0e-3f)
  576. #define MIN_CONTRIBUTION vec3 (1.0e-2f)
  577. #define MATERIAL_KC(index) (19 * index + 11)
  578. #define MATERIAL_KD(index) (19 * index + 12)
  579. #define MATERIAL_KS(index) (19 * index + 13)
  580. #define MATERIAL_KT(index) (19 * index + 14)
  581. #define MATERIAL_LE(index) (19 * index + 15)
  582. #define MATERIAL_FRESNEL_COAT(index) (19 * index + 16)
  583. #define MATERIAL_FRESNEL_BASE(index) (19 * index + 17)
  584. #define MATERIAL_ABSORPT_BASE(index) (19 * index + 18)
  585. //! Enables experimental Russian roulette sampling path termination.
  586. //! In most cases, it provides faster image convergence with minimal
  587. //! bias, so it is enabled by default.
  588. #define RUSSIAN_ROULETTE
  589. //! Frame step to increase number of bounces. This mode is used
  590. //! for interaction with the model, when path length is limited
  591. //! for the first samples, and gradually increasing when camera
  592. //! is stabilizing.
  593. #ifdef ADAPTIVE_SAMPLING
  594. #define FRAME_STEP 4
  595. #else
  596. #define FRAME_STEP 5
  597. #endif
  598. //=======================================================================
  599. // function : IsNotZero
  600. // purpose : Checks whether BSDF reflects direct light
  601. //=======================================================================
  602. bool IsNotZero (in SBSDF theBSDF, in vec3 theThroughput)
  603. {
  604. vec3 aGlossy = theBSDF.Kc.rgb * step (FLT_EPSILON, theBSDF.Kc.w) +
  605. theBSDF.Ks.rgb * step (FLT_EPSILON, theBSDF.Ks.w);
  606. return convolve (theBSDF.Kd.rgb + aGlossy, theThroughput) > FLT_EPSILON;
  607. }
  608. //=======================================================================
  609. // function : NormalAdaptation
  610. // purpose : Adapt smooth normal (which may be different from geometry normal) in order to avoid black areas in render
  611. //=======================================================================
  612. bool NormalAdaptation (in vec3 theView, in vec3 theGeometryNormal, inout vec3 theSmoothNormal)
  613. {
  614. float aMinCos = dot(theView, theGeometryNormal);
  615. aMinCos = 0.5 * (sqrt(1.0 - aMinCos) + sqrt(1.0 + aMinCos));
  616. float aCos = dot(theGeometryNormal, theSmoothNormal);
  617. if (aCos < aMinCos)
  618. {
  619. theSmoothNormal = aMinCos * theGeometryNormal + normalize(theSmoothNormal - aCos * theGeometryNormal) * sqrt(1.0 - aMinCos * aMinCos);
  620. return true;
  621. }
  622. return false;
  623. }
  624. //=======================================================================
  625. // function : PathTrace
  626. // purpose : Calculates radiance along the given ray
  627. //=======================================================================
  628. vec4 PathTrace (in SRay theRay, in vec3 theInverse, in int theNbSamples)
  629. {
  630. float aRaytraceDepth = MAXFLOAT;
  631. vec3 aRadiance = ZERO;
  632. vec3 aThroughput = UNIT;
  633. int aTransfID = 0; // ID of object transformation
  634. bool aInMedium = false; // is the ray inside an object
  635. float aExpPDF = 1.f;
  636. float aImpPDF = 1.f;
  637. for (int aDepth = 0; aDepth < NB_BOUNCES; ++aDepth)
  638. {
  639. SIntersect aHit = SIntersect (MAXFLOAT, vec2 (ZERO), ZERO);
  640. STriangle aTriangle = SceneNearestHit (theRay, theInverse, aHit, aTransfID);
  641. // check implicit path
  642. vec3 aLe = IntersectLight (theRay, aDepth, aHit.Time, aExpPDF);
  643. if (any (greaterThan (aLe, ZERO)) || aTriangle.TriIndex.x == -1)
  644. {
  645. float aMIS = (aDepth == 0 || aImpPDF == MAXFLOAT) ? 1.f :
  646. aImpPDF * aImpPDF / (aExpPDF * aExpPDF + aImpPDF * aImpPDF);
  647. aRadiance += aThroughput * aLe * aMIS; break; // terminate path
  648. }
  649. vec3 aInvTransf0 = texelFetch (uSceneTransformTexture, aTransfID + 0).xyz;
  650. vec3 aInvTransf1 = texelFetch (uSceneTransformTexture, aTransfID + 1).xyz;
  651. vec3 aInvTransf2 = texelFetch (uSceneTransformTexture, aTransfID + 2).xyz;
  652. // compute geometrical normal
  653. aHit.Normal = normalize (vec3 (dot (aInvTransf0, aHit.Normal),
  654. dot (aInvTransf1, aHit.Normal),
  655. dot (aInvTransf2, aHit.Normal)));
  656. theRay.Origin += theRay.Direct * aHit.Time; // get new intersection point
  657. // evaluate depth on first hit
  658. if (aDepth == 0)
  659. {
  660. vec4 aNDCPoint = uViewMat * vec4 (theRay.Origin, 1.f);
  661. float aPolygonOffset = PolygonOffset (aHit.Normal, theRay.Origin);
  662. #ifdef THE_ZERO_TO_ONE_DEPTH
  663. aRaytraceDepth = (aNDCPoint.z / aNDCPoint.w + aPolygonOffset * POLYGON_OFFSET_SCALE);
  664. #else
  665. aRaytraceDepth = (aNDCPoint.z / aNDCPoint.w + aPolygonOffset * POLYGON_OFFSET_SCALE) * 0.5f + 0.5f;
  666. #endif
  667. }
  668. SBSDF aBSDF;
  669. // fetch BxDF weights
  670. aBSDF.Kc = texelFetch (uRaytraceMaterialTexture, MATERIAL_KC (aTriangle.TriIndex.w));
  671. aBSDF.Kd = texelFetch (uRaytraceMaterialTexture, MATERIAL_KD (aTriangle.TriIndex.w));
  672. aBSDF.Ks = texelFetch (uRaytraceMaterialTexture, MATERIAL_KS (aTriangle.TriIndex.w));
  673. aBSDF.Kt = texelFetch (uRaytraceMaterialTexture, MATERIAL_KT (aTriangle.TriIndex.w));
  674. // fetch Fresnel reflectance for both layers
  675. aBSDF.FresnelCoat = texelFetch (uRaytraceMaterialTexture, MATERIAL_FRESNEL_COAT (aTriangle.TriIndex.w)).xyz;
  676. aBSDF.FresnelBase = texelFetch (uRaytraceMaterialTexture, MATERIAL_FRESNEL_BASE (aTriangle.TriIndex.w));
  677. vec4 anLE = texelFetch (uRaytraceMaterialTexture, MATERIAL_LE (aTriangle.TriIndex.w));
  678. // compute smooth normal (in parallel with fetch)
  679. vec3 aNormal = SmoothNormal (aHit.UV, aTriangle.TriIndex);
  680. aNormal = normalize (vec3 (dot (aInvTransf0, aNormal),
  681. dot (aInvTransf1, aNormal),
  682. dot (aInvTransf2, aNormal)));
  683. #ifdef USE_TEXTURES
  684. if (aBSDF.Kd.w >= 0.0 || aBSDF.Kt.w >= 0.0 || aBSDF.FresnelBase.w >=0.0 || anLE.w >= 0.0)
  685. {
  686. vec2 aUVs[3];
  687. vec4 aTexCoord = vec4 (SmoothUV (aHit.UV, aTriangle.TriIndex, aUVs), 0.f, 1.f);
  688. vec4 aTrsfRow1 = texelFetch (uRaytraceMaterialTexture, MATERIAL_TRS1 (aTriangle.TriIndex.w));
  689. vec4 aTrsfRow2 = texelFetch (uRaytraceMaterialTexture, MATERIAL_TRS2 (aTriangle.TriIndex.w));
  690. aTexCoord.st = vec2 (dot (aTrsfRow1, aTexCoord),
  691. dot (aTrsfRow2, aTexCoord));
  692. if (anLE.w >= 0.0)
  693. {
  694. anLE.rgb *= textureLod (sampler2D (uTextureSamplers[int (anLE.w)]), aTexCoord.st, 0.0).rgb;
  695. }
  696. if (aBSDF.Kt.w >= 0.0)
  697. {
  698. vec2 aTexMetRough = textureLod (sampler2D (uTextureSamplers[int (aBSDF.Kt.w)]), aTexCoord.st, 0.0).bg;
  699. float aPbrMetal = aTexMetRough.x;
  700. float aPbrRough2 = aTexMetRough.y * aTexMetRough.y;
  701. aBSDF.Ks.a *= aPbrRough2;
  702. // when using metal-roughness texture, global metalness of material (encoded in FresnelBase) is expected to be 1.0 so that Kd will be 0.0
  703. aBSDF.Kd.rgb = aBSDF.FresnelBase.rgb * (1.0 - aPbrMetal);
  704. aBSDF.FresnelBase.rgb *= aPbrMetal;
  705. }
  706. if (aBSDF.Kd.w >= 0.0)
  707. {
  708. vec4 aTexColor = textureLod (sampler2D (uTextureSamplers[int (aBSDF.Kd.w)]), aTexCoord.st, 0.0);
  709. vec3 aDiff = aTexColor.rgb * aTexColor.a;
  710. aBSDF.Kd.rgb *= aDiff;
  711. aBSDF.FresnelBase.rgb *= aDiff;
  712. if (aTexColor.a != 1.0)
  713. {
  714. // mix transparency BTDF with texture alpha-channel
  715. aBSDF.Ks.rgb *= aTexColor.a;
  716. aBSDF.Kt.rgb = (UNIT - aTexColor.aaa) + aTexColor.a * aBSDF.Kt.rgb;
  717. }
  718. }
  719. #ifndef IGNORE_NORMAL_MAP
  720. if (aBSDF.FresnelBase.w >= 0.0)
  721. {
  722. for (int i = 0 ; i < 3; ++i)
  723. {
  724. aUVs[i] = vec2 (dot (aTrsfRow1, vec4(aUVs[i], 0.0, 1.0)),
  725. dot (aTrsfRow2, vec4(aUVs[i], 0.0, 1.0)));
  726. }
  727. vec3 aMapNormalValue = textureLod (sampler2D (uTextureSamplers[int (aBSDF.FresnelBase.w)]), aTexCoord.st, 0.0).xyz;
  728. mat2 aDeltaUVMatrix = mat2 (aUVs[1] - aUVs[0], aUVs[1] - aUVs[2]);
  729. mat2x3 aDeltaVectorMatrix = mat2x3 (aTriangle.Points[1] - aTriangle.Points[0], aTriangle.Points[1] - aTriangle.Points[2]);
  730. aNormal = TangentSpaceNormal (aDeltaUVMatrix, aDeltaVectorMatrix, aMapNormalValue, aNormal, true);
  731. }
  732. #endif
  733. }
  734. #endif
  735. NormalAdaptation (-theRay.Direct, aHit.Normal, aNormal);
  736. aHit.Normal = aNormal;
  737. SLocalSpace aSpace = buildLocalSpace (aNormal);
  738. if (uLightCount > 0 && IsNotZero (aBSDF, aThroughput))
  739. {
  740. aExpPDF = 1.0 / float(uLightCount);
  741. int aLightIdx = min (int (floor (RandFloat() * float(uLightCount))), uLightCount - 1);
  742. vec4 aLight = texelFetch (uRaytraceLightSrcTexture, LIGHT_POS (aLightIdx));
  743. vec4 aParam = texelFetch (uRaytraceLightSrcTexture, LIGHT_PWR (aLightIdx));
  744. // 'w' component is 0 for infinite light and 1 for point light
  745. aLight.xyz -= mix (ZERO, theRay.Origin, aLight.w);
  746. float aDistance = length (aLight.xyz);
  747. aLight.xyz = SampleLight (aLight.xyz, aDistance,
  748. aLight.w == 0.f /* is infinite */, aParam.w /* max cos or radius */, aExpPDF);
  749. aImpPDF = BsdfPdfLayered (aBSDF,
  750. toLocalSpace (-theRay.Direct, aSpace), toLocalSpace (aLight.xyz, aSpace), aThroughput);
  751. // MIS weight including division by explicit PDF
  752. float aMIS = (aExpPDF == MAXFLOAT) ? 1.f : aExpPDF / (aExpPDF * aExpPDF + aImpPDF * aImpPDF);
  753. vec3 aContrib = aMIS * aParam.rgb /* Le */ * EvalBsdfLayered (
  754. aBSDF, toLocalSpace (aLight.xyz, aSpace), toLocalSpace (-theRay.Direct, aSpace));
  755. if (any (greaterThan (aContrib, MIN_CONTRIBUTION))) // check if light source is important
  756. {
  757. SRay aShadow = SRay (theRay.Origin + aLight.xyz * uSceneEpsilon, aLight.xyz);
  758. aShadow.Origin += aHit.Normal * mix (
  759. -uSceneEpsilon, uSceneEpsilon, step (0.f, dot (aHit.Normal, aLight.xyz)));
  760. float aVisibility = SceneAnyHit (aShadow,
  761. InverseDirection (aLight.xyz), aLight.w == 0.f ? MAXFLOAT : aDistance);
  762. aRadiance += aVisibility * (aThroughput * aContrib);
  763. }
  764. }
  765. // account for self-emission
  766. aRadiance += aThroughput * anLE.rgb;
  767. if (aInMedium) // handle attenuation
  768. {
  769. vec4 aScattering = texelFetch (uRaytraceMaterialTexture, MATERIAL_ABSORPT_BASE (aTriangle.TriIndex.w));
  770. aThroughput *= exp (-aHit.Time * aScattering.w * (UNIT - aScattering.rgb));
  771. }
  772. vec3 anInput = UNIT; // sampled input direction
  773. aImpPDF = SampleBsdfLayered (aBSDF,
  774. toLocalSpace (-theRay.Direct, aSpace), anInput, aThroughput, aInMedium);
  775. float aSurvive = float (any (greaterThan (aThroughput, MIN_THROUGHPUT)));
  776. #ifdef RUSSIAN_ROULETTE
  777. aSurvive = aDepth < 3 ? aSurvive : min (dot (LUMA, aThroughput), 0.95f);
  778. #endif
  779. // here, we additionally increase path length for non-diffuse bounces
  780. if (RandFloat() > aSurvive
  781. || all (lessThan (aThroughput, MIN_THROUGHPUT))
  782. || aDepth >= (theNbSamples / FRAME_STEP + int(step (1.0 / M_PI, aImpPDF))))
  783. {
  784. aDepth = INVALID_BOUNCES; // terminate path
  785. }
  786. #ifdef RUSSIAN_ROULETTE
  787. aThroughput /= aSurvive;
  788. #endif
  789. anInput = normalize (fromLocalSpace (anInput, aSpace));
  790. theRay = SRay (theRay.Origin + anInput * uSceneEpsilon +
  791. aHit.Normal * mix (-uSceneEpsilon, uSceneEpsilon, step (0.f, dot (aHit.Normal, anInput))), anInput);
  792. theInverse = InverseDirection (anInput);
  793. }
  794. gl_FragDepth = aRaytraceDepth;
  795. return vec4 (aRadiance, aRaytraceDepth);
  796. }
  797. #endif