webgl_ubo_arrays.html 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js WebGL 2 - Uniform Buffer Objects Arrays</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> - Uniform Buffer Objects Arrays
  12. </div>
  13. <div id="container"></div>
  14. <script id="vertexShader" type="x-shader/x-vertex">
  15. uniform ViewData {
  16. mat4 projectionMatrix;
  17. mat4 viewMatrix;
  18. };
  19. uniform mat4 modelMatrix;
  20. uniform mat3 normalMatrix;
  21. in vec3 position;
  22. in vec3 normal;
  23. in vec2 uv;
  24. out vec2 vUv;
  25. out vec3 vPositionEye;
  26. out vec3 vNormalEye;
  27. void main() {
  28. vec4 vertexPositionEye = viewMatrix * modelMatrix * vec4( position, 1.0 );
  29. vPositionEye = (modelMatrix * vec4( position, 1.0 )).xyz;
  30. vNormalEye = (vec4(normal , 1.)).xyz;
  31. vUv = uv;
  32. gl_Position = projectionMatrix * vertexPositionEye;
  33. }
  34. </script>
  35. <script id="fragmentShader" type="x-shader/x-vertex">
  36. precision highp float;
  37. precision highp int;
  38. uniform LightingData {
  39. vec4 lightPosition[POINTLIGHTS_MAX];
  40. vec4 lightColor[POINTLIGHTS_MAX];
  41. float pointLightsCount;
  42. };
  43. #include <common>
  44. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  45. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  46. if ( cutoffDistance > 0.0 ) {
  47. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  48. }
  49. return distanceFalloff;
  50. }
  51. in vec2 vUv;
  52. in vec3 vPositionEye;
  53. in vec3 vNormalEye;
  54. out vec4 fragColor;
  55. void main() {
  56. vec4 color = vec4(vec3(0.), 1.);
  57. for (int x = 0; x < int(pointLightsCount); x++) {
  58. vec3 offset = lightPosition[x].xyz - vPositionEye;
  59. vec3 dirToLight = normalize( offset );
  60. float distance = length( offset );
  61. float diffuse = max(0.0, dot(vNormalEye, dirToLight));
  62. float attenuation = 1.0 / (distance * distance);
  63. vec3 lightWeighting = lightColor[x].xyz * getDistanceAttenuation( distance, 4., .7 );
  64. color.rgb += lightWeighting;
  65. }
  66. fragColor = color;
  67. }
  68. </script>
  69. <script type="importmap">
  70. {
  71. "imports": {
  72. "three": "../build/three.module.js",
  73. "three/addons/": "./jsm/"
  74. }
  75. }
  76. </script>
  77. <script type="module">
  78. import * as THREE from 'three';
  79. import Stats from 'three/addons/libs/stats.module.js';
  80. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  81. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  82. let camera, scene, renderer, clock, stats;
  83. let lightingUniformsGroup, lightCenters;
  84. const container = document.getElementById( 'container' );
  85. const pointLightsMax = 300;
  86. const api = {
  87. count: 200,
  88. };
  89. init();
  90. function init() {
  91. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
  92. camera.position.set( 0, 50, 50 );
  93. scene = new THREE.Scene();
  94. camera.lookAt( scene.position );
  95. clock = new THREE.Clock();
  96. // geometry
  97. const geometry = new THREE.SphereGeometry();
  98. // uniforms groups
  99. lightingUniformsGroup = new THREE.UniformsGroup();
  100. lightingUniformsGroup.setName( 'LightingData' );
  101. const data = [];
  102. const dataColors = [];
  103. lightCenters = [];
  104. for ( let i = 0; i < pointLightsMax; i ++ ) {
  105. const col = new THREE.Color( 0xffffff * Math.random() ).toArray();
  106. const x = Math.random() * 50 - 25;
  107. const z = Math.random() * 50 - 25;
  108. data.push( new THREE.Uniform( new THREE.Vector4( x, 1, z, 0 ) ) ); // light position
  109. dataColors.push( new THREE.Uniform( new THREE.Vector4( col[ 0 ], col[ 1 ], col[ 2 ], 0 ) ) ); // light color
  110. // Store the center positions
  111. lightCenters.push( { x, z } );
  112. }
  113. lightingUniformsGroup.add( data ); // light position
  114. lightingUniformsGroup.add( dataColors ); // light position
  115. lightingUniformsGroup.add( new THREE.Uniform( pointLightsMax ) ); // light position
  116. const cameraUniformsGroup = new THREE.UniformsGroup();
  117. cameraUniformsGroup.setName( 'ViewData' );
  118. cameraUniformsGroup.add( new THREE.Uniform( camera.projectionMatrix ) ); // projection matrix
  119. cameraUniformsGroup.add( new THREE.Uniform( camera.matrixWorldInverse ) ); // view matrix
  120. const material = new THREE.RawShaderMaterial( {
  121. uniforms: {
  122. modelMatrix: { value: null },
  123. normalMatrix: { value: null }
  124. },
  125. // uniformsGroups: [ cameraUniformsGroup, lightingUniformsGroup ],
  126. name: 'Box',
  127. defines: {
  128. POINTLIGHTS_MAX: pointLightsMax
  129. },
  130. vertexShader: document.getElementById( 'vertexShader' ).textContent,
  131. fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
  132. glslVersion: THREE.GLSL3
  133. } );
  134. const plane = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), material.clone() );
  135. plane.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  136. plane.material.uniforms.modelMatrix.value = plane.matrixWorld;
  137. plane.material.uniforms.normalMatrix.value = plane.normalMatrix;
  138. plane.rotation.x = - Math.PI / 2;
  139. plane.position.y = - 1;
  140. scene.add( plane );
  141. // meshes
  142. const gridSize = { x: 10, y: 1, z: 10 };
  143. const spacing = 6;
  144. for ( let i = 0; i < gridSize.x; i ++ ) {
  145. for ( let j = 0; j < gridSize.y; j ++ ) {
  146. for ( let k = 0; k < gridSize.z; k ++ ) {
  147. const mesh = new THREE.Mesh( geometry, material.clone() );
  148. mesh.name = 'Sphere';
  149. mesh.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  150. mesh.material.uniforms.modelMatrix.value = mesh.matrixWorld;
  151. mesh.material.uniforms.normalMatrix.value = mesh.normalMatrix;
  152. scene.add( mesh );
  153. mesh.position.x = i * spacing - ( gridSize.x * spacing ) / 2;
  154. mesh.position.y = 0;
  155. mesh.position.z = k * spacing - ( gridSize.z * spacing ) / 2;
  156. }
  157. }
  158. }
  159. //
  160. renderer = new THREE.WebGLRenderer( { antialias: true } );
  161. renderer.setSize( window.innerWidth, window.innerHeight );
  162. renderer.setAnimationLoop( animate );
  163. container.appendChild( renderer.domElement );
  164. window.addEventListener( 'resize', onWindowResize, false );
  165. // controls
  166. const controls = new OrbitControls( camera, renderer.domElement );
  167. controls.enablePan = false;
  168. // stats
  169. stats = new Stats();
  170. document.body.appendChild( stats.dom );
  171. // gui
  172. const gui = new GUI();
  173. gui.add( api, 'count', 1, pointLightsMax ).step( 1 ).onChange( function () {
  174. lightingUniformsGroup.uniforms[ 2 ].value = api.count;
  175. } );
  176. }
  177. function onWindowResize() {
  178. camera.aspect = window.innerWidth / window.innerHeight;
  179. camera.updateProjectionMatrix();
  180. renderer.setSize( window.innerWidth, window.innerHeight );
  181. }
  182. //
  183. function animate() {
  184. const elapsedTime = clock.getElapsedTime();
  185. const lights = lightingUniformsGroup.uniforms[ 0 ];
  186. // Parameters for circular movement
  187. const radius = 5; // Smaller radius for individual circular movements
  188. const speed = 0.5; // Speed of rotation
  189. // Update each light's position
  190. for ( let i = 0; i < lights.length; i ++ ) {
  191. const light = lights[ i ];
  192. const center = lightCenters[ i ];
  193. // Calculate circular movement around the light's center
  194. const angle = speed * elapsedTime + i * 0.5; // Phase difference for each light
  195. const x = center.x + Math.sin( angle ) * radius;
  196. const z = center.z + Math.cos( angle ) * radius;
  197. // Update the light's position
  198. light.value.set( x, 1, z, 0 );
  199. }
  200. renderer.render( scene, camera );
  201. stats.update();
  202. }
  203. </script>
  204. </body>
  205. </html>