webgl2_ubo_arrays.html 8.2 KB

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