Can someone help me with loading shaders from an external file in Three.js? The shader works fine when placed within a <script>
tag, but I'm encountering issues when trying to load it externally. Here's what I'm doing:
var loader = new THREE.FileLoader();
loader.load('shader.vert',function ( data ) {vShader = data;},);
loader.load('shader.frag',function ( data ) {fShader = data;},);
Later on, I use the shaders like this:
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vShader,
fragmentShader: fShader,
});
The problem arises when I reload the page and get errors stating that the shaders are not defined. Strangely, when I check vShader in the console, it displays the correct value. However, during debugging (with a breakpoint inside the init() function), vShader is shown as undefined.
Could someone please explain my mistake?
Here is the snippet of the entire code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://threejs.org/build/three.min.js"></script>
</head>
<body>
<div class="WebGL-output" id="WebGL-output"></div>
<script id="vertexShader" type="x-shader/x-vertex" src="shader.vert">
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
uniform vec3 color;
varying vec2 vUv;
void main() {
gl_FragColor = vec4(color,1.);
}
</script>
<script>
var renderer,uniforms,vShader,fShader,camera,scene;
var loader = new THREE.FileLoader();
init();
animate();
function init(){
renderer = new THREE.WebGLRenderer
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('WebGL-output').appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 5000;
scene = new THREE.Scene();
//******* DO NOT WORK
loader.load('plaid.frag',function ( data ) {fShader = data;},);
loader.load('plaid.vert',function ( data ) {vShader = data;},);
// ****** WORK
//fShader = document.getElementById('fragmentShader').text;
//vShader = document.getElementById('vertexShader').text;
// **************************
uniforms = {
"color" : {
type : "c",
//value :new THREE.Color(0xf0f0f0)
value :new THREE.Color(0x00ff00)
},
};
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vShader,
fragmentShader: fShader,
});
// Create circles and add to scene.
var geometry = new THREE.CircleGeometry(100, 50);
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
var light = new THREE.AmbientLight(0x000000); // soft white light
scene.add(light);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
</script>
</body>
</html>