webgl2_ubo_arrays.html 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. <!-- Import maps polyfill -->
  70. <!-- Remove this when import maps will be widely supported -->
  71. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  72. <script type="importmap">
  73. {
  74. "imports": {
  75. "three": "../build/three.module.js",
  76. "three/addons/": "./jsm/"
  77. }
  78. }
  79. </script>
  80. <script type="module">
  81. import * as THREE from 'three';
  82. import Stats from 'three/addons/libs/stats.module.js';
  83. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  84. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  85. let camera, scene, renderer, clock, stats;
  86. let lightingUniformsGroup, lightCenters;
  87. const container = document.getElementById( 'container' );
  88. const pointLightsMax = 300;
  89. const api = {
  90. count: 200,
  91. };
  92. init();
  93. animate();
  94. function init() {
  95. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
  96. camera.position.set( 0, 50, 50 );
  97. scene = new THREE.Scene();
  98. camera.lookAt( scene.position );
  99. clock = new THREE.Clock();
  100. // geometry
  101. const geometry = new THREE.SphereGeometry();
  102. // uniforms groups
  103. lightingUniformsGroup = new THREE.UniformsGroup();
  104. lightingUniformsGroup.setName( 'LightingData' );
  105. const data = [];
  106. const dataColors = [];
  107. lightCenters = [];
  108. for ( let i = 0; i < pointLightsMax; i ++ ) {
  109. const col = new THREE.Color( 0xffffff * Math.random() ).toArray();
  110. const x = Math.random() * 50 - 25;
  111. const z = Math.random() * 50 - 25;
  112. data.push( new THREE.Uniform( new THREE.Vector4( x, 1, z, 0 ) ) ); // light position
  113. dataColors.push( new THREE.Uniform( new THREE.Vector4( col[ 0 ], col[ 1 ], col[ 2 ], 0 ) ) ); // light color
  114. // Store the center positions
  115. lightCenters.push( { x, z } );
  116. }
  117. lightingUniformsGroup.add( data ); // light position
  118. lightingUniformsGroup.add( dataColors ); // light position
  119. lightingUniformsGroup.add( new THREE.Uniform( pointLightsMax ) ); // light position
  120. const cameraUniformsGroup = new THREE.UniformsGroup();
  121. cameraUniformsGroup.setName( 'ViewData' );
  122. cameraUniformsGroup.add( new THREE.Uniform( camera.projectionMatrix ) ); // projection matrix
  123. cameraUniformsGroup.add( new THREE.Uniform( camera.matrixWorldInverse ) ); // view matrix
  124. const material = new THREE.RawShaderMaterial( {
  125. uniforms: {
  126. modelMatrix: { value: null },
  127. normalMatrix: { value: null }
  128. },
  129. // uniformsGroups: [ cameraUniformsGroup, lightingUniformsGroup ],
  130. name: 'Box',
  131. defines: {
  132. POINTLIGHTS_MAX: pointLightsMax
  133. },
  134. vertexShader: document.getElementById( 'vertexShader' ).textContent,
  135. fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
  136. glslVersion: THREE.GLSL3
  137. } );
  138. const plane = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), material.clone() );
  139. plane.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  140. plane.material.uniforms.modelMatrix.value = plane.matrixWorld;
  141. plane.material.uniforms.normalMatrix.value = plane.normalMatrix;
  142. plane.rotation.x = - Math.PI / 2;
  143. plane.position.y = - 1;
  144. scene.add( plane );
  145. // meshes
  146. const gridSize = { x: 10, y: 1, z: 10 };
  147. const spacing = 6;
  148. for ( let i = 0; i < gridSize.x; i ++ ) {
  149. for ( let j = 0; j < gridSize.y; j ++ ) {
  150. for ( let k = 0; k < gridSize.z; k ++ ) {
  151. const mesh = new THREE.Mesh( geometry, material.clone() );
  152. mesh.name = 'Sphere';
  153. mesh.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  154. mesh.material.uniforms.modelMatrix.value = mesh.matrixWorld;
  155. mesh.material.uniforms.normalMatrix.value = mesh.normalMatrix;
  156. scene.add( mesh );
  157. mesh.position.x = i * spacing - ( gridSize.x * spacing ) / 2;
  158. mesh.position.y = 0;
  159. mesh.position.z = k * spacing - ( gridSize.z * spacing ) / 2;
  160. }
  161. }
  162. }
  163. //
  164. renderer = new THREE.WebGLRenderer( { antialias: true } );
  165. renderer.setSize( window.innerWidth, window.innerHeight );
  166. container.appendChild( renderer.domElement );
  167. window.addEventListener( 'resize', onWindowResize, false );
  168. // controls
  169. const controls = new OrbitControls( camera, renderer.domElement );
  170. controls.enablePan = false;
  171. // stats
  172. stats = new Stats();
  173. document.body.appendChild( stats.dom );
  174. // gui
  175. const gui = new GUI();
  176. gui.add( api, 'count', 1, pointLightsMax ).step( 1 ).onChange( function () {
  177. lightingUniformsGroup.uniforms[ 2 ].value = api.count;
  178. } );
  179. }
  180. function onWindowResize() {
  181. camera.aspect = window.innerWidth / window.innerHeight;
  182. camera.updateProjectionMatrix();
  183. renderer.setSize( window.innerWidth, window.innerHeight );
  184. }
  185. //
  186. function animate() {
  187. requestAnimationFrame( animate );
  188. stats.update();
  189. const elapsedTime = clock.getElapsedTime();
  190. const lights = lightingUniformsGroup.uniforms[ 0 ];
  191. // Parameters for circular movement
  192. const radius = 5; // Smaller radius for individual circular movements
  193. const speed = 0.5; // Speed of rotation
  194. // Update each light's position
  195. for ( let i = 0; i < lights.length; i ++ ) {
  196. const light = lights[ i ];
  197. const center = lightCenters[ i ];
  198. // Calculate circular movement around the light's center
  199. const angle = speed * elapsedTime + i * 0.5; // Phase difference for each light
  200. const x = center.x + Math.sin( angle ) * radius;
  201. const z = center.z + Math.cos( angle ) * radius;
  202. // Update the light's position
  203. light.value.set( x, 1, z, 0 );
  204. }
  205. renderer.render( scene, camera );
  206. }
  207. </script>
  208. </body>
  209. </html>