From e0bc5aab8b0a3d827e12a4f9f46238f6972f6968 Mon Sep 17 00:00:00 2001 From: Emile Clark-Boman Date: Mon, 28 Jul 2025 12:44:46 +1000 Subject: [PATCH] webgl-demo fragment shader now has uniform uTime --- www/draw-scene.js | 8 +++++++- www/webgl-demo.js | 40 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/www/draw-scene.js b/www/draw-scene.js index f470ae4..57b212f 100644 --- a/www/draw-scene.js +++ b/www/draw-scene.js @@ -1,4 +1,4 @@ -function drawScene(gl, programInfo, buffers) { +function drawScene(gl, programInfo, buffers, time) { gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque gl.clearDepth(1.0); // Clear everything gl.enable(gl.DEPTH_TEST); // Enable depth testing @@ -56,6 +56,12 @@ function drawScene(gl, programInfo, buffers) { modelViewMatrix, ); + // Time since page loaded in seconds + gl.uniform1f( + programInfo.uniformLocations.time, + time, + ); + { const offset = 0; const vertexCount = 4; diff --git a/www/webgl-demo.js b/www/webgl-demo.js index c0cb590..5ebbe68 100644 --- a/www/webgl-demo.js +++ b/www/webgl-demo.js @@ -77,8 +77,27 @@ function main() { `; const fsSource = ` + // is highp wasteful for this shader? + #ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + #else + precision mediump float; + #endif + + // shadertoy-like parameters + // uniform vec2 uResolution; + uniform float uTime; + void main() { - gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); + vec2 uv = gl_FragCoord.xy/vec2(300, 300).xy; + + // Time varying pixel color + vec3 col = 0.5 + 0.5*cos(uTime+uv.xyx+vec3(0,2,4)); + + // Output to screen + gl_FragColor = vec4(col,1.0); + + // gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } `; @@ -95,6 +114,9 @@ function main() { uniformLocations: { projectionMatrix: gl.getUniformLocation(shaderProgram, "uProjectionMatrix"), modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"), + + // resolution: context.getUniformLocation(program, "uResolution"), + time: gl.getUniformLocation(shaderProgram, "uTime"), }, }; @@ -103,6 +125,20 @@ function main() { const buffers = initBuffers(gl); // Draw the scene - drawScene(gl, programInfo, buffers); + // drawScene(gl, programInfo, buffers, 0); + + // let timePrev = 0; + // requestAnimationFrame asks the browser to call render, + // providing the time in milliseconds since the page loaded + function render(time) { + time *= 0.001; // convert to seconds + // deltaTime = time - prevTime; + // prevTime = time; + + console.log(time) + drawScene(gl, programInfo, buffers, time); + requestAnimationFrame(render); + } + requestAnimationFrame(render); }