Three js - Cloning a shader and changing uniform values

守給你的承諾、 提交于 2019-12-04 17:59:31

问题


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:

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:

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


回答1:


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.



来源:https://stackoverflow.com/questions/12091795/three-js-cloning-a-shader-and-changing-uniform-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!