webgl_volume_instancing.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl2 - volume - instancing</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. <meta property="og:title" content="three.js webgl2 - volume - instancing">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_volume_instancing.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_volume_instancing.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl2 - volume - instancing
  16. </div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  28. import { VOXLoader, buildData3DTexture } from 'three/addons/loaders/VOXLoader.js';
  29. let renderer, scene, camera, controls, timer;
  30. init();
  31. function init() {
  32. renderer = new THREE.WebGLRenderer();
  33. renderer.setPixelRatio( window.devicePixelRatio );
  34. renderer.setSize( window.innerWidth, window.innerHeight );
  35. renderer.setAnimationLoop( animate );
  36. document.body.appendChild( renderer.domElement );
  37. scene = new THREE.Scene();
  38. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 );
  39. camera.position.set( 0, 0, 4 );
  40. controls = new OrbitControls( camera, renderer.domElement );
  41. controls.autoRotate = true;
  42. controls.autoRotateSpeed = - 1.0;
  43. controls.enableDamping = true;
  44. timer = new THREE.Timer();
  45. timer.connect( document );
  46. // Material
  47. const vertexShader = /* glsl */`
  48. in vec3 position;
  49. in mat4 instanceMatrix;
  50. uniform mat4 modelMatrix;
  51. uniform mat4 modelViewMatrix;
  52. uniform mat4 projectionMatrix;
  53. uniform vec3 cameraPos;
  54. out vec4 vScreenPosition;
  55. out mat4 vInstanceToViewMatrix;
  56. void main() {
  57. vec4 mvPosition = modelViewMatrix * instanceMatrix * vec4( position, 1.0 );
  58. gl_Position = projectionMatrix * mvPosition;
  59. vScreenPosition = vec4( gl_Position.xy, 0.0, gl_Position.w );
  60. vInstanceToViewMatrix = modelViewMatrix * instanceMatrix;
  61. }
  62. `;
  63. const fragmentShader = /* glsl */`
  64. precision highp float;
  65. precision highp sampler3D;
  66. uniform mat4 viewMatrix;
  67. uniform mat4 modelViewMatrix;
  68. uniform mat4 projectionMatrix;
  69. in vec4 vScreenPosition;
  70. in mat4 vInstanceToViewMatrix;
  71. out vec4 color;
  72. uniform sampler3D map;
  73. vec2 hitBox( vec3 orig, vec3 dir ) {
  74. const vec3 box_min = vec3( - 0.5 );
  75. const vec3 box_max = vec3( 0.5 );
  76. vec3 inv_dir = 1.0 / dir;
  77. vec3 tmin_tmp = ( box_min - orig ) * inv_dir;
  78. vec3 tmax_tmp = ( box_max - orig ) * inv_dir;
  79. vec3 tmin = min( tmin_tmp, tmax_tmp );
  80. vec3 tmax = max( tmin_tmp, tmax_tmp );
  81. float t0 = max( tmin.x, max( tmin.y, tmin.z ) );
  82. float t1 = min( tmax.x, min( tmax.y, tmax.z ) );
  83. return vec2( t0, t1 );
  84. }
  85. float sample1( vec3 p ) {
  86. return texture( map, p ).r;
  87. }
  88. #define epsilon .0001
  89. vec3 normal( vec3 coord ) {
  90. if ( coord.x < epsilon ) return vec3( 1.0, 0.0, 0.0 );
  91. if ( coord.y < epsilon ) return vec3( 0.0, 1.0, 0.0 );
  92. if ( coord.z < epsilon ) return vec3( 0.0, 0.0, 1.0 );
  93. if ( coord.x > 1.0 - epsilon ) return vec3( - 1.0, 0.0, 0.0 );
  94. if ( coord.y > 1.0 - epsilon ) return vec3( 0.0, - 1.0, 0.0 );
  95. if ( coord.z > 1.0 - epsilon ) return vec3( 0.0, 0.0, - 1.0 );
  96. float step = 0.01;
  97. float x = sample1( coord + vec3( - step, 0.0, 0.0 ) ) - sample1( coord + vec3( step, 0.0, 0.0 ) );
  98. float y = sample1( coord + vec3( 0.0, - step, 0.0 ) ) - sample1( coord + vec3( 0.0, step, 0.0 ) );
  99. float z = sample1( coord + vec3( 0.0, 0.0, - step ) ) - sample1( coord + vec3( 0.0, 0.0, step ) );
  100. return normalize( vec3( x, y, z ) );
  101. }
  102. void main() {
  103. // perform w divide in the fragment shader to avoid interpolation artifacts
  104. vec2 screenUv = vScreenPosition.xy / vScreenPosition.w;
  105. mat4 invProjectionMatrix = inverse( projectionMatrix );
  106. mat4 invInstanceToViewMatrix = inverse( vInstanceToViewMatrix );
  107. // get camera ray
  108. vec4 temp;
  109. vec3 camRayOrigin, camRayEnd;
  110. temp = invProjectionMatrix * vec4( screenUv, - 1.0, 1.0 );
  111. camRayOrigin = temp.xyz / temp.w;
  112. temp = invProjectionMatrix * vec4( screenUv, 1.0, 1.0 );
  113. camRayEnd = temp.xyz / temp.w;
  114. // get local ray
  115. vec3 instRayOrigin, instRayDirection, instRayEnd;
  116. instRayOrigin = ( invInstanceToViewMatrix * vec4( camRayOrigin, 1.0 ) ).xyz;
  117. instRayEnd = ( invInstanceToViewMatrix * vec4( camRayEnd, 1.0 ) ).xyz;
  118. instRayDirection = normalize( instRayEnd - instRayOrigin );
  119. // calculate the start of the ray at the box edge
  120. vec2 bounds = hitBox( instRayOrigin, instRayDirection );
  121. if ( bounds.x > bounds.y ) discard;
  122. bounds.x = max( bounds.x, 0.0 );
  123. float stepSize = ( bounds.y - bounds.x ) / 100.0;
  124. vec3 p;
  125. // march through the volume
  126. for ( float i = 0.0; i < 100.0; i += 1.0 ) {
  127. float t = bounds.x + i * stepSize;
  128. p = instRayOrigin + t * instRayDirection;
  129. float d = sample1( p + 0.5 );
  130. if ( d > 0.5 ) {
  131. color.rgb = p * 2.0;
  132. color.a = 1.;
  133. break;
  134. }
  135. }
  136. if ( color.a == 0.0 ) discard;
  137. // calculate the final point in the ndc coords
  138. vec4 ndc = projectionMatrix * vInstanceToViewMatrix * vec4( p, 1.0 );
  139. ndc /= ndc.w;
  140. // map the ndc coordinate to depth
  141. // https://stackoverflow.com/questions/10264949/glsl-gl-fragcoord-z-calculation-and-setting-gl-fragdepth
  142. float far = gl_DepthRange.far;
  143. float near = gl_DepthRange.near;
  144. gl_FragDepth = ( ( ( far - near ) * ndc.z ) + near + far ) / 2.0;
  145. }
  146. `;
  147. const loader = new VOXLoader();
  148. loader.load( 'models/vox/menger.vox', function ( chunks ) {
  149. for ( let i = 0; i < chunks.length; i ++ ) {
  150. const chunk = chunks[ i ];
  151. const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  152. const material = new THREE.RawShaderMaterial( {
  153. glslVersion: THREE.GLSL3,
  154. uniforms: {
  155. map: { value: buildData3DTexture( chunk ) },
  156. cameraPos: { value: new THREE.Vector3() }
  157. },
  158. vertexShader,
  159. fragmentShader,
  160. side: THREE.BackSide
  161. } );
  162. const mesh = new THREE.InstancedMesh( geometry, material, 50000 );
  163. mesh.onBeforeRender = function () {
  164. this.material.uniforms.cameraPos.value.copy( camera.position );
  165. };
  166. const transform = new THREE.Object3D();
  167. for ( let i = 0; i < mesh.count; i ++ ) {
  168. transform.position.random().subScalar( 0.5 ).multiplyScalar( 150 );
  169. transform.rotation.x = Math.random() * Math.PI;
  170. transform.rotation.y = Math.random() * Math.PI;
  171. transform.rotation.z = Math.random() * Math.PI;
  172. transform.updateMatrix();
  173. mesh.setMatrixAt( i, transform.matrix );
  174. }
  175. scene.add( mesh );
  176. }
  177. } );
  178. window.addEventListener( 'resize', onWindowResize );
  179. }
  180. function onWindowResize() {
  181. camera.aspect = window.innerWidth / window.innerHeight;
  182. camera.updateProjectionMatrix();
  183. renderer.setSize( window.innerWidth, window.innerHeight );
  184. }
  185. function animate() {
  186. timer.update();
  187. const delta = timer.getDelta();
  188. controls.update( delta );
  189. renderer.render( scene, camera );
  190. }
  191. </script>
  192. </body>
  193. </html>
粤ICP备19079148号