In my three.js project I try to change the color texture by clicking on an image.
Here goes my code:
...
var col;
document.getElementById('image3').onclick = function() {
col=("textures/synleder/synleder_COL.png");
};
var textures = {
color: THREE.ImageUtils.loadTexture(col),
normal: THREE.ImageUtils.loadTexture('textures/synleder/synleder_NRM.jpg'),
specular: THREE.ImageUtils.loadTexture('textures/synleder/synleder_SPEC.jpg'),
};
textures.color.wrapS = textures.color.wrapT = THREE.RepeatWrapping;
textures.color.repeat.set( 2, 2);
textures.normal.wrapS = textures.normal.wrapT = THREE.RepeatWrapping;
textures.normal.repeat.set( 2, 2);
textures.specular.wrapS = textures.specular.wrapT = THREE.RepeatWrapping;
textures.specular.repeat.set( 2, 2);
var shader = THREE.ShaderLib[ "normalmap" ];
var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
uniforms[ "tNormal" ].value = textures.normal;
uniforms[ "uNormalScale" ].value.y = 2;
var material2 = new THREE.MeshPhongMaterial( {
map: textures.color,
specularMap: textures.specular,
normalMap: uniforms[ "tNormal" ].value,
normalScale: uniforms[ "uNormalScale" ].value,
} );
loader = new THREE.JSONLoader( true );
document.body.appendChild( loader.statusDomElement );
loader.load( "geo/kugel5.js", function( geometry ) { createScene( geometry, scale, material2 ) } );
...
what I tried until now is that I defined a variable col which should contain the path of my color textures. And by clicking on image3 the new color texture should be visible on my geometry. Unfortunately it doesn´t work.
After some research I found this thread: Three.js texture / image update at runtime
and I think I have to add something to update the texture: textures.color.needsUpdate=true;
But when I add this to my code like:
document.getElementById('image3').onclick = function() {
col=("textures/synleder/synleder_COL.png");
textures.color.needsUpdate=true;
};
my geometry disappears. Does anyone have a clue what I did wrong?
Many thanks!
document.getElementById('image3').onclick = function() {
textures.color = THREE.ImageUtils.loadTexture("textures/synleder/synleder_COL.png",function(){
material2.color = textures.color;
textures.color.wrapS = textures.color.wrapT = THREE.RepeatWrapping;
textures.color.repeat.set( 2, 2);
textures.color.needsUpdate=true;
});
};
This should do it
Related
I have 3D models as such:
I want to add a cast shadow similar to this:
And I have the following piece of code responsible for the model:
var ambLight = new THREE.AmbientLight( 0x404040 );
this.scene.add(ambLight)
var loader = new THREE.GLTFLoader();
loader.load(path,function (gltf) {
gltf.scene.traverse( function( model ) {
if (model.isMesh){
model.castShadow = true;
}
});
this.scene.add(gltf.scene);
}
I added the castSHadow part as seen in this StackOverflow post.
I've tried model.castShadow = true and I've tried removing the if condition and just leave the castShadow but that doesn't work either. Am I missing a step? The full custom layer code is here if it helps.
You only have an instance of AmbientLight in your scene which is no shadow-casting light.
3D objects can only receive shadow if they set Object3D.receiveShadow to true and if the material is not unlit. Meaning MeshBasicMaterial would not work as the ground's material.
You have to globally enable shadows via: renderer.shadowMap.enabled = true;
I suggest you have a closer look to the shadow setup of this official example.
Based on your code, you're trying to add a shadow on top of Mapbox.
For that, apart from the suggestions from #Mugen87, you'll need to create a surface to receive the shadow, and place it exactly below the model you're loading, considering also the size of the object you're loading to avoid the shadow goes out of the plane surface... and then you'll get this.
Relevant code in this fiddle I have created. I slightly changed the light and I added a light helper for clarity.
var customLayer = {
id: '3d-model',
type: 'custom',
renderingMode: '3d',
onAdd: function(map, gl) {
this.camera = new THREE.Camera();
this.scene = new THREE.Scene();
const dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.position.set(0, 70, 100);
let d = 1000;
let r = 2;
let mapSize = 8192;
dirLight.castShadow = true;
dirLight.shadow.radius = r;
dirLight.shadow.mapSize.width = mapSize;
dirLight.shadow.mapSize.height = mapSize;
dirLight.shadow.camera.top = dirLight.shadow.camera.right = d;
dirLight.shadow.camera.bottom = dirLight.shadow.camera.left = -d;
dirLight.shadow.camera.near = 1;
dirLight.shadow.camera.far = 400000000;
//dirLight.shadow.camera.visible = true;
this.scene.add(dirLight);
this.scene.add(new THREE.DirectionalLightHelper(dirLight, 10));
// use the three.js GLTF loader to add the 3D model to the three.js scene
var loader = new THREE.GLTFLoader();
loader.load(
'https://docs.mapbox.com/mapbox-gl-js/assets/34M_17/34M_17.gltf',
function(gltf) {
gltf.scene.traverse(function(model) {
if (model.isMesh) {
model.castShadow = true;
}
});
this.scene.add(gltf.scene);
// we add the shadow plane automatically
const s = new THREE.Box3().setFromObject(gltf.scene).getSize(new THREE.Vector3(0, 0, 0));
const sizes = [s.x, s.y, s.z];
const planeSize = Math.max(...sizes) * 10;
const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
const planeMat = new THREE.ShadowMaterial();
planeMat.opacity = 0.5;
let plane = new THREE.Mesh(planeGeo, planeMat);
plane.rotateX(-Math.PI / 2);
plane.receiveShadow = true;
this.scene.add(plane);
}.bind(this)
);
this.map = map;
// use the Mapbox GL JS map canvas for three.js
this.renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true
});
this.renderer.autoClear = false;
this.renderer.shadowMap.enabled = true;
},
render: function(gl, matrix) {
var rotationX = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(1, 0, 0),
modelTransform.rotateX
);
var rotationY = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 1, 0),
modelTransform.rotateY
);
var rotationZ = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 0, 1),
modelTransform.rotateZ
);
var m = new THREE.Matrix4().fromArray(matrix);
var l = new THREE.Matrix4()
.makeTranslation(
modelTransform.translateX,
modelTransform.translateY,
modelTransform.translateZ
)
.scale(
new THREE.Vector3(
modelTransform.scale,
-modelTransform.scale,
modelTransform.scale
)
)
.multiply(rotationX)
.multiply(rotationY)
.multiply(rotationZ);
this.camera.projectionMatrix = m.multiply(l);
this.renderer.state.reset();
this.renderer.render(this.scene, this.camera);
this.map.triggerRepaint();
}
};
attempting to apply a bump map to an object loaded, but no change is seen on the material
var loader = new THREE.ObjectLoader();
loader.load("../js/brain2.json", function(object) {
var mapHeight = new THREE.TextureLoader().load( "../js/texture.jpg" );
var material = new THREE.MeshPhongMaterial( { color: 0x888888, specular: 0xEEEEEE, shininess: 5} );
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = material;
child.material.bumpMap = mapHeight;
child.material.bumpScale = 1;
var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
geometry.computeFaceNormals();
geometry.mergeVertices();
geometry.computeVertexNormals();
child.geometry = new THREE.BufferGeometry().fromGeometry( geometry );
var modifier = new THREE.BufferSubdivisionModifier(1);
modifier.modify(geometry);
child.material.overdraw = 1
};
});
object.scale.set(15, 15, 15);
object.position.x = 1;
object.position.y = 1;
object.position.z = 1;
object.rotation.set( 5, 1, 1 );
scene.add( object );
});
I've already fixed earlier issues with this code, including applying a subdivision modifier to it, but now it appears the bump map refuses to be applied.
I'm trying to make a realistic silver ring like this:
with different colors and size.
This is my result at this moment:
As you can see my ring is not smooth.
I don't know if it's a problem of the model, or of the code:
There are my models ( i'm using 2 model, one for the light silver and another for the dark one )
light: http://www.websuvius.it/atma/myring/assets/3d/anello-1/interno.obj
dark: http://www.websuvius.it/atma/myring/assets/3d/anello-1/esterno.obj
This is part of my code:
...
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45, containerWidth / containerHeight, 0.1, 20000 );
scene.add(camera);
camera.position.set( 0, 150, 400 );
camera.lookAt(scene.position);
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( containerWidth, containerHeight );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableZoom = false;
var ambientlight = new THREE.AmbientLight( 0xffffff );
scene.add( ambientlight );
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {};
var onProgress = function ( xhr ) {};
var onError = function ( xhr ) {};
var loader = new THREE.OBJLoader( manager );
var textureLoader = new THREE.TextureLoader( manager );
loader.load( path + '/assets/3d/anello-1/interno.obj', function ( object ) {
var backgroundTexture = textureLoader.load( path + '/assets/3d/texture/argento_standard_512_1024.jpg');
backgroundTexture.flipY = false;
var background = new THREE.MeshPhongMaterial({
map: backgroundTexture,
envMap: textureCube,
reflectivity:0.5
});
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = background;
}
});
object.position.y =-50;
scene.add(object);
}, onProgress, onError );
loader.load( path + '/assets/3d/anello-1/esterno.obj', function ( object ) {
var geometry = object.children[ 0 ].geometry;
var materials = [];
var scavoTexture = textureLoader.load( path + '/assets/3d/texture/argento_scuro_512_1024.jpg');
var material = new THREE.MeshPhongMaterial({
map: scavoTexture,
envMap: textureCube,
reflectivity:0.5
});
materials.push(material);
var customTexture = textureLoader.load( path + "/" + immagine);
customTexture.flipY = false;
var custom = new THREE.MeshPhongMaterial({
map: customTexture,
transparent: true,
opacity: 1,
color: 0xffffff
});
materials.push(custom);
esterno = THREE.SceneUtils.createMultiMaterialObject(geometry, materials);
esterno.position.y=-50;
scene.add(esterno);
}, onProgress, onError );
container = document.getElementById( 'preview3d' );
container.appendChild( renderer.domElement );
animate();
How can i get a better result?
I have to change my models? My code? Both?
Thanks
[EDIT]
Thanks, everyone for the comments.
This is the result now:
Now, i have another question. Is there a way to extrude the text and other elements? I have only a png element of the central part.
Thanks
[EDIT 2]
Now I'm making some experiment with displacementMap.
This is the result at this moment:
Now the problem is: the browser freeze due to heavily subdivided mesh.
This is a part of my code:
var external = new THREE.CylinderBufferGeometry( 3.48, 3.48, 4, 800, 400, true, -1.19, 5.54 );
var materials = [];
var baseMaterial = new THREE.MeshPhongMaterial({
color: 0x222222
});
materials.push(baseMaterial);
var textureMaterial = new THREE.MeshPhongMaterial({
map: image, //PNG with text and symbols
transparent: true,
opacity: 1,
reflectivity:0.5,
color: 0xc0c0c0,
emissive: 0x111111,
specular: 0xffffff,
shininess: 34,
displacementMap: image, //same as map
displacementScale: 0.15,
displacementBias: 0
});
materials.push(textureMaterial);
var externalObj = THREE.SceneUtils.createMultiMaterialObject(external, materials);
I think that the problem is the 800x400 segments of cylinder, that generate a mesh with 320000 "faces". There is a way to optimize the performance keeping this level of detail?
Thanks again.
P.s. maybe I have to open a new question?
Answering your new question: you could use your png also as displacement map. Have a look at the official example: https://threejs.org/examples/webgl_materials_displacementmap.html
But you probably need to heavily subdivide your "central part" for displacement.
Maybe in your case there will be your png as bump map sufficient enough, then you you might check out this example: https://threejs.org/examples/webgl_materials_bumpmap.html
My goal is to create a cube/box with a single texture but different repeat values for each of the sides. Working code is below:
var cubeMaker = function(w,h,d, tName)
{
var g = new THREE.CubeGeometry( 50*w, 50*h, 50*d );
var tx = THREE.ImageUtils.loadTexture( tName );
var ty = THREE.ImageUtils.loadTexture( tName );
var tz = THREE.ImageUtils.loadTexture( tName );
tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
ty.wrapS = ty.wrapT = THREE.RepeatWrapping;
tz.wrapS = tz.wrapT = THREE.RepeatWrapping;
tx.repeat.set(d,h);
ty.repeat.set(w,d);
tz.repeat.set(w,h);
var mx = new THREE.MeshBasicMaterial( {map: tx} );
var my = new THREE.MeshBasicMaterial( {map: ty} );
var mz = new THREE.MeshBasicMaterial( {map: tz} );
var mArray = [mx,mx,my,my,mz,mz];
var m6 = new THREE.MeshFaceMaterial( mArray );
var cube = new THREE.Mesh(g, m6);
return cube;
}
However, it seems wasteful to load the texture three times. Earlier, I instead tried passing a texture as an argument to the function (instead of a string representing the filename), as follows:
var cubeMaker = function(w,h,d, texture)
{
...
var tx = texture.clone();
var ty = texture.clone();
var tz = texture.clone();
...
but then the textures didn't appear in the scene, only solid black images appeared in their place. My best guess is that the texture image hadn't finished loading before the clone methods were called, and perhaps some kind of null value was copied instead. Is there some way to use an onLoad method to wait long enough so that the clone function works as intended?
Note: I have tried the suggestion from Can't clone() Texture but it does not solve my issue.
Thanks for any assistance!
Load your texture once, and move the rest of your code into the loader callback function. You also have to set the needsUpdate flag to true when you clone your texture.
var tx = THREE.ImageUtils.loadTexture( tName, undefined, function() {
var ty = tx.clone();
ty.needsUpdate = true; // important!
var tz = tx.clone();
tz.needsUpdate = true; // important!
tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
ty.wrapS = ty.wrapT = THREE.RepeatWrapping;
tz.wrapS = tz.wrapT = THREE.RepeatWrapping;
tx.repeat.set( 1, 1 );
ty.repeat.set( 2, 1 );
tz.repeat.set( 2, 2 );
var mx = new THREE.MeshBasicMaterial( { map: tx } );
var my = new THREE.MeshBasicMaterial( { map: ty } );
var mz = new THREE.MeshBasicMaterial( { map: tz } );
var mArray = [ mx, mx, my, my, mz, mz ];
var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( mArray ) );
scene.add( mesh );
} );
Why don't you create then your texture outside of your function and just use this texture inside of your function, assigning it to special variable for each side? That way for sure you are going to load it just once.
I have some strange behaviour with bounding box in three.js.
I use STLLoader and for some models everything works fine, but for some of them box is shifted.
For example:
http://oi37.tinypic.com/35a1y4l.jpg
and
http://oi34.tinypic.com/4hf4tl.jpg
Bounding box has right size and it's position is (0,0,0). The same position has loaded STL model.
And here is my code:
function stlLoader() {
var redPhongMaterial = new THREE.MeshPhongMaterial({ color: 0xFFEA32, side: THREE.DoubleSide, ambient:0x000000}); // yellow
var stlLoader = new THREE.STLLoader();
stlLoader.addEventListener('load', function (event) {
var stlGeometry = event.content;
var mesh = new THREE.Mesh(stlGeometry, redPhongMaterial);
mesh.scale.set(2, 2, 2);
mesh.castShadow = true;
mesh.receiveShadow = true;
stlGeometry.computeBoundingBox();
var boundingBox = mesh.geometry.boundingBox.clone();
drawBoundingBox(boundingBox, mesh.scale.x, mesh.scale.y, mesh.scale.z);
mesh.position.y = 0;
mesh.position.x = 0;
mesh.position.z = 0;
scene.add( mesh );
loadComplete();
} );
stlLoader.load( ptsfilestoload );
}
function drawBoundingBox(box, scaleX, scaleY, scaleZ)
{
var length = scaleX * (box.max.x - box.min.x);
var height = scaleY * (box.max.y - box.min.y);
var depth = scaleZ * (box.max.z - box.min.z);
var boundingBoxGeometry = new THREE.CubeGeometry( length, height, depth );
for ( var i = 0; i < boundingBoxGeometry.faces.length; i ++ )
{
boundingBoxGeometry.faces[i].color.setHex( Math.random() * 0xffffff );
}
var boundingBoxMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, transparent: true, opacity: 0.7 } );
var boundingBoxMesh = new THREE.Mesh( boundingBoxGeometry, boundingBoxMaterial);
scene.add( boundingBoxMesh );
}
Or maybe this is problem with STLLoader? I'm really new to webgl and three.js so any help appreciated
In your drawBoundingBox routine you need
var bboxCenter = box.center ();
boundingBoxMesh .translateX (bboxCenter.x);
boundingBoxMesh .translateY (bboxCenter.y);
boundingBoxMesh .translateZ (bboxCenter.z);
just before you add the mesh to the scene. Your Cube is created around 0,0,0.