Andres Andres - 9 months ago 90
Javascript Question

Three.js UV mapping for bump map

I have a

.obj
model with the corresponding
.mtl
file loaded in my scene. I'm applying a
bumpMap
to it after being loaded:

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath('/models/');
mtlLoader.load('model.mtl', function (materials) {
materials.preload();

// Load obj file
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('/models/');
objLoader.load('model.obj', function (group) {

var geometry = group.children[0].geometry;
geometry.center();

model = new THREE.Mesh(geometry, otherMesh.material.clone());
model.material.bumpMap = new THREE.ImageUtils.loadTexture('images/bump.png');
model.name = "obj model";
scene.add(model);

render();
callback();
});
});


This works as expected. The
map
texture is just a black and white
.png
image. But if I apply the
bumpMap
not just before adding the model it's not applied. For example, with this code the
bumpMap
is not applied to the model:

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath('/models/');
mtlLoader.load('model.mtl', function (materials) {
materials.preload();

// Load obj file
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('/models/');
objLoader.load('model.obj', function (group) {

var geometry = group.children[0].geometry;
geometry.center();

model = new THREE.Mesh(geometry, otherMesh.material.clone());
setTimeout(function(){
model.material.bumpMap = new THREE.ImageUtils.loadTexture('images/bump.png');
}, 0);

model.name = "obj model";
scene.add(model);

render();
callback();
});
});


Just adding a timeout and the
bumpMap
is not applied anymore. Adding
model.bumpMap.needsUpdate = true;
after applying the
bumpMap
doesn't change anything.

Answer Source

After you have rendered a material at least once, adding a texture that was not previously present requires the building of a new shader program. To force that, you need to set

mesh.material.needsUpdate = true;

See the three.js documentation How to Update Things.

three.js r.84