forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebgl2_ubo_arrays.html
317 lines (214 loc) · 8.21 KB
/
webgl2_ubo_arrays.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js WebGL 2 - Uniform Buffer Objects Arrays</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Uniform Buffer Objects Arrays
</div>
<div id="container"></div>
<script id="vertexShader" type="x-shader/x-vertex">
uniform ViewData {
mat4 projectionMatrix;
mat4 viewMatrix;
};
uniform mat4 modelMatrix;
uniform mat3 normalMatrix;
in vec3 position;
in vec3 normal;
in vec2 uv;
out vec2 vUv;
out vec3 vPositionEye;
out vec3 vNormalEye;
void main() {
vec4 vertexPositionEye = viewMatrix * modelMatrix * vec4( position, 1.0 );
vPositionEye = (modelMatrix * vec4( position, 1.0 )).xyz;
vNormalEye = (vec4(normal , 1.)).xyz;
vUv = uv;
gl_Position = projectionMatrix * vertexPositionEye;
}
</script>
<script id="fragmentShader" type="x-shader/x-vertex">
precision highp float;
precision highp int;
uniform LightingData {
vec4 lightPosition[POINTLIGHTS_MAX];
vec4 lightColor[POINTLIGHTS_MAX];
float pointLightsCount;
};
#include <common>
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
if ( cutoffDistance > 0.0 ) {
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
}
return distanceFalloff;
}
in vec2 vUv;
in vec3 vPositionEye;
in vec3 vNormalEye;
out vec4 fragColor;
void main() {
vec4 color = vec4(vec3(0.), 1.);
for (int x = 0; x < int(pointLightsCount); x++) {
vec3 offset = lightPosition[x].xyz - vPositionEye;
vec3 dirToLight = normalize( offset );
float distance = length( offset );
float diffuse = max(0.0, dot(vNormalEye, dirToLight));
float attenuation = 1.0 / (distance * distance);
vec3 lightWeighting = lightColor[x].xyz * getDistanceAttenuation( distance, 4., .7 );
color.rgb += lightWeighting;
}
fragColor = color;
}
</script>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
let camera, scene, renderer, clock, stats;
let lightingUniformsGroup, lightCenters;
const container = document.getElementById( 'container' );
const pointLightsMax = 300;
const api = {
count: 200,
};
init();
animate();
function init() {
if ( WebGL.isWebGL2Available() === false ) {
document.body.appendChild( WebGL.getWebGL2ErrorMessage() );
return;
}
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
camera.position.set( 0, 50, 50 );
scene = new THREE.Scene();
camera.lookAt( scene.position );
clock = new THREE.Clock();
// geometry
const geometry = new THREE.SphereGeometry();
// uniforms groups
lightingUniformsGroup = new THREE.UniformsGroup();
lightingUniformsGroup.setName( 'LightingData' );
const data = [];
const dataColors = [];
lightCenters = [];
for ( let i = 0; i < pointLightsMax; i ++ ) {
const col = new THREE.Color( 0xffffff * Math.random() ).toArray();
const x = Math.random() * 50 - 25;
const z = Math.random() * 50 - 25;
data.push( new THREE.Uniform( new THREE.Vector4( x, 1, z, 0 ) ) ); // light position
dataColors.push( new THREE.Uniform( new THREE.Vector4( col[ 0 ], col[ 1 ], col[ 2 ], 0 ) ) ); // light color
// Store the center positions
lightCenters.push( { x, z } );
}
lightingUniformsGroup.add( data ); // light position
lightingUniformsGroup.add( dataColors ); // light position
lightingUniformsGroup.add( new THREE.Uniform( pointLightsMax ) ); // light position
const cameraUniformsGroup = new THREE.UniformsGroup();
cameraUniformsGroup.setName( 'ViewData' );
cameraUniformsGroup.add( new THREE.Uniform( camera.projectionMatrix ) ); // projection matrix
cameraUniformsGroup.add( new THREE.Uniform( camera.matrixWorldInverse ) ); // view matrix
const material = new THREE.RawShaderMaterial( {
uniforms: {
modelMatrix: { value: null },
normalMatrix: { value: null }
},
// uniformsGroups: [ cameraUniformsGroup, lightingUniformsGroup ],
name: 'Box',
defines: {
POINTLIGHTS_MAX: pointLightsMax
},
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
glslVersion: THREE.GLSL3
} );
const plane = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), material.clone() );
plane.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
plane.material.uniforms.modelMatrix.value = plane.matrixWorld;
plane.material.uniforms.normalMatrix.value = plane.normalMatrix;
plane.rotation.x = - Math.PI / 2;
plane.position.y = - 1;
scene.add( plane );
// meshes
const gridSize = { x: 10, y: 1, z: 10 };
const spacing = 6;
for ( let i = 0; i < gridSize.x; i ++ ) {
for ( let j = 0; j < gridSize.y; j ++ ) {
for ( let k = 0; k < gridSize.z; k ++ ) {
const mesh = new THREE.Mesh( geometry, material.clone() );
mesh.name = 'Sphere';
mesh.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
mesh.material.uniforms.modelMatrix.value = mesh.matrixWorld;
mesh.material.uniforms.normalMatrix.value = mesh.normalMatrix;
scene.add( mesh );
mesh.position.x = i * spacing - ( gridSize.x * spacing ) / 2;
mesh.position.y = 0;
mesh.position.z = k * spacing - ( gridSize.z * spacing ) / 2;
}
}
}
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
// controls
const controls = new OrbitControls( camera, renderer.domElement );
controls.enablePan = false;
// stats
stats = new Stats();
document.body.appendChild( stats.dom );
// gui
const gui = new GUI();
gui.add( api, 'count', 1, pointLightsMax ).step( 1 ).onChange( function () {
lightingUniformsGroup.uniforms[ 2 ].value = api.count;
} );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//
function animate() {
requestAnimationFrame( animate );
stats.update();
const elapsedTime = clock.getElapsedTime();
const lights = lightingUniformsGroup.uniforms[ 0 ];
// Parameters for circular movement
const radius = 5; // Smaller radius for individual circular movements
const speed = 0.5; // Speed of rotation
// Update each light's position
for ( let i = 0; i < lights.length; i ++ ) {
const light = lights[ i ];
const center = lightCenters[ i ];
// Calculate circular movement around the light's center
const angle = speed * elapsedTime + i * 0.5; // Phase difference for each light
const x = center.x + Math.sin( angle ) * radius;
const z = center.z + Math.cos( angle ) * radius;
// Update the light's position
light.value.set( x, 1, z, 0 );
}
renderer.render( scene, camera );
}
</script>
</body>
</html>