webgl_texture3d_partialupdate.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl2 - volume - cloud</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="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl2 - volume - cloud
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  24. import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
  25. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  26. const INITIAL_CLOUD_SIZE = 128;
  27. let renderer, scene, camera;
  28. let mesh;
  29. let prevTime = performance.now();
  30. let cloudTexture = null;
  31. init();
  32. function generateCloudTexture( size, scaleFactor = 1.0 ) {
  33. const data = new Uint8Array( size * size * size );
  34. const scale = scaleFactor * 10.0 / size;
  35. let i = 0;
  36. const perlin = new ImprovedNoise();
  37. const vector = new THREE.Vector3();
  38. for ( let z = 0; z < size; z ++ ) {
  39. for ( let y = 0; y < size; y ++ ) {
  40. for ( let x = 0; x < size; x ++ ) {
  41. const dist = vector.set( x, y, z ).subScalar( size / 2 ).divideScalar( size ).length();
  42. const fadingFactor = ( 1.0 - dist ) * ( 1.0 - dist );
  43. data[ i ] = ( 128 + 128 * perlin.noise( x * scale / 1.5, y * scale, z * scale / 1.5 ) ) * fadingFactor;
  44. i ++;
  45. }
  46. }
  47. }
  48. return new THREE.Data3DTexture( data, size, size, size );
  49. }
  50. function init() {
  51. renderer = new THREE.WebGLRenderer();
  52. renderer.setPixelRatio( window.devicePixelRatio );
  53. renderer.setSize( window.innerWidth, window.innerHeight );
  54. renderer.setAnimationLoop( animate );
  55. document.body.appendChild( renderer.domElement );
  56. scene = new THREE.Scene();
  57. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
  58. camera.position.set( 0, 0, 1.5 );
  59. new OrbitControls( camera, renderer.domElement );
  60. // Sky
  61. const canvas = document.createElement( 'canvas' );
  62. canvas.width = 1;
  63. canvas.height = 32;
  64. const context = canvas.getContext( '2d' );
  65. const gradient = context.createLinearGradient( 0, 0, 0, 32 );
  66. gradient.addColorStop( 0.0, '#014a84' );
  67. gradient.addColorStop( 0.5, '#0561a0' );
  68. gradient.addColorStop( 1.0, '#437ab6' );
  69. context.fillStyle = gradient;
  70. context.fillRect( 0, 0, 1, 32 );
  71. const skyMap = new THREE.CanvasTexture( canvas );
  72. skyMap.colorSpace = THREE.SRGBColorSpace;
  73. const sky = new THREE.Mesh(
  74. new THREE.SphereGeometry( 10 ),
  75. new THREE.MeshBasicMaterial( { map: skyMap, side: THREE.BackSide } )
  76. );
  77. scene.add( sky );
  78. // Texture
  79. const texture = new THREE.Data3DTexture(
  80. new Uint8Array( INITIAL_CLOUD_SIZE * INITIAL_CLOUD_SIZE * INITIAL_CLOUD_SIZE ).fill( 0 ),
  81. INITIAL_CLOUD_SIZE,
  82. INITIAL_CLOUD_SIZE,
  83. INITIAL_CLOUD_SIZE
  84. );
  85. texture.format = THREE.RedFormat;
  86. texture.minFilter = THREE.LinearFilter;
  87. texture.magFilter = THREE.LinearFilter;
  88. texture.unpackAlignment = 1;
  89. texture.needsUpdate = true;
  90. cloudTexture = texture;
  91. // Material
  92. const vertexShader = /* glsl */`
  93. in vec3 position;
  94. uniform mat4 modelMatrix;
  95. uniform mat4 modelViewMatrix;
  96. uniform mat4 projectionMatrix;
  97. uniform vec3 cameraPos;
  98. out vec3 vOrigin;
  99. out vec3 vDirection;
  100. void main() {
  101. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  102. vOrigin = vec3( inverse( modelMatrix ) * vec4( cameraPos, 1.0 ) ).xyz;
  103. vDirection = position - vOrigin;
  104. gl_Position = projectionMatrix * mvPosition;
  105. }
  106. `;
  107. const fragmentShader = /* glsl */`
  108. precision highp float;
  109. precision highp sampler3D;
  110. uniform mat4 modelViewMatrix;
  111. uniform mat4 projectionMatrix;
  112. in vec3 vOrigin;
  113. in vec3 vDirection;
  114. out vec4 color;
  115. uniform vec3 base;
  116. uniform sampler3D map;
  117. uniform float threshold;
  118. uniform float range;
  119. uniform float opacity;
  120. uniform float steps;
  121. uniform float frame;
  122. uint wang_hash(uint seed)
  123. {
  124. seed = (seed ^ 61u) ^ (seed >> 16u);
  125. seed *= 9u;
  126. seed = seed ^ (seed >> 4u);
  127. seed *= 0x27d4eb2du;
  128. seed = seed ^ (seed >> 15u);
  129. return seed;
  130. }
  131. float randomFloat(inout uint seed)
  132. {
  133. return float(wang_hash(seed)) / 4294967296.;
  134. }
  135. vec2 hitBox( vec3 orig, vec3 dir ) {
  136. const vec3 box_min = vec3( - 0.5 );
  137. const vec3 box_max = vec3( 0.5 );
  138. vec3 inv_dir = 1.0 / dir;
  139. vec3 tmin_tmp = ( box_min - orig ) * inv_dir;
  140. vec3 tmax_tmp = ( box_max - orig ) * inv_dir;
  141. vec3 tmin = min( tmin_tmp, tmax_tmp );
  142. vec3 tmax = max( tmin_tmp, tmax_tmp );
  143. float t0 = max( tmin.x, max( tmin.y, tmin.z ) );
  144. float t1 = min( tmax.x, min( tmax.y, tmax.z ) );
  145. return vec2( t0, t1 );
  146. }
  147. float sample1( vec3 p ) {
  148. return texture( map, p ).r;
  149. }
  150. float shading( vec3 coord ) {
  151. float step = 0.01;
  152. return sample1( coord + vec3( - step ) ) - sample1( coord + vec3( step ) );
  153. }
  154. vec4 linearToSRGB( in vec4 value ) {
  155. return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
  156. }
  157. void main(){
  158. vec3 rayDir = normalize( vDirection );
  159. vec2 bounds = hitBox( vOrigin, rayDir );
  160. if ( bounds.x > bounds.y ) discard;
  161. bounds.x = max( bounds.x, 0.0 );
  162. vec3 p = vOrigin + bounds.x * rayDir;
  163. vec3 inc = 1.0 / abs( rayDir );
  164. float delta = min( inc.x, min( inc.y, inc.z ) );
  165. delta /= steps;
  166. // Jitter
  167. // Nice little seed from
  168. // https://blog.demofox.org/2020/05/25/casual-shadertoy-path-tracing-1-basic-camera-diffuse-emissive/
  169. uint seed = uint( gl_FragCoord.x ) * uint( 1973 ) + uint( gl_FragCoord.y ) * uint( 9277 ) + uint( frame ) * uint( 26699 );
  170. vec3 size = vec3( textureSize( map, 0 ) );
  171. float randNum = randomFloat( seed ) * 2.0 - 1.0;
  172. p += rayDir * randNum * ( 1.0 / size );
  173. //
  174. vec4 ac = vec4( base, 0.0 );
  175. for ( float t = bounds.x; t < bounds.y; t += delta ) {
  176. float d = sample1( p + 0.5 );
  177. d = smoothstep( threshold - range, threshold + range, d ) * opacity;
  178. float col = shading( p + 0.5 ) * 3.0 + ( ( p.x + p.y ) * 0.25 ) + 0.2;
  179. ac.rgb += ( 1.0 - ac.a ) * d * col;
  180. ac.a += ( 1.0 - ac.a ) * d;
  181. if ( ac.a >= 0.95 ) break;
  182. p += rayDir * delta;
  183. }
  184. color = linearToSRGB( ac );
  185. if ( color.a == 0.0 ) discard;
  186. }
  187. `;
  188. const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  189. const material = new THREE.RawShaderMaterial( {
  190. glslVersion: THREE.GLSL3,
  191. uniforms: {
  192. base: { value: new THREE.Color( 0x798aa0 ) },
  193. map: { value: texture },
  194. cameraPos: { value: new THREE.Vector3() },
  195. threshold: { value: 0.25 },
  196. opacity: { value: 0.25 },
  197. range: { value: 0.1 },
  198. steps: { value: 100 },
  199. frame: { value: 0 }
  200. },
  201. vertexShader,
  202. fragmentShader,
  203. side: THREE.BackSide,
  204. transparent: true
  205. } );
  206. mesh = new THREE.Mesh( geometry, material );
  207. scene.add( mesh );
  208. //
  209. const parameters = {
  210. threshold: 0.25,
  211. opacity: 0.25,
  212. range: 0.1,
  213. steps: 100
  214. };
  215. function update() {
  216. material.uniforms.threshold.value = parameters.threshold;
  217. material.uniforms.opacity.value = parameters.opacity;
  218. material.uniforms.range.value = parameters.range;
  219. material.uniforms.steps.value = parameters.steps;
  220. }
  221. const gui = new GUI();
  222. gui.add( parameters, 'threshold', 0, 1, 0.01 ).onChange( update );
  223. gui.add( parameters, 'opacity', 0, 1, 0.01 ).onChange( update );
  224. gui.add( parameters, 'range', 0, 1, 0.01 ).onChange( update );
  225. gui.add( parameters, 'steps', 0, 200, 1 ).onChange( update );
  226. window.addEventListener( 'resize', onWindowResize );
  227. }
  228. function onWindowResize() {
  229. camera.aspect = window.innerWidth / window.innerHeight;
  230. camera.updateProjectionMatrix();
  231. renderer.setSize( window.innerWidth, window.innerHeight );
  232. }
  233. let curr = 0;
  234. const countPerRow = 4;
  235. const countPerSlice = countPerRow * countPerRow;
  236. const sliceCount = 4;
  237. const totalCount = sliceCount * countPerSlice;
  238. const margins = 8;
  239. const perElementPaddedSize = ( INITIAL_CLOUD_SIZE - margins ) / countPerRow;
  240. const perElementSize = Math.floor( ( INITIAL_CLOUD_SIZE - 1 ) / countPerRow );
  241. function animate() {
  242. const time = performance.now();
  243. if ( time - prevTime > 1500.0 && curr < totalCount ) {
  244. const position = new THREE.Vector3(
  245. Math.floor( curr % countPerRow ) * perElementSize + margins * 0.5,
  246. ( Math.floor( ( ( curr % countPerSlice ) / countPerRow ) ) ) * perElementSize + margins * 0.5,
  247. Math.floor( curr / countPerSlice ) * perElementSize + margins * 0.5
  248. ).floor();
  249. const maxDimension = perElementPaddedSize - 1;
  250. const box = new THREE.Box3( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( maxDimension, maxDimension, maxDimension ) );
  251. const scaleFactor = ( Math.random() + 0.5 ) * 0.5;
  252. const source = generateCloudTexture( perElementPaddedSize, scaleFactor );
  253. renderer.copyTextureToTexture3D( source, cloudTexture, box, position );
  254. prevTime = time;
  255. curr ++;
  256. }
  257. mesh.material.uniforms.cameraPos.value.copy( camera.position );
  258. // mesh.rotation.y = - performance.now() / 7500;
  259. mesh.material.uniforms.frame.value ++;
  260. renderer.render( scene, camera );
  261. }
  262. </script>
  263. </body>
  264. </html>