Material with texture for CSG object

Hey there!
I’m new to three.js and I’m trying to union some BoxGeometries into a single object. For union I use CSG (threeCSG.js). My problem is I can’t use material with texture like a single object. Texture scale is different for each previous object, but I need to use the resulting object as one.


Please help me to fix it UVs.

var texture = new THREE.Texture( image );
image.addEventListener( 'load', function ( event ) { 
texture.needsUpdate = true; 
texture.shading = THREE.FlatShading;
} );

var sideMaterial = new THREE.MeshPhongMaterial({shininess: 0, color: ‘#aaaaaa’, wireframe: true});
var frontMaterial = new THREE.MeshPhongMaterial({shininess: 0, color: ‘#ff0000’});
var backMaterial = new THREE.MeshPhongMaterial({shininess: 0, color: ‘#00ff00’, wireframe: true});

var material = new THREE.MeshPhongMaterial( {
color: 0xffffff,
specular: 0x050505,
shininess: 0,
map: texture
} );

var left = new THREE.BoxGeometry( 50,50,10,0,0,0 );
var left_bsp = new ThreeBSP(left);

var cylinder = new THREE.BoxGeometry (10,50,10,5);
cylinder.translate (30,0,0);
var cylinder_bsp = new ThreeBSP(cylinder);

var total = left_bsp.union(cylinder_bsp);

var result = total.toMesh();

var r2= new THREE.Mesh (result.geometry,[sideMaterial,material]);

scene.add( r2 );

result.material = [sideMaterial,material];

for (var face of result.geometry.faces) {
    if (face.normal.y >  0) 
    {
        face.materialIndex = 1;
    }
}

You can check my fiddle:
http://jsfiddle.net/dvisik/ekspmb1h/1/

I’ve hacked something together based on BufferGeometry right here: http://jsfiddle.net/Lnuqmthr/

Since your final geometry is an (axis-aligned) box, it’s possible to compute the AABB of the geometry and use it to recompute the texture coordinates. For this, you have to know which vertices lies on which side of the box. You can figure this out by computing the face normal. With this information, it’s now possible to derive uvs in the range of [0,1].

Note that this approach only works since you have an axis-aligned box.

Thank you so much!
I need to understand this. But I have one more question, what if my object is not a axis-aligned box? I mean any extruded shape