What is the best approach to handle large numbers like the one provided in GLSL?
I have a shader that requires Date.now()
as a uniform, which is defined as:
The
Date.now()
method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. — MDN
For example, 1514678400000
represents the last day of the year.
When I pass this value to my ShaderMaterial
, it doesn't seem to work as expected unless I significantly scale down the value.
Specifically, I notice a difference in behavior when trying to map the last 2500 milliseconds to a value between 0–1:
JavaScript: ( Date.now() % 2500 ) / 2500
GLSL: mod( time, 2500.0 ) / 2500.0
I would prefer to perform these calculations on the GPU, but I'm unsure of the correct approach. Can anyone provide guidance on this?
Below is a simple scene demonstrating the issue:
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 )
const renderer = new THREE.WebGLRenderer()
renderer.setSize( window.innerWidth, window.innerHeight )
camera.position.z = 0.5
document.body.appendChild( renderer.domElement )
const checkbox = document.getElementById( "toggle" )
const geo = new THREE.PlaneGeometry( 1, 1 )
const mat = new THREE.ShaderMaterial({
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`,
fragmentShader: `
uniform bool check;
uniform float time;
const float TAU = 6.2831;
void main() {
float fColor;
check
? fColor = ( sin( ( time * TAU ) ) + 1.0 ) / 2.0
: fColor = ( sin( ( ( mod( time, 2500.0 ) / 2500.0 ) * TAU ) ) + 1.0 ) / 2.0;
gl_FragColor = vec4( 1.0, fColor, 1.0, 1.0 );
}
`,
uniforms: {
"check": { value: false },
"time": { value: 1.0 },
},
})
const plane = new THREE.Mesh( geo, mat )
scene.add( plane )
const animate = function() {
requestAnimationFrame( animate )
if ( checkbox.checked ) {
plane.material.uniforms.check.value = true
plane.material.uniforms.time.value = ( Date.now() % 2500 ) / 2500
} else {
plane.material.uniforms.check.value = false
plane.material.uniforms.time.value = Date.now()
}
renderer.render( scene, camera )
}
animate()
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%;
}
#config {
position: absolute;
color: #fff;
cursor: pointer;
user-select: none;
font: bold 1em/1.5 sans-serif;
padding: 1em;
}
#config label,
#config input {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.js"></script>
<div id="config">
<input id="toggle" type="checkbox">
<label for="toggle">Use JavaScript</label>
</div>