PhysicalLightingModel.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import BRDF_Lambert from './BSDF/BRDF_Lambert.js';
  2. import BRDF_GGX from './BSDF/BRDF_GGX.js';
  3. import DFGApprox from './BSDF/DFGApprox.js';
  4. import EnvironmentBRDF from './BSDF/EnvironmentBRDF.js';
  5. import F_Schlick from './BSDF/F_Schlick.js';
  6. import Schlick_to_F0 from './BSDF/Schlick_to_F0.js';
  7. import BRDF_Sheen from './BSDF/BRDF_Sheen.js';
  8. import { LTC_Evaluate, LTC_Uv } from './BSDF/LTC.js';
  9. import LightingModel from '../core/LightingModel.js';
  10. import { diffuseColor, specularColor, specularF90, roughness, clearcoat, clearcoatRoughness, sheen, sheenRoughness, iridescence, iridescenceIOR, iridescenceThickness, ior, thickness, transmission, attenuationDistance, attenuationColor, dispersion } from '../core/PropertyNode.js';
  11. import { transformedNormalView, transformedClearcoatNormalView, transformedNormalWorld } from '../accessors/Normal.js';
  12. import { positionViewDirection, positionView, positionWorld } from '../accessors/Position.js';
  13. import { Fn, float, vec2, vec3, vec4, mat3, If } from '../tsl/TSLBase.js';
  14. import { select } from '../math/ConditionalNode.js';
  15. import { mix, normalize, refract, length, clamp, log2, log, exp, smoothstep } from '../math/MathNode.js';
  16. import { div } from '../math/OperatorNode.js';
  17. import { cameraPosition, cameraProjectionMatrix, cameraViewMatrix } from '../accessors/Camera.js';
  18. import { modelWorldMatrix } from '../accessors/ModelNode.js';
  19. import { screenSize } from '../display/ScreenNode.js';
  20. import { viewportMipTexture } from '../display/ViewportTextureNode.js';
  21. import { textureBicubic } from '../accessors/TextureBicubic.js';
  22. import { Loop } from '../utils/LoopNode.js';
  23. import { BackSide } from '../../constants.js';
  24. //
  25. // Transmission
  26. //
  27. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  28. // Direction of refracted light.
  29. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  30. // Compute rotation-independent scaling of the model matrix.
  31. const modelScale = vec3(
  32. length( modelMatrix[ 0 ].xyz ),
  33. length( modelMatrix[ 1 ].xyz ),
  34. length( modelMatrix[ 2 ].xyz )
  35. );
  36. // The thickness is specified in local space.
  37. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  38. } ).setLayout( {
  39. name: 'getVolumeTransmissionRay',
  40. type: 'vec3',
  41. inputs: [
  42. { name: 'n', type: 'vec3' },
  43. { name: 'v', type: 'vec3' },
  44. { name: 'thickness', type: 'float' },
  45. { name: 'ior', type: 'float' },
  46. { name: 'modelMatrix', type: 'mat4' }
  47. ]
  48. } );
  49. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  50. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  51. // an IOR of 1.5 results in the default amount of microfacet refraction.
  52. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  53. } ).setLayout( {
  54. name: 'applyIorToRoughness',
  55. type: 'float',
  56. inputs: [
  57. { name: 'roughness', type: 'float' },
  58. { name: 'ior', type: 'float' }
  59. ]
  60. } );
  61. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  62. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  63. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  64. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  65. const transmissionSample = vTexture.sample( fragCoord );
  66. //const transmissionSample = viewportMipTexture( fragCoord );
  67. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  68. return textureBicubic( transmissionSample, lod );
  69. } );
  70. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  71. If( attenuationDistance.notEqual( 0 ), () => {
  72. // Compute light attenuation using Beer's law.
  73. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  74. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  75. return transmittance;
  76. } );
  77. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  78. return vec3( 1.0 );
  79. } ).setLayout( {
  80. name: 'volumeAttenuation',
  81. type: 'vec3',
  82. inputs: [
  83. { name: 'transmissionDistance', type: 'float' },
  84. { name: 'attenuationColor', type: 'vec3' },
  85. { name: 'attenuationDistance', type: 'float' }
  86. ]
  87. } );
  88. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  89. let transmittedLight, transmittance;
  90. if ( dispersion ) {
  91. transmittedLight = vec4().toVar();
  92. transmittance = vec3().toVar();
  93. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  94. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  95. Loop( { start: 0, end: 3 }, ( { i } ) => {
  96. const ior = iors.element( i );
  97. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  98. const refractedRayExit = position.add( transmissionRay );
  99. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  100. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  101. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  102. refractionCoords.addAssign( 1.0 );
  103. refractionCoords.divAssign( 2.0 );
  104. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  105. // Sample framebuffer to get pixel the refracted ray hits.
  106. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  107. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  108. transmittedLight.a.addAssign( transmissionSample.a );
  109. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  110. } );
  111. transmittedLight.a.divAssign( 3.0 );
  112. } else {
  113. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  114. const refractedRayExit = position.add( transmissionRay );
  115. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  116. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  117. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  118. refractionCoords.addAssign( 1.0 );
  119. refractionCoords.divAssign( 2.0 );
  120. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  121. // Sample framebuffer to get pixel the refracted ray hits.
  122. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  123. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  124. }
  125. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  126. const dotNV = n.dot( v ).clamp();
  127. // Get the specular component.
  128. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  129. dotNV,
  130. specularColor,
  131. specularF90,
  132. roughness
  133. } ) );
  134. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  135. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  136. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  137. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  138. } );
  139. //
  140. // Iridescence
  141. //
  142. // XYZ to linear-sRGB color space
  143. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  144. 3.2404542, - 0.9692660, 0.0556434,
  145. - 1.5371385, 1.8760108, - 0.2040259,
  146. - 0.4985314, 0.0415560, 1.0572252
  147. );
  148. // Assume air interface for top
  149. // Note: We don't handle the case fresnel0 == 1
  150. const Fresnel0ToIor = ( fresnel0 ) => {
  151. const sqrtF0 = fresnel0.sqrt();
  152. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  153. };
  154. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  155. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  156. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  157. };
  158. // Fresnel equations for dielectric/dielectric interfaces.
  159. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  160. // Evaluation XYZ sensitivity curves in Fourier space
  161. const evalSensitivity = ( OPD, shift ) => {
  162. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  163. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  164. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  165. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  166. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  167. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  168. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  169. const rgb = XYZ_TO_REC709.mul( xyz );
  170. return rgb;
  171. };
  172. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  173. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  174. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  175. // Evaluate the cosTheta on the base layer (Snell law)
  176. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  177. // Handle TIR:
  178. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  179. If( cosTheta2Sq.lessThan( 0 ), () => {
  180. return vec3( 1.0 );
  181. } );
  182. const cosTheta2 = cosTheta2Sq.sqrt();
  183. // First interface
  184. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  185. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  186. //const R21 = R12;
  187. const T121 = R12.oneMinus();
  188. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  189. const phi21 = float( Math.PI ).sub( phi12 );
  190. // Second interface
  191. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  192. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  193. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  194. const phi23 = vec3(
  195. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  196. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  197. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  198. );
  199. // Phase shift
  200. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  201. const phi = vec3( phi21 ).add( phi23 );
  202. // Compound terms
  203. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  204. const r123 = R123.sqrt();
  205. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  206. // Reflectance term for m = 0 (DC term amplitude)
  207. const C0 = R12.add( Rs );
  208. const I = C0.toVar();
  209. // Reflectance term for m > 0 (pairs of diracs)
  210. const Cm = Rs.sub( T121 ).toVar();
  211. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  212. Cm.mulAssign( r123 );
  213. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  214. I.addAssign( Cm.mul( Sm ) );
  215. } );
  216. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  217. return I.max( vec3( 0.0 ) );
  218. } ).setLayout( {
  219. name: 'evalIridescence',
  220. type: 'vec3',
  221. inputs: [
  222. { name: 'outsideIOR', type: 'float' },
  223. { name: 'eta2', type: 'float' },
  224. { name: 'cosTheta1', type: 'float' },
  225. { name: 'thinFilmThickness', type: 'float' },
  226. { name: 'baseF0', type: 'vec3' }
  227. ]
  228. } );
  229. //
  230. // Sheen
  231. //
  232. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  233. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  234. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  235. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  236. const dotNV = normal.dot( viewDir ).saturate();
  237. const r2 = roughness.pow2();
  238. const a = select(
  239. roughness.lessThan( 0.25 ),
  240. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  241. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  242. );
  243. const b = select(
  244. roughness.lessThan( 0.25 ),
  245. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  246. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  247. );
  248. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  249. return DG.mul( 1.0 / Math.PI ).saturate();
  250. } );
  251. const clearcoatF0 = vec3( 0.04 );
  252. const clearcoatF90 = float( 1 );
  253. /**
  254. * Represents the lighting model for a PBR material.
  255. *
  256. * @augments LightingModel
  257. */
  258. class PhysicalLightingModel extends LightingModel {
  259. /**
  260. * Constructs a new physical lighting model.
  261. *
  262. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  263. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  264. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  265. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  266. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  267. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  268. */
  269. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  270. super();
  271. /**
  272. * Whether clearcoat is supported or not.
  273. *
  274. * @type {Boolean}
  275. * @default false
  276. */
  277. this.clearcoat = clearcoat;
  278. /**
  279. * Whether sheen is supported or not.
  280. *
  281. * @type {Boolean}
  282. * @default false
  283. */
  284. this.sheen = sheen;
  285. /**
  286. * Whether iridescence is supported or not.
  287. *
  288. * @type {Boolean}
  289. * @default false
  290. */
  291. this.iridescence = iridescence;
  292. /**
  293. * Whether anisotropy is supported or not.
  294. *
  295. * @type {Boolean}
  296. * @default false
  297. */
  298. this.anisotropy = anisotropy;
  299. /**
  300. * Whether transmission is supported or not.
  301. *
  302. * @type {Boolean}
  303. * @default false
  304. */
  305. this.transmission = transmission;
  306. /**
  307. * Whether dispersion is supported or not.
  308. *
  309. * @type {Boolean}
  310. * @default false
  311. */
  312. this.dispersion = dispersion;
  313. /**
  314. * The clear coat radiance.
  315. *
  316. * @type {Node?}
  317. * @default null
  318. */
  319. this.clearcoatRadiance = null;
  320. /**
  321. * The clear coat specular direct.
  322. *
  323. * @type {Node?}
  324. * @default null
  325. */
  326. this.clearcoatSpecularDirect = null;
  327. /**
  328. * The clear coat specular indirect.
  329. *
  330. * @type {Node?}
  331. * @default null
  332. */
  333. this.clearcoatSpecularIndirect = null;
  334. /**
  335. * The sheen specular direct.
  336. *
  337. * @type {Node?}
  338. * @default null
  339. */
  340. this.sheenSpecularDirect = null;
  341. /**
  342. * The sheen specular indirect.
  343. *
  344. * @type {Node?}
  345. * @default null
  346. */
  347. this.sheenSpecularIndirect = null;
  348. /**
  349. * The iridescence Fresnel.
  350. *
  351. * @type {Node?}
  352. * @default null
  353. */
  354. this.iridescenceFresnel = null;
  355. /**
  356. * The iridescence F0.
  357. *
  358. * @type {Node?}
  359. * @default null
  360. */
  361. this.iridescenceF0 = null;
  362. }
  363. /**
  364. * Depending on what features are requested, the method prepares certain node variables
  365. * which are later used for lighting computations.
  366. *
  367. * @param {ContextNode} context - The current node context.
  368. */
  369. start( context ) {
  370. if ( this.clearcoat === true ) {
  371. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  372. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  373. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  374. }
  375. if ( this.sheen === true ) {
  376. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  377. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  378. }
  379. if ( this.iridescence === true ) {
  380. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  381. this.iridescenceFresnel = evalIridescence( {
  382. outsideIOR: float( 1.0 ),
  383. eta2: iridescenceIOR,
  384. cosTheta1: dotNVi,
  385. thinFilmThickness: iridescenceThickness,
  386. baseF0: specularColor
  387. } );
  388. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  389. }
  390. if ( this.transmission === true ) {
  391. const position = positionWorld;
  392. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  393. const n = transformedNormalWorld;
  394. context.backdrop = getIBLVolumeRefraction(
  395. n,
  396. v,
  397. roughness,
  398. diffuseColor,
  399. specularColor,
  400. specularF90, // specularF90
  401. position, // positionWorld
  402. modelWorldMatrix, // modelMatrix
  403. cameraViewMatrix, // viewMatrix
  404. cameraProjectionMatrix, // projMatrix
  405. ior,
  406. thickness,
  407. attenuationColor,
  408. attenuationDistance,
  409. this.dispersion ? dispersion : null
  410. );
  411. context.backdropAlpha = transmission;
  412. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  413. }
  414. }
  415. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  416. // Approximates multi-scattering in order to preserve energy.
  417. // http://www.jcgt.org/published/0008/01/03/
  418. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  419. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  420. const fab = DFGApprox( { roughness, dotNV } );
  421. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  422. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  423. const Ess = fab.x.add( fab.y );
  424. const Ems = Ess.oneMinus();
  425. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  426. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  427. singleScatter.addAssign( FssEss );
  428. multiScatter.addAssign( Fms.mul( Ems ) );
  429. }
  430. /**
  431. * Implements the direct light.
  432. *
  433. * @param {Object} input - The input data.
  434. * @param {StackNode} stack - The current stack.
  435. * @param {NodeBuilder} builder - The current node builder.
  436. */
  437. direct( { lightDirection, lightColor, reflectedLight } ) {
  438. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  439. const irradiance = dotNL.mul( lightColor );
  440. if ( this.sheen === true ) {
  441. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  442. }
  443. if ( this.clearcoat === true ) {
  444. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  445. const ccIrradiance = dotNLcc.mul( lightColor );
  446. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  447. }
  448. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  449. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  450. }
  451. /**
  452. * This method is intended for implementing the direct light term for
  453. * rect area light nodes.
  454. *
  455. * @param {Object} input - The input data.
  456. * @param {StackNode} stack - The current stack.
  457. * @param {NodeBuilder} builder - The current node builder.
  458. */
  459. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  460. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  461. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  462. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  463. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  464. const N = transformedNormalView;
  465. const V = positionViewDirection;
  466. const P = positionView.toVar();
  467. const uv = LTC_Uv( { N, V, roughness } );
  468. const t1 = ltc_1.sample( uv ).toVar();
  469. const t2 = ltc_2.sample( uv ).toVar();
  470. const mInv = mat3(
  471. vec3( t1.x, 0, t1.y ),
  472. vec3( 0, 1, 0 ),
  473. vec3( t1.z, 0, t1.w )
  474. ).toVar();
  475. // LTC Fresnel Approximation by Stephen Hill
  476. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  477. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  478. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  479. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  480. }
  481. /**
  482. * Implements the indirect lighting.
  483. *
  484. * @param {ContextNode} context - The current node context.
  485. * @param {StackNode} stack - The current stack.
  486. * @param {NodeBuilder} builder - The current node builder.
  487. */
  488. indirect( context, stack, builder ) {
  489. this.indirectDiffuse( context, stack, builder );
  490. this.indirectSpecular( context, stack, builder );
  491. this.ambientOcclusion( context, stack, builder );
  492. }
  493. /**
  494. * Implements the indirect diffuse term.
  495. *
  496. * @param {ContextNode} input - The current node context.
  497. * @param {StackNode} stack - The current stack.
  498. * @param {NodeBuilder} builder - The current node builder.
  499. */
  500. indirectDiffuse( { irradiance, reflectedLight } ) {
  501. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  502. }
  503. /**
  504. * Implements the indirect specular term.
  505. *
  506. * @param {ContextNode} input - The current node context.
  507. * @param {StackNode} stack - The current stack.
  508. * @param {NodeBuilder} builder - The current node builder.
  509. */
  510. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  511. if ( this.sheen === true ) {
  512. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  513. sheen,
  514. IBLSheenBRDF( {
  515. normal: transformedNormalView,
  516. viewDir: positionViewDirection,
  517. roughness: sheenRoughness
  518. } )
  519. ) );
  520. }
  521. if ( this.clearcoat === true ) {
  522. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  523. const clearcoatEnv = EnvironmentBRDF( {
  524. dotNV: dotNVcc,
  525. specularColor: clearcoatF0,
  526. specularF90: clearcoatF90,
  527. roughness: clearcoatRoughness
  528. } );
  529. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  530. }
  531. // Both indirect specular and indirect diffuse light accumulate here
  532. const singleScattering = vec3().toVar( 'singleScattering' );
  533. const multiScattering = vec3().toVar( 'multiScattering' );
  534. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  535. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  536. const totalScattering = singleScattering.add( multiScattering );
  537. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  538. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  539. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  540. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  541. }
  542. /**
  543. * Implements the ambient occlusion term.
  544. *
  545. * @param {ContextNode} input - The current node context.
  546. * @param {StackNode} stack - The current stack.
  547. * @param {NodeBuilder} builder - The current node builder.
  548. */
  549. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  550. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  551. const aoNV = dotNV.add( ambientOcclusion );
  552. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  553. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  554. if ( this.clearcoat === true ) {
  555. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  556. }
  557. if ( this.sheen === true ) {
  558. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  559. }
  560. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  561. reflectedLight.indirectSpecular.mulAssign( aoNode );
  562. }
  563. /**
  564. * Used for final lighting accumulations depending on the requested features.
  565. *
  566. * @param {ContextNode} context - The current node context.
  567. * @param {StackNode} stack - The current stack.
  568. * @param {NodeBuilder} builder - The current node builder.
  569. */
  570. finish( context ) {
  571. const { outgoingLight } = context;
  572. if ( this.clearcoat === true ) {
  573. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  574. const Fcc = F_Schlick( {
  575. dotVH: dotNVcc,
  576. f0: clearcoatF0,
  577. f90: clearcoatF90
  578. } );
  579. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  580. outgoingLight.assign( clearcoatLight );
  581. }
  582. if ( this.sheen === true ) {
  583. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  584. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  585. outgoingLight.assign( sheenLight );
  586. }
  587. }
  588. }
  589. export default PhysicalLightingModel;
粤ICP备19079148号