webgl_materials_envmaps_parallax.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>js webgl - box projected cubemap environment mapping</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="container"></div>
  11. <div id="info">
  12. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - box projected cubemap environment mapping. <br> created by <a href="https://codercat.tk" target="_blank" rel="noopener">codercat</a>
  13. </div>
  14. <script type="module">
  15. import * as THREE from '../build/three.module.js';
  16. import { GUI } from './jsm/libs/dat.gui.module.js';
  17. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  18. import { RectAreaLightHelper } from './jsm/helpers/RectAreaLightHelper.js';
  19. import { RectAreaLightUniformsLib } from './jsm/lights/RectAreaLightUniformsLib.js';
  20. // shader injection for box projected cube environment mapping
  21. const worldposReplace = /* glsl */`
  22. #define BOX_PROJECTED_ENV_MAP
  23. #if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )
  24. vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );
  25. #ifdef BOX_PROJECTED_ENV_MAP
  26. vWorldPosition = worldPosition.xyz;
  27. #endif
  28. #endif
  29. `;
  30. const envmapPhysicalParsReplace = /* glsl */`
  31. #if defined( USE_ENVMAP )
  32. #define BOX_PROJECTED_ENV_MAP
  33. #ifdef BOX_PROJECTED_ENV_MAP
  34. uniform vec3 cubeMapSize;
  35. uniform vec3 cubeMapPos;
  36. varying vec3 vWorldPosition;
  37. vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) {
  38. vec3 nDir = normalize( v );
  39. vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir;
  40. vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir;
  41. vec3 rbminmax;
  42. rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x;
  43. rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y;
  44. rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z;
  45. float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z );
  46. vec3 boxIntersection = vWorldPosition + nDir * correction;
  47. return boxIntersection - cubePos;
  48. }
  49. #endif
  50. #ifdef ENVMAP_MODE_REFRACTION
  51. uniform float refractionRatio;
  52. #endif
  53. vec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {
  54. vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );
  55. #ifdef ENVMAP_TYPE_CUBE
  56. #ifdef BOX_PROJECTED_ENV_MAP
  57. worldNormal = parallaxCorrectNormal( worldNormal, cubeMapSize, cubeMapPos );
  58. #endif
  59. vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );
  60. // TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level
  61. // of a specular cubemap, or just the default level of a specially created irradiance cubemap.
  62. #ifdef TEXTURE_LOD_EXT
  63. vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );
  64. #else
  65. // force the bias high to get the last LOD level as it is the most blurred.
  66. vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );
  67. #endif
  68. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  69. #elif defined( ENVMAP_TYPE_CUBE_UV )
  70. vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
  71. #else
  72. vec4 envMapColor = vec4( 0.0 );
  73. #endif
  74. return PI * envMapColor.rgb * envMapIntensity;
  75. }
  76. // Trowbridge-Reitz distribution to Mip level, following the logic of http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html
  77. float getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {
  78. float maxMIPLevelScalar = float( maxMIPLevel );
  79. float sigma = PI * roughness * roughness / ( 1.0 + roughness );
  80. float desiredMIPLevel = maxMIPLevelScalar + log2( sigma );
  81. // clamp to allowable LOD ranges.
  82. return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );
  83. }
  84. vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {
  85. #ifdef ENVMAP_MODE_REFLECTION
  86. vec3 reflectVec = reflect( -viewDir, normal );
  87. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  88. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  89. #else
  90. vec3 reflectVec = refract( -viewDir, normal, refractionRatio );
  91. #endif
  92. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  93. float specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );
  94. #ifdef ENVMAP_TYPE_CUBE
  95. #ifdef BOX_PROJECTED_ENV_MAP
  96. reflectVec = parallaxCorrectNormal( reflectVec, cubeMapSize, cubeMapPos );
  97. #endif
  98. vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );
  99. #ifdef TEXTURE_LOD_EXT
  100. vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );
  101. #else
  102. vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );
  103. #endif
  104. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  105. #elif defined( ENVMAP_TYPE_CUBE_UV )
  106. vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
  107. #endif
  108. return envMapColor.rgb * envMapIntensity;
  109. }
  110. #endif
  111. `;
  112. // scene size
  113. const WIDTH = window.innerWidth;
  114. const HEIGHT = window.innerHeight;
  115. // camera
  116. const VIEW_ANGLE = 45;
  117. const ASPECT = WIDTH / HEIGHT;
  118. const NEAR = 1;
  119. const FAR = 800;
  120. let camera, cubeCamera, scene, renderer;
  121. let cameraControls;
  122. let groundPlane, wallMat;
  123. init();
  124. function init() {
  125. const container = document.getElementById( 'container' );
  126. // renderer
  127. renderer = new THREE.WebGLRenderer( { antialias: true } );
  128. renderer.setPixelRatio( window.devicePixelRatio );
  129. renderer.setSize( WIDTH, HEIGHT );
  130. container.appendChild( renderer.domElement );
  131. // gui controls
  132. const gui = new GUI();
  133. const params = {
  134. 'box projected': true
  135. };
  136. const bpcemGui = gui.add( params, 'box projected' );
  137. bpcemGui.onChange( function ( value ) {
  138. if ( value ) {
  139. groundPlane.material = boxProjectedMat;
  140. } else {
  141. groundPlane.material = defaultMat;
  142. }
  143. render();
  144. } );
  145. // scene
  146. scene = new THREE.Scene();
  147. // camera
  148. camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
  149. camera.position.set( 280, 106, - 5 );
  150. cameraControls = new OrbitControls( camera, renderer.domElement );
  151. cameraControls.target.set( 0, - 10, 0 );
  152. cameraControls.maxDistance = 400;
  153. cameraControls.minDistance = 10;
  154. cameraControls.addEventListener( 'change', render );
  155. cameraControls.update();
  156. // cube camera for environment map
  157. const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 512, {
  158. format: THREE.RGBFormat,
  159. generateMipmaps: true,
  160. minFilter: THREE.LinearMipmapLinearFilter
  161. } );
  162. cubeCamera = new THREE.CubeCamera( 1, 1000, cubeRenderTarget );
  163. cubeCamera.position.set( 0, - 100, 0 );
  164. scene.add( cubeCamera );
  165. // ground floor ( with box projected environment mapping )
  166. const loader = new THREE.TextureLoader();
  167. const rMap = loader.load( 'textures/lava/lavatile.jpg' );
  168. rMap.wrapS = THREE.RepeatWrapping;
  169. rMap.wrapT = THREE.RepeatWrapping;
  170. rMap.repeat.set( 2, 1 );
  171. const defaultMat = new THREE.MeshPhysicalMaterial( {
  172. roughness: 1,
  173. envMap: cubeRenderTarget.texture,
  174. roughnessMap: rMap
  175. } );
  176. const boxProjectedMat = new THREE.MeshPhysicalMaterial( {
  177. color: new THREE.Color( '#ffffff' ),
  178. roughness: 1,
  179. envMap: cubeRenderTarget.texture,
  180. roughnessMap: rMap
  181. } );
  182. boxProjectedMat.onBeforeCompile = function ( shader ) {
  183. //these parameters are for the cubeCamera texture
  184. shader.uniforms.cubeMapSize = { value: new THREE.Vector3( 200, 200, 100 ) };
  185. shader.uniforms.cubeMapPos = { value: new THREE.Vector3( 0, - 50, 0 ) };
  186. //replace shader chunks with box projection chunks
  187. shader.vertexShader = 'varying vec3 vWorldPosition;\n' + shader.vertexShader;
  188. shader.vertexShader = shader.vertexShader.replace(
  189. '#include <worldpos_vertex>',
  190. worldposReplace
  191. );
  192. shader.fragmentShader = shader.fragmentShader.replace(
  193. '#include <envmap_physical_pars_fragment>',
  194. envmapPhysicalParsReplace
  195. );
  196. };
  197. groundPlane = new THREE.Mesh( new THREE.PlaneGeometry( 200, 100, 100 ), boxProjectedMat );
  198. groundPlane.rotateX( - Math.PI / 2 );
  199. groundPlane.position.set( 0, - 49, 0 );
  200. scene.add( groundPlane );
  201. // walls
  202. const diffuseTex = loader.load( 'textures/brick_diffuse.jpg', function () {
  203. updateCubeMap();
  204. } );
  205. const bumpTex = loader.load( 'textures/brick_bump.jpg', function () {
  206. updateCubeMap();
  207. } );
  208. wallMat = new THREE.MeshPhysicalMaterial( {
  209. map: diffuseTex,
  210. bumpMap: bumpTex,
  211. bumpScale: 0.3,
  212. } );
  213. const planeGeo = new THREE.PlaneGeometry( 100, 100 );
  214. const planeBack1 = new THREE.Mesh( planeGeo, wallMat );
  215. planeBack1.position.z = - 50;
  216. planeBack1.position.x = - 50;
  217. scene.add( planeBack1 );
  218. const planeBack2 = new THREE.Mesh( planeGeo, wallMat );
  219. planeBack2.position.z = - 50;
  220. planeBack2.position.x = 50;
  221. scene.add( planeBack2 );
  222. const planeFront1 = new THREE.Mesh( planeGeo, wallMat );
  223. planeFront1.position.z = 50;
  224. planeFront1.position.x = - 50;
  225. planeFront1.rotateY( Math.PI );
  226. scene.add( planeFront1 );
  227. const planeFront2 = new THREE.Mesh( planeGeo, wallMat );
  228. planeFront2.position.z = 50;
  229. planeFront2.position.x = 50;
  230. planeFront2.rotateY( Math.PI );
  231. scene.add( planeFront2 );
  232. const planeRight = new THREE.Mesh( planeGeo, wallMat );
  233. planeRight.position.x = 100;
  234. planeRight.rotateY( - Math.PI / 2 );
  235. scene.add( planeRight );
  236. const planeLeft = new THREE.Mesh( planeGeo, wallMat );
  237. planeLeft.position.x = - 100;
  238. planeLeft.rotateY( Math.PI / 2 );
  239. scene.add( planeLeft );
  240. //lights
  241. const width = 50;
  242. const height = 50;
  243. const intensity = 10;
  244. RectAreaLightUniformsLib.init();
  245. const blueRectLight = new THREE.RectAreaLight( 0xf3aaaa, intensity, width, height );
  246. blueRectLight.position.set( 99, 5, 0 );
  247. blueRectLight.lookAt( 0, 5, 0 );
  248. scene.add( blueRectLight );
  249. const blueRectLightHelper = new RectAreaLightHelper( blueRectLight );
  250. blueRectLight.add( blueRectLightHelper );
  251. const redRectLight = new THREE.RectAreaLight( 0x9aaeff, intensity, width, height );
  252. redRectLight.position.set( - 99, 5, 0 );
  253. redRectLight.lookAt( 0, 5, 0 );
  254. scene.add( redRectLight );
  255. const redRectLightHelper = new RectAreaLightHelper( redRectLight );
  256. redRectLight.add( redRectLightHelper );
  257. render();
  258. }
  259. function updateCubeMap() {
  260. //disable specular highlights on walls in the environment map
  261. wallMat.roughness = 1;
  262. groundPlane.visible = false;
  263. cubeCamera.position.copy( groundPlane.position );
  264. cubeCamera.update( renderer, scene );
  265. wallMat.roughness = 0.6;
  266. groundPlane.visible = true;
  267. render();
  268. }
  269. function render() {
  270. renderer.render( scene, camera );
  271. }
  272. </script>
  273. </body>
  274. </html>