How to apply a texture to part of a face? - three.js

I want to apply a texture to only a specified portion of the face of a cube - not the whole face. I want to do this multiple times to the same face. For example, I want to put texture1.jpg on the top right corner of the face, texture2.jpg on the lower right corner, texture3.jpg on the upper left corner, and texture4.jpg in the middle.
I want to be able to do this without creating new meshes for each portion.
I am experiencing performance issues related to having to create a new mesh for each portion of texture, and if I could just do it by somehow placing "decals" on a single mesh, the whole thing would run smoother.

You can combine textures at custom THREE.ShaderMAterial:
<script id="cubeFragmentShader" type="x-shader/x-fragment">
uniform vec2 aMin;
uniform vec2 aMax;
varying vec2 vUv;
uniform sampler2D texture;
uniform sampler2D texture2;
void main() {
vec2 position = vUv;
if (vUv.x<aMin.x || vUv.x>aMax.x || vUv.y<aMin.y || vUv.y>aMax.y) {
gl_FragColor = texture2D( texture2, position );
} else {
position -= aMin;
position.x /= aMax.x - aMin.x;
position.y /= aMax.y - aMin.y;
gl_FragColor = texture2D( texture, position );
}
}
</script>
http://jsfiddle.net/fj2r9b55/

I drew multiple images on a canvas in different spots and then exported the canvas as a URL, which I added as a textured material to a Mesh:
var scene = new THREE.Scene();
var sceneWidth = window.innerWidth;
var sceneHeight = window.innerHeight;
var camera = new THREE.PerspectiveCamera(45, sceneWidth/sceneHeight, 0.1, 3000);
var controls = new THREE.OrbitControls(camera);
var raycaster = new THREE.Raycaster();
var renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor( 0xcccccc, 1);
renderer.setSize(sceneWidth, sceneHeight);
document.getElementById("content").appendChild(renderer.domElement);
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 900;
var ctx = canvas.getContext("2d");
var imgs = [];
imgs.push(loadImage('http://uobot.com/demo/1.jpg', main));
imgs.push(loadImage('http://uobot.com/demo/2.jpg', main));
imgs.push(loadImage('http://uobot.com/demo/3.jpg', main));
var imagesLoaded = 0;
function main() {
imagesLoaded ++;
if(imagesLoaded == imgs.length) {
for(var i in imgs) {
ctx.drawImage(imgs[i], 0, i*100);
}
var dataUrl = canvas.toDataURL();
var texture = THREE.ImageUtils.loadTexture(dataUrl);
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
var material = new THREE.MeshPhongMaterial( {
map: texture,
specular: 0x050505,
shininess: 0
});
var object = new THREE.Mesh(new THREE.PlaneGeometry(10, 60, 1, 1), material);
scene.add(object);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}

Related

three.js How to have 2 textures on one object, the second being transparent according to a grayscale png?

I need to have an object with a texture I can change the color of, and another one on top of the first one for colored details.
Here are some pictures to describe this :
The result I need : Fig1 and 2.
Fig3 is the texture of the background.
Fig4 is the alpha texture of the details.
I know how to do this with lightwave for example, it's called texture layers. But I can't figure it out in threejs.
Thank you.
You can use THREE.ShaderMaterial() to mix those textures, using .r channel for the value of mixing from the texture with the pattern:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var c1 = document.createElement("canvas");
c1.width = 128;
c1.height = 128;
var ctx1 = c1.getContext("2d");
ctx1.fillStyle = "gray";
ctx1.fillRect(0, 0, 128, 128);
var tex1 = new THREE.CanvasTexture(c1); // texture of a solid color
var c2 = document.createElement("canvas");
c2.width = 128;
c2.height = 128;
var ctx2 = c2.getContext("2d");
ctx2.fillStyle = "black";
ctx2.fillRect(0, 0, 128, 128);
ctx2.strokeStyle = "white";
ctx2.moveTo(50, -20);
ctx2.lineTo(100, 148);
ctx2.lineWidth = 20;
ctx2.stroke();
var tex2 = new THREE.CanvasTexture(c2); // texture with a pattern
var planeGeom = new THREE.PlaneBufferGeometry(10, 10);
var planeMat = new THREE.ShaderMaterial({
uniforms: {
tex1: {
value: tex1
},
tex2: {
value: tex2
},
color: {
value: new THREE.Color() //color of the pattern
}
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
}
`,
fragmentShader: `
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform vec3 color;
varying vec2 vUv;
void main() {
vec3 c1 = texture2D(tex1, vUv).rgb;
float m = texture2D(tex2, vUv).r;
vec3 col = mix(c1, color, m);
gl_FragColor = vec4(col, 1);
}
`
});
var plane = new THREE.Mesh(planeGeom, planeMat);
scene.add(plane);
var clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
let t = (clock.getElapsedTime() * 0.125) % 1;
planeMat.uniforms.color.value.setHSL(t, 1, 0.5);
renderer.render(scene, camera);
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

Turning an image into Point Cloud in Three.js

I want to turn an image into a Point Cloud and offset the z-position based on the color value. So far I have:
Loaded an image, and upon load
Built a geometry and stored image colour within the geometry
Create a PointsMaterial and build a THREE.Points
Add to scene
However, the result looks nothing like the input image. I am missing something but unsure of what.
What am I missing with regards to displaying a point cloud version of the image?
Example: https://img2pointcloud.glitch.me/
<html>
<head>
<script src="https://threejs.org/build/three.js"></script>
</head>
<body style="margin:0">
<script>
var container, renderer, points;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
10000
);
camera.position.set(0, 0, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var imgSrc =
"https://cdn.glitch.com/c3afecd9-365c-424f-a08e-90fce02a151a%2Fimg.jpeg?v=1588102020636";
var img = new Image();
var width = 1920 / 4;
var height = 1080 / 4;
img.crossOrigin = "anonymous";
img.src = imgSrc;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var imageData = ctx.getImageData(0, 0, width, height);
var data = imageData.data;
document.body.appendChild(canvas);
createPointCloud(imageData);
};
function createPointCloud(imageData) {
var geometry = new THREE.BufferGeometry();
var positions = [];
for (var x = 0; x < height; x++) {
for (var z = 0; z < width; z++) {
positions.push(x, z, x);
}
}
var color = new THREE.Color();
var colors = [];
for (let i = 0; i < imageData.data.length; i += 4) {
const r = imageData.data[i + 0];
const g = imageData.data[i + 1];
const b = imageData.data[i + 2];
const a = imageData.data[i + 3];
color.setRGB(r, g, b);
colors.push(color.r, color.b, color.c);
}
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeBoundingSphere();
var material = new THREE.PointsMaterial({
size: 0.1,
vertexColors: true
});
points = new THREE.Points(geometry, material);
scene.add(points);
animate();
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
[1]: https://i.stack.imgur.com/9etFB.png
[2]: https://i.stack.imgur.com/HKM7m.png
Another approach is to modify shaders of THREE.PointsMaterial():
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(-75, 0, 1);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
new THREE.TextureLoader().load("https://cdn.glitch.com/c3afecd9-365c-424f-a08e-90fce02a151a%2Fimg.jpeg?v=1588102020636", tex => {
let img = tex.image;
console.log(img.width, img.height);
let g = new THREE.PlaneBufferGeometry(Math.floor(img.width / 4), Math.floor(img.height / 4), img.width, img.height);
let m = new THREE.PointsMaterial({
map: tex,
size: 0.1
});
m.onBeforeCompile = shader => {
shader.vertexShader = `
varying vec2 vUv;
${shader.vertexShader}
`;
shader.vertexShader = shader.vertexShader.replace(
`#include <color_vertex>`,
`
vUv = uv;
#include <color_vertex>`
);
shader.fragmentShader = `
varying vec2 vUv;
${shader.fragmentShader}
`;
shader.fragmentShader = shader.fragmentShader.replace(
`#include <map_particle_fragment>`,
`vec4 mapTexel = texture2D( map, vUv );
diffuseColor = mapTexel;
`
);
console.log(shader.vertexShader);
};
let p = new THREE.Points(g, m);
scene.add(p);
});
renderer.setAnimationLoop(() => {
renderer.render(scene, camera)
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
There's a big typo in my code where it for some reason says colors.push(color.r, color.b, color.c); and not colors.push(color.r, color.g, color.b); (notice the rbc vs rgb).
Sorted now, thanks for the comment, made me see it.

Particles follow texture

I have a sphere created with particles in three.js that works perfectly. Now I wanted to put these particles on top of a texture that I have of a world map simulating a 3D planet, I searched the internet but I did not find any information on how to do it, when I put the texture instead of it being outside it ends up getting inside each particle, how could I do that? Any idea ? Thank you all
here is my code
$( document ).ready(function() {
var globe = document.getElementById('globe')
var Maxwidth = window.innerWidth
var Maxheight = window.innerHeight
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer({antilias:true});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(Maxwidth,Maxheight)
globe.appendChild(renderer.domElement)
var camera = new THREE.PerspectiveCamera(60, Maxwidth / Maxheight,1,1000);
camera.position.z = 50;
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.dampingFactor = 0.25;
controls.panningMode = THREE.HorizontalPanning; // default is
THREE.ScreenSpacePanning
controls.maxPolarAngle = Math.PI / 2;
var geometry = new THREE.SphereGeometry( 200, 42, 42 );
geometry.widthSegments = 42;
var colors = [];
for( var i = 0; i < geometry.vertices.length; i++ ) {
// random color
colors[i] = new THREE.Color();
//colors[i].setHSV( Math.random(), 1.0, 1.0 );
}
geometry.colors = colors;
// texture
var texture = new THREE.Texture( generateTexture( ) );
texture.needsUpdate = true; // important
// particle system material
var material = new THREE.ParticleBasicMaterial( {
size: 5,
map: texture,
blending: THREE.AdditiveBlending, // required
depthTest: false, // required
transparent: true,
opacity: 0.7,
vertexColors: true // optional
} );
material.map = THREE.ImageUtils.loadTexture('../img/point_picker.png')
material.anisotropy = 0;
material.magFilter = THREE.NearestFilter;
material.minFilter = THREE.NearestFilter;
var union = new THREE.ParticleSystem( geometry, material );
function generateTexture( ) {
var size = 128;
var canvas = document.createElement( 'canvas' );
canvas.width = size;
canvas.height = size;
var context = canvas.getContext( '2d' );
var centerX = size / 2;
var centerY = size / 2;
var radius = size / 2;
context.beginPath();
context.arc( centerX, centerY, radius, 0, 2 * Math.PI, false );
context.fillStyle = "#FFFFFF";
context.fill();
return canvas;
}
scene.add(union)
renderer.setClearColor(0x2675AD)
renderer.render(scene,camera)
controls.update();
function render(delta){
requestAnimationFrame(render);
renderer.render(scene,camera)
union.rotation.y += 0.0009
}
render()
});
I need something like this
So, this is the option I was talking about in my comment:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1.25, 7, 7);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setClearColor(0x080808);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var geom = new THREE.SphereBufferGeometry(5, 120, 60);
var colors = [];
var color = new THREE.Color();
var q = 0xffffff * 0.25;
for (let i = 0; i < geom.attributes.position.count; i++) {
color.set(Math.random() * q + q * 3);
color.toArray(colors, i * 3);
}
geom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
var loader = new THREE.TextureLoader();
loader.setCrossOrigin('');
var texture = loader.load('https://learningthreejs.com/data/2013-09-16-how-to-make-the-earth-in-webgl/demo/bower_components/threex.planets/images/earthspec1k.jpg');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);
var disk = loader.load('https://threejs.org/examples/textures/sprites/circle.png');
var points = new THREE.Points(geom, new THREE.ShaderMaterial({
vertexColors: THREE.VertexColors,
uniforms: {
visibility: {
value: texture
},
shift: {
value: 0
},
shape: {
value: disk
},
size: {
value: 0.125
},
scale: {
value: window.innerHeight / 2
}
},
vertexShader: `
uniform float scale;
uniform float size;
varying vec2 vUv;
varying vec3 vColor;
void main() {
vUv = uv;
vColor = color;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( scale / length( mvPosition.xyz ) );
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: `
uniform sampler2D visibility;
uniform float shift;
uniform sampler2D shape;
varying vec2 vUv;
varying vec3 vColor;
void main() {
vec2 uv = vUv;
uv.x += shift;
vec4 v = texture2D(visibility, uv);
if (length(v.rgb) > 1.0) discard;
gl_FragColor = vec4( vColor, 1.0 );
vec4 shapeData = texture2D( shape, gl_PointCoord );
if (shapeData.a < 0.5) discard;
gl_FragColor = gl_FragColor * shapeData;
}
`,
transparent: true
}));
scene.add(points);
var blackGlobe = new THREE.Mesh(geom, new THREE.MeshBasicMaterial({
color: 0x000000
}));
blackGlobe.scale.setScalar(0.99);
points.add(blackGlobe);
var clock = new THREE.Clock();
var time = 0;
render();
function render() {
requestAnimationFrame(render);
time += clock.getDelta();
points.material.uniforms.shift.value = time * 0.1;
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.91.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.91.0/examples/js/controls/OrbitControls.js"></script>

How to change the colors in this THREE.js demo

I just found this beautiful demo on codepen, but I don't know how to change the colors of the sphere - I mean the blue and purple colore, not the background color I know how to change that!
Here is the demo: Link to the demo
JavaScript experts please help!
This is the HTML code:
<canvas></canvas>
<script type="x-shader/x-vertex" id="wrapVertexShader">
uniform float uTime;
varying vec3 vNormal;
attribute float perlin;
varying float vPerlin;
void main()
{
vNormal = normal;
vPerlin = perlin;
vec3 position = position;
position.x *= abs(perlin)*0.1+1.0;
position.y *= abs(perlin)*0.1+1.0;
position.z *= abs(perlin)*0.1+1.0;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = 3.0;
gl_Position = projectionMatrix * mvPosition;
}
</script>
<script type="x-shader/x-fragment" id="wrapFragmentShader">
varying float vPerlin;
void main(){
vec3 outcolor = vec3(abs(vPerlin),vPerlin-1.0,1.0);
gl_FragColor = vec4(outcolor, 1.0);
}
</script>
And this is the JS code:
var ww = window.innerWidth,
wh = window.innerHeight,
imgData;
var renderer = new THREE.WebGLRenderer({
canvas: document.querySelector("canvas")
});
renderer.setClearColor(0xffffff);
renderer.setSize(ww, wh);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, ww / wh, 1, 10000);
camera.position.set(0, 0, 300);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var geom = new THREE.SphereBufferGeometry(100,60, 60);
var mat = new THREE.MeshBasicMaterial({color:0xff0000});
var length = geom.attributes.position.count;
var perlins = new Float32Array(length);
geom.addAttribute('perlin', new THREE.BufferAttribute(perlins, 1));
var wrapMatShader = new THREE.ShaderMaterial({
uniforms: {
uTime: { type: "f", value: 1.0 },
},
vertexShader: document.getElementById("wrapVertexShader").textContent,
fragmentShader: document.getElementById("wrapFragmentShader").textContent
});
var sphere = new THREE.Mesh(geom, wrapMatShader);
scene.add(sphere);
// ========
//RENDER
// ========
function render(a) {
requestAnimationFrame(render);
var perlins = new Float32Array(length);
for(var i=0;i<length;i++){
var x = geom.attributes.position.array[i*3];
var y = geom.attributes.position.array[i*3+1];
var z = geom.attributes.position.array[i*3+2];
var random = noise.simplex3((x+a*0.02)*0.01, (y+a*0.02)*0.01, (z+a*0.02)*0.01);
perlins[i] = random;
}
geom.addAttribute('perlin', new THREE.BufferAttribute(perlins, 1));
wrapMatShader.uniforms.uTime.value = a;
renderer.render(scene, camera);
}
requestAnimationFrame(render);
This is the line that sets the color-value:
vec3 outcolor = vec3(abs(vPerlin), vPerlin - 1.0, 1.0);
So there is the parameter vPerlin that controls both the red and green-values of the color. The blue-component is fixed to 1.0. Go ahead and play with these values a bit.
Now, that perlin-value is coming from the vertex-shader which in turn receives the values from this piece of javascript:
var perlins = new Float32Array(length);
for(var i=0;i<length;i++){
var x = geom.attributes.position.array[i*3];
var y = geom.attributes.position.array[i*3+1];
var z = geom.attributes.position.array[i*3+2];
var random = noise.simplex3((x+a*0.02)*0.01, (y+a*0.02)*0.01, (z+a*0.02)*0.01);
perlins[i] = random;
}
geom.addAttribute('perlin', new THREE.BufferAttribute(perlins, 1));
It's a bit more complicated than that, and involves how teh vertex- and fragment-shaders work together. You might want to read this if you're curious what is going on there: https://webglfundamentals.org/webgl/lessons/webgl-shaders-and-glsl.html

Display wireframe and solid color

Is it possible to display the wireframe of the object and also the solid color of its faces on the same object? I found a way using a clone of the object and assign different materials e.g
var geometry = new THREE.PlaneGeometry(plane.width, plane.height,width - 1, height - 1);
var materialWireframe = new THREE.MeshPhongMaterial({color:"red",wireframe:true});
var materialSolid = new THREE.MeshPhongMaterial({color:"green",wireframe:false});
var plane = new THREE.Mesh(geometry, materialWireframe );
var plane1 = plane.clone();
plane1.material = materialSolid ;
plane1.material.needsUpdate = true;
any thoughts?
To render both a model and its wireframe, you can use a pattern like this one:
// mesh
var material = new THREE.MeshPhongMaterial( {
color: 0xff0000,
polygonOffset: true,
polygonOffsetFactor: 1, // positive value pushes polygon further away
polygonOffsetUnits: 1
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh )
// wireframe
var geo = new THREE.EdgesGeometry( mesh.geometry ); // or WireframeGeometry
var mat = new THREE.LineBasicMaterial( { color: 0xffffff } );
var wireframe = new THREE.LineSegments( geo, mat );
mesh.add( wireframe );
The use of polygonOffset will help prevent z-fighting between the mesh material and the wireframe line. Consequently, the wireframe will look a lot better.
three.js r.126
This can also be achieved with WireframeGeometry:
https://threejs.org/docs/#api/en/geometries/WireframeGeometry.
(and give plane and line the same position, you can also play with opacity see the docs).
let geometryWithFillAndWireFrame = () => {
let geometry = new THREE.PlaneGeometry(250, 250, 10, 10);
let material = new THREE.MeshBasicMaterial( { color: 0xd3d3d3} );
let plane = new THREE.Mesh(geometry, material);
scene.add(plane);
let wireframe = new THREE.WireframeGeometry( geometry );
let line = new THREE.LineSegments( wireframe );
line.material.color.setHex(0x000000);
scene.add(line);
};
To do that, a possibility is to use a GLSL fragment shader that changes the fragment color when the fragment is near one edge of the triangle. Here is the GLSL shader that I am using. As input, it takes the barycentric coordinates of the fragment in the triangle, and an edge mask that selects for each edge whether it should be drawn or not. (rem: I had to use it with the compatibility profile for backward compatibility reasons, if you do not want to do that, it can easily be adapted):
(fragment source)
#version 150 compatibility
flat in float diffuse;
flat in float specular;
flat in vec3 edge_mask;
in vec2 bary;
uniform float mesh_width = 1.0;
uniform vec3 mesh_color = vec3(0.0, 0.0, 0.0);
uniform bool lighting = true;
out vec4 frag_color;
float edge_factor(){
vec3 bary3 = vec3(bary.x, bary.y, 1.0-bary.x-bary.y);
vec3 d = fwidth(bary3);
vec3 a3 = smoothstep(vec3(0.0,0.0,0.0), d*mesh_width, bary3);
a3 = vec3(1.0, 1.0, 1.0) - edge_mask + edge_mask*a3;
return min(min(a3.x, a3.y), a3.z);
}
void main() {
float s = (lighting && gl_FrontFacing) ? 1.0 : -1.0;
vec4 Kdiff = gl_FrontFacing ?
gl_FrontMaterial.diffuse : gl_BackMaterial.diffuse;
float sdiffuse = s * diffuse;
vec4 result = vec4(0.1, 0.1, 0.1, 1.0);
if(sdiffuse > 0.0) {
result += sdiffuse*Kdiff +
specular*gl_FrontMaterial.specular;
}
frag_color = (mesh_width != 0.0) ?
mix(vec4(mesh_color,1.0),result,edge_factor()) :
result;
}
To avoid cloning my object I used a pattern like that :
var mat_wireframe = new THREE.MeshBasicMaterial({color: 0x000000, wireframe: true});
var mat_lambert = new THREE.MeshLambertMaterial({color: 0xffffff, shading: THREE.FlatShading});
var meshmaterials = [ mat_wireframe, mat_lambert ];
and then applied it to my mesh like that :
var myMesh = THREE.SceneUtils.createMultiMaterialObject( mesh_geometry, meshmaterials );
scene.add( myMesh ) ;
I hope it could help...

Resources