Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebGLUniformsGroups: Support for array of Uniform Buffer Object #27293

Merged
merged 7 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/files.json
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@
"webgl2_rendertarget_texture2darray",
"webgl2_texture2darray_compressed",
"webgl2_ubo",
"webgl2_ubo_arrays",
"webgl2_volume_cloud",
"webgl2_volume_instancing",
"webgl2_volume_perlin"
Expand Down
Binary file added examples/screenshots/webgl2_ubo_arrays.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
317 changes: 317 additions & 0 deletions examples/webgl2_ubo_arrays.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,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.enabledPan = 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>
8 changes: 7 additions & 1 deletion src/core/UniformsGroup.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,13 @@ class UniformsGroup extends EventDispatcher {

for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {

this.uniforms.push( uniformsSource[ i ].clone() );
const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];

for ( let j = 0; j < uniforms.length; j ++ ) {

this.uniforms.push( uniforms[ j ].clone() );

}

}

Expand Down
Loading