Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three js - Cloning a shader and changing uniform values

I'm working on creating a shader to generate terrain with shadows.

My starting point is to clone the lambert shader and use a ShaderMaterial to eventually customise it with my own script.

The standard method works well:

var material = new MeshLambertMaterial({map:THREE.ImageUtils.loadTexture('images/texture.jpg')});

var mesh = new THREE.Mesh(geometry, material);

etc

The result: Result with standard lambert material

However I'd like to use the lambert material as a base and work on top of it, so I tried this:

var lambertShader = THREE.ShaderLib['lambert'];
var uniforms = THREE.UniformsUtils.clone(lambertShader.uniforms);

var texture = THREE.ImageUtils.loadTexture('images/texture.jpg');
uniforms['map'].texture = texture;

var material = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: lambertShader.vertexShader,
    fragmentShader: lambertShader.fragmentShader,
    lights:true,
    fog: true
});

var mesh = new THREE.Mesh(geometry, material);

The result for this one: Result for cloning lambert shader and changing map uniforms

It looks as if the shader is not taking into account the new texture I have added, however looking at the inspector when I logged the uniforms, the map object has the correct values.

I'm pretty new to three so I might be doing something fundamentally wrong, if someone could point me in the right direction here, that would be great.

I can also put up demo links if that would be helpful?

Thanks, Will

EDIT:

Here are some demo links.

Demo with shader material: http://dev.thinkjam.com/experiments/threejs/terrain/terrain-shader-material.html

Demo with working lambert material: http://dev.thinkjam.com/experiments/threejs/terrain/terrain-lambert-material.html

like image 218
WillDonohoe Avatar asked Aug 23 '12 12:08

WillDonohoe


1 Answers

The reason this doesn't work is the default Three.js lambert shader uses the preprocessor macro directive #ifdef to determine whether to use maps, envmaps, lightmaps, etc etc.

The Three.js WebGLRenderer sets the appropriate preprocessor directives (#define) to enable these pieces of the shaders based on whether certain properties exist on the material object.

If you're set on taking the approach of cloning & modifying the default shaders, you will have to set relevant properties on the material. For texture maps, the Three.js WebGLRenderer.js has this line:

parameters.map ? "#define USE_MAP" : ""

So try setting material.map = true; for your shader material.

Of course, if you know you're going to be writing your own shader and you don't need the dynamic inclusion of various shader snippets, you can just write the shader explicitly and you won't need to worry about this.

like image 68
fuzic Avatar answered Oct 19 '22 18:10

fuzic