webgl_raymarching_reflect.html 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - raymarching - reflect</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. <style type="text/css">
  9. html, body {
  10. height: 100%;
  11. }
  12. #container {
  13. width: 100%;
  14. height: 100%;
  15. display: flex;
  16. align-items: center;
  17. justify-content: center;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div id="info">
  23. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl raymarching example<br/>
  24. reflect by <a href="https://github.com/gam0022" target="_blank" rel="noopener">gam0022</a> (<a href="http://qiita.com/gam0022/items/03699a07e4a4b5f2d41f" target="_blank" rel="noopener">article</a>)
  25. </div>
  26. <div id="container">
  27. <canvas id="canvas"></canvas>
  28. </div>
  29. <script id="fragment_shader" type="x-shader/x-fragment">
  30. precision highp float;
  31. uniform vec2 resolution;
  32. uniform mat4 viewMatrix;
  33. uniform vec3 cameraPosition;
  34. uniform mat4 cameraWorldMatrix;
  35. uniform mat4 cameraProjectionMatrixInverse;
  36. const float EPS = 0.01;
  37. const float OFFSET = EPS * 100.0;
  38. const vec3 lightDir = vec3( -0.48666426339228763, 0.8111071056538127, -0.3244428422615251 );
  39. // distance functions
  40. vec3 opRep( vec3 p, float interval ) {
  41. vec2 q = mod( p.xz, interval ) - interval * 0.5;
  42. return vec3( q.x, p.y, q.y );
  43. }
  44. float sphereDist( vec3 p, float r ) {
  45. return length( opRep( p, 3.0 ) ) - r;
  46. }
  47. float floorDist( vec3 p ){
  48. return dot(p, vec3( 0.0, 1.0, 0.0 ) ) + 1.0;
  49. }
  50. vec4 minVec4( vec4 a, vec4 b ) {
  51. return ( a.a < b.a ) ? a : b;
  52. }
  53. float checkeredPattern( vec3 p ) {
  54. float u = 1.0 - floor( mod( p.x, 2.0 ) );
  55. float v = 1.0 - floor( mod( p.z, 2.0 ) );
  56. if ( ( u == 1.0 && v < 1.0 ) || ( u < 1.0 && v == 1.0 ) ) {
  57. return 0.2;
  58. } else {
  59. return 1.0;
  60. }
  61. }
  62. vec3 hsv2rgb( vec3 c ) {
  63. vec4 K = vec4( 1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0 );
  64. vec3 p = abs( fract( c.xxx + K.xyz ) * 6.0 - K.www );
  65. return c.z * mix( K.xxx, clamp( p - K.xxx, 0.0, 1.0 ), c.y );
  66. }
  67. float sceneDist( vec3 p ) {
  68. return min(
  69. sphereDist( p, 1.0 ),
  70. floorDist( p )
  71. );
  72. }
  73. vec4 sceneColor( vec3 p ) {
  74. return minVec4(
  75. // 3 * 6 / 2 = 9
  76. vec4( hsv2rgb(vec3( ( p.z + p.x ) / 9.0, 1.0, 1.0 ) ), sphereDist( p, 1.0 ) ),
  77. vec4( vec3( 0.5 ) * checkeredPattern( p ), floorDist( p ) )
  78. );
  79. }
  80. vec3 getNormal( vec3 p ) {
  81. return normalize(vec3(
  82. sceneDist(p + vec3( EPS, 0.0, 0.0 ) ) - sceneDist(p + vec3( -EPS, 0.0, 0.0 ) ),
  83. sceneDist(p + vec3( 0.0, EPS, 0.0 ) ) - sceneDist(p + vec3( 0.0, -EPS, 0.0 ) ),
  84. sceneDist(p + vec3( 0.0, 0.0, EPS ) ) - sceneDist(p + vec3( 0.0, 0.0, -EPS ) )
  85. ));
  86. }
  87. float getShadow( vec3 ro, vec3 rd ) {
  88. float h = 0.0;
  89. float c = 0.0;
  90. float r = 1.0;
  91. float shadowCoef = 0.5;
  92. for ( float t = 0.0; t < 50.0; t++ ) {
  93. h = sceneDist( ro + rd * c );
  94. if ( h < EPS ) return shadowCoef;
  95. r = min( r, h * 16.0 / c );
  96. c += h;
  97. }
  98. return 1.0 - shadowCoef + r * shadowCoef;
  99. }
  100. vec3 getRayColor( vec3 origin, vec3 ray, out vec3 pos, out vec3 normal, out bool hit ) {
  101. // marching loop
  102. float dist;
  103. float depth = 0.0;
  104. pos = origin;
  105. for ( int i = 0; i < 64; i++ ){
  106. dist = sceneDist( pos );
  107. depth += dist;
  108. pos = origin + depth * ray;
  109. if ( abs(dist) < EPS ) break;
  110. }
  111. // hit check and calc color
  112. vec3 color;
  113. if ( abs(dist) < EPS ) {
  114. normal = getNormal( pos );
  115. float diffuse = clamp( dot( lightDir, normal ), 0.1, 1.0 );
  116. float specular = pow( clamp( dot( reflect( lightDir, normal ), ray ), 0.0, 1.0 ), 10.0 );
  117. float shadow = getShadow( pos + normal * OFFSET, lightDir );
  118. color = ( sceneColor( pos ).rgb * diffuse + vec3( 0.8 ) * specular ) * max( 0.5, shadow );
  119. hit = true;
  120. } else {
  121. color = vec3( 0.0 );
  122. }
  123. return color - pow( clamp( 0.05 * depth, 0.0, 0.6 ), 2.0 );
  124. }
  125. void main(void) {
  126. // screen position
  127. vec2 screenPos = ( gl_FragCoord.xy * 2.0 - resolution ) / resolution;
  128. // ray direction in normalized device coordinate
  129. vec4 ndcRay = vec4( screenPos.xy, 1.0, 1.0 );
  130. // convert ray direction from normalized device coordinate to world coordinate
  131. vec3 ray = ( cameraWorldMatrix * cameraProjectionMatrixInverse * ndcRay ).xyz;
  132. ray = normalize( ray );
  133. // camera position
  134. vec3 cPos = cameraPosition;
  135. // cast ray
  136. vec3 color = vec3( 0.0 );
  137. vec3 pos, normal;
  138. bool hit;
  139. float alpha = 1.0;
  140. for ( int i = 0; i < 3; i++ ) {
  141. color += alpha * getRayColor( cPos, ray, pos, normal, hit );
  142. alpha *= 0.3;
  143. ray = normalize( reflect( ray, normal ) );
  144. cPos = pos + normal * OFFSET;
  145. if ( !hit ) break;
  146. }
  147. gl_FragColor = vec4( color, 1.0 );
  148. }
  149. </script>
  150. <script id="vertex_shader" type="x-shader/x-vertex">
  151. attribute vec3 position;
  152. void main(void) {
  153. gl_Position = vec4(position, 1.0);
  154. }
  155. </script>
  156. <script type="module">
  157. import * as THREE from '../build/three.module.js';
  158. import Stats from './jsm/libs/stats.module.js';
  159. import { GUI } from './jsm/libs/dat.gui.module.js';
  160. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  161. var dolly, camera, scene, renderer;
  162. var geometry, material, mesh;
  163. var stats;
  164. var canvas = document.querySelector( '#canvas' );
  165. var config = {
  166. saveImage: function () {
  167. renderer.render( scene, camera );
  168. window.open( canvas.toDataURL() );
  169. },
  170. resolution: '512'
  171. };
  172. init();
  173. render();
  174. function init() {
  175. renderer = new THREE.WebGLRenderer( { canvas: canvas } );
  176. renderer.setPixelRatio( window.devicePixelRatio );
  177. renderer.setSize( config.resolution, config.resolution );
  178. window.addEventListener( 'resize', onWindowResize );
  179. // THREE.Scene
  180. scene = new THREE.Scene();
  181. dolly = new THREE.Group();
  182. scene.add( dolly );
  183. camera = new THREE.PerspectiveCamera( 60, canvas.width / canvas.height, 1, 2000 );
  184. camera.position.z = 4;
  185. dolly.add( camera );
  186. geometry = new THREE.PlaneBufferGeometry( 2.0, 2.0 );
  187. material = new THREE.RawShaderMaterial( {
  188. uniforms: {
  189. resolution: { value: new THREE.Vector2( canvas.width, canvas.height ) },
  190. cameraWorldMatrix: { value: camera.matrixWorld },
  191. cameraProjectionMatrixInverse: { value: new THREE.Matrix4().getInverse( camera.projectionMatrix ) }
  192. },
  193. vertexShader: document.getElementById( 'vertex_shader' ).textContent,
  194. fragmentShader: document.getElementById( 'fragment_shader' ).textContent
  195. } );
  196. mesh = new THREE.Mesh( geometry, material );
  197. mesh.frustumCulled = false;
  198. scene.add( mesh );
  199. // Controls
  200. var controls = new OrbitControls( camera, canvas );
  201. // GUI
  202. var gui = new GUI();
  203. gui.add( config, 'saveImage' ).name( 'Save Image' );
  204. gui.add( config, 'resolution', [ '256', '512', '800', 'full' ] ).name( 'Resolution' ).onChange( onWindowResize );
  205. stats = new Stats();
  206. document.body.appendChild( stats.dom );
  207. }
  208. function onWindowResize() {
  209. if ( config.resolution === 'full' ) {
  210. renderer.setSize( window.innerWidth, window.innerHeight );
  211. } else {
  212. renderer.setSize( config.resolution, config.resolution );
  213. }
  214. camera.aspect = canvas.width / canvas.height;
  215. camera.updateProjectionMatrix();
  216. material.uniforms.resolution.value.set( canvas.width, canvas.height );
  217. material.uniforms.cameraProjectionMatrixInverse.value.getInverse( camera.projectionMatrix );
  218. }
  219. function render( time ) {
  220. stats.begin();
  221. dolly.position.z = - time / 1000;
  222. renderer.render( scene, camera );
  223. stats.end();
  224. requestAnimationFrame( render );
  225. }
  226. </script>
  227. </body>
  228. </html>