Merging geometries in three.js - javascript

I have a scene which contains multiple meshes, each of varying shapes and sizes.
I have looped through each Mesh and using geometry.merge() I have been able to create a new mesh from the geometries in the scene.
I want to mask the entire mesh with an alphaMask, however, each geometry has the material applied to it separately.
An example of this can be seen here - https://codepen.io/danlong/pen/KXOObr
function addObjects(scene) {
// merged geomoetry & material
var mergedGeometry = new THREE.Geometry();
var mergedMaterial = new THREE.MeshStandardMaterial({ color: "#444", transparent: true, side: THREE.DoubleSide, alphaTest: 0.5, opacity: 1, roughness: 1 });
// multiple meshes
var geometry = new THREE.IcosahedronGeometry(30, 5);
var material = new THREE.MeshStandardMaterial({ color: "#444" });
var geo1 = new THREE.IcosahedronGeometry(30, 5);
var mesh1 = new THREE.Mesh( geo1, material );
mesh1.position.x = 10;
mesh1.position.y = 10;
mesh1.position.z = 0;
var geo2 = new THREE.IcosahedronGeometry(30, 5);
var mesh2 = new THREE.Mesh( geo2, material );
mesh2.position.x = 20;
mesh2.position.y = 20;
mesh2.position.z = 0;
var geo3 = new THREE.IcosahedronGeometry(30, 5);
var mesh3 = new THREE.Mesh( geo3, material );
mesh3.position.x = 30;
mesh3.position.y = 30;
mesh3.position.z = 0;
// scene.add(mesh1, mesh2, mesh3);
mesh1.updateMatrix();
mergedGeometry.merge(mesh1.geometry, mesh1.matrix);
mesh2.updateMatrix();
mergedGeometry.merge(mesh2.geometry, mesh2.matrix);
mesh3.updateMatrix();
mergedGeometry.merge(mesh3.geometry, mesh3.matrix);
// alpha texture
var image = document.createElement('img');
var alphaMap = new THREE.Texture(image);
image.onload = function() {
alphaMap.needsUpdate = true;
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGUlEQVQoU2NkYGD4z4AHMP7//x+/gmFhAgCXphP14bko/wAAAABJRU5ErkJggg==';
mergedMaterial.alphaMap = alphaMap;
mergedMaterial.alphaMap.magFilter = THREE.NearestFilter;
mergedMaterial.alphaMap.wrapT = THREE.RepeatWrapping;
mergedMaterial.alphaMap.repeat.y = 1;
// merged geometry with alpha mask
merge1 = new THREE.Mesh(mergedGeometry, mergedMaterial);
merge1.rotation.z = -Math.PI/4;
// merge geometry without alpha mask
var merge2 = new THREE.Mesh(mergedGeometry, material);
merge2.position.x = -100;
merge2.rotation.z = -Math.PI/4;
scene.add(merge1, merge2);
return mesh;
}
The mesh on the left is the merged geometries which I want to apply the alphaMask to. The mesh on the right is the outcome of this and instead of the map being applied to the mesh as a whole, each of the geometries has the map applied.
Is there a way to mask the entire mesh and not each geometry?
--
three.js r86
EDIT:
I've tried to apply a clipping plane to my mesh but it's not the effect I'm looking for. I want to be able to apply an alphaMask across the whole mesh and reveal it however I make my mask image. Something like this effect - https://codepen.io/supah/pen/zwJxdb
Is it something to do with the UV's being preserved from the original geometries? Do I need to change these in some way?

I think what you really want is an overlaid mask. This can be accomplished by rendering a single plane that has the alpha map applied, on top of the scene rendering. Using an orthographic camera, and controlling certain renderer settings, such as disabling automatic clearing of color.

Related

How to color a shape in Babylon.js?

Working off the "Basic Scene" example on babylonjs-playground.com here, I am trying to do a simple modification on the color of the sphere.
Here is my attempt, which can be run interactively:
https://www.babylonjs-playground.com/#95BNBS
Here is the code:
var createScene = function () {
// The original example, without comments:
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
camera.setTarget(BABYLON.Vector3.Zero());
camera.attachControl(canvas, true);
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
sphere.position.y = 1;
var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
// My attempt to color the sphere
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(1,0,0);
scene.material = material;
return scene;
};
My attempt to add the colored material to the sphere has no effect.
I also tried to look for color-related attributes on the sphere object:
Object.keys(sphere).filter((key) => return key.includes("Color") )
// => "outlineColor", "overlayColor", "_useVertexColors", "edgesColor"
Except for _useVertexColors, all of these seem to be color objects, but changing them has no effect:
sphere.overlayColor.g = 1;
sphere.outlineColor.g = 1;
sphere.edgesColor.g = 1;
You're pretty close. You are setting a color correctly with diffuseColor but you aren't actually adding it specifically to your sphere.
Your sphere object is stored in sphere so what you need to do is you need to set the material you created on sphere and not on scene.
// My attempt to color the sphere
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(1.0, 0.2, 0.7);
sphere.material = material; // <--
See this tutorial

Threejs draw a path with textures

I want to draw a path in my 3D world, but the class of line is not useful. Who can help me?!
Like this image
Now I fixed my question
I want draw a path ,and fill it with texture
var SUBDIVISIONS = 20;
geometry = new THREE.Geometry();
var curve = new THREE.QuadraticBezierCurve3();
curve.v0 = new THREE.Vector3(0, 0, 110);
curve.v1 = new THREE.Vector3(0, 200, 110);
curve.v2 = new THREE.Vector3(200, 200, 110);
for (j = 0; j < SUBDIVISIONS; j++) {
geometry.vertices.push( curve.getPoint(j / SUBDIVISIONS) )
}
material = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 5 } );
line = new THREE.Line(geometry, material);
scene.add(line);
this way has two problem 1:linewidth is not support on Windows ,2: LineBasicMaterial not support texture
So i search on google find class Three.MeshLine. linewidth is Ok,but texture mapping not fine. texture code there:var loader = new THREE.TextureLoader();
loader.load( 'assets/images.png', function( texture ) {
strokeTexture = texture;
strokeTexture.wrapS = strokeTexture.wrapT = THREE.RepeatWrapping;
strokeTexture.repeat.set( 5, 1);
strokeTexture.needsUpdate = true;
init()
} );
Regardless of the setting the texture and MeshLineMaterial ,The result is not what I want result image:result image
have a look at https://github.com/spite/THREE.MeshLine - it's an implementation of mesh-based lines. Also note the references on that site, could give you some insights.
Otherwise you might want to look into creating a shape from the line. This could be done using the THREE.ShapeGeometry-class.

How to set correct direction for a decal using THREE.DecalGeometry

I am trying to understand how to add decals to a mesh using THREE.DecalGeometry
I am adding decals to the vertex on each face - face.a, I've tried using the face normal and arbitrary Vector3 to define the direction for the decal.
I cannot understand why all the decals are not being created correctly. Where am I go wrong with the direction? Is the face normal not correct?
function addObjects(){
var geometry = new THREE.BoxGeometry(200, 200, 200, 8, 8, 8);
var material = new THREE.MeshLambertMaterial({color: 0xff0000});
cube = new THREE.Mesh(geometry, material);
// addWireframeHelper(cube, 0xffffff, 1);
scene.add(cube);
THREE.ImageUtils.crossOrigin = 'Anonymous';
var texture = THREE.ImageUtils.loadTexture( 'http://i.imgur.com/RNb17q7.png' );
geometry.faces.forEach(function(face){
var index = face.a;
var vertex = geometry.vertices[index];
var direction = new THREE.Vector3(0,1,0);
addDecal(cube, vertex, direction, texture);
})
}
function addDecal(mesh, position, direction, texture){
var size = 16;
var decalGeometry = new THREE.DecalGeometry(
mesh,
position,
direction,
new THREE.Vector3(size,size,size),
new THREE.Vector3(1,1,1)
);
var decalMaterial = new THREE.MeshLambertMaterial( {
map: texture,
transparent: true,
depthTest: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -4,
});
var m = new THREE.Mesh( decalGeometry, decalMaterial );
mesh.add(m);
}
This is the hotspot 64px x 64px
This is how they are getting mapped...
Why are some decals stretched?
I have setup a JSFIDDLE
EDIT:
Using SphereBufferGeometry suggested by WestLangley, I am now happy that this solution will work for me.
Rather than using THREE.DecalGeometry, for your use case a sector of a SphereGeometry will be sufficient, and computationally less-expensive.
var geometry = new THREE.SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
three.js r.143

Is it possible to map multiple different textures to ONE face of a geometry in three.js?

Is it possible to map multiple different textures to one face of a geometry in three.js?
I don't want to create multiple faces and assign materialIndexes since the number of faces I need for the geometry changes during runtime.
Here is my last unsuccessful attempt (three.js r.71):
//get some materials
var materials = [];
materials.push(loadTextures(1));
materials.push(loadTextures(2));
materials.push(loadTextures(3));
materials.push(loadTextures(4));
var faceMaterial = new THREE.MeshFaceMaterial(materials);
//create objects
var wireframeObj = new THREE.Mesh(geometry.clone(), new THREE.MeshBasicMaterial({
wireframe: true,
color: 'red'
}));
var mainObj = new THREE.Mesh(geometry, faceMaterial);
scene.add(wireframeObj);
scene.add(mainObj);
camera.position.z = 100;
renderer.render(scene, camera);
function loadTextures(i) {
var texture = new THREE.Texture();
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(2, 2);
var image = new Image();
image.onload = function () {
texture.image = this;
texture.needsUpdate = true;
};
image.src = 'images/crate' + i + '.gif';
return new THREE.MeshBasicMaterial({ map: texture });
}
This produces the following:
while I want to see also crate2 to the right, crate3 above crate1 etc.

Creating a plane, adding a texture on both sides and rotating the object on its side

I'm trying to create a long corridor with a repeating texture. How do I add a repeating texture and rotate a object (in this case a plane) at right angles to create the corridor wall's and ceiling?
var texture, material, plane;
texture = THREE.ImageUtils.loadTexture( "../img/texture.jpg" );
texture.wrapT = THREE.RepeatWrapping; // This doesn't seem to work;
material = new THREE.MeshLambertMaterial({ map : texture });
plane = new THREE.Mesh(new THREE.PlaneGeometry(400, 3500), material);
plane.doubleSided = true;
plane.position.x = 100;
plane.rotation.z = 2; // Not sure what this number represents.
scene.add(plane);
For an example of a repeating texture, check out the source of the example at:
http://stemkoski.github.com/Three.js/Texture-Repeat.html
I recommend the following changes to your code:
var texture, material, plane;
texture = THREE.ImageUtils.loadTexture( "../img/texture.jpg" );
// assuming you want the texture to repeat in both directions:
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
// how many times to repeat in each direction; the default is (1,1),
// which is probably why your example wasn't working
texture.repeat.set( 4, 4 );
material = new THREE.MeshLambertMaterial({ map : texture });
plane = new THREE.Mesh(new THREE.PlaneGeometry(400, 3500), material);
plane.material.side = THREE.DoubleSide;
plane.position.x = 100;
// rotation.z is rotation around the z-axis, measured in radians (rather than degrees)
// Math.PI = 180 degrees, Math.PI / 2 = 90 degrees, etc.
plane.rotation.z = Math.PI / 2;
scene.add(plane);
Was searching for solution without duplicating all my geometry.
Here you go ladies and gentlemen...
var materials = [new THREE.MeshBasicMaterial({map: texture, side: THREE.FrontSide}),
new THREE.MeshBasicMaterial({map: textureBack, side: THREE.BackSide})];
var geometry = new THREE.PlaneGeometry(width, height);
for (var i = 0, len = geometry.faces.length; i < len; i++) {
var face = geometry.faces[i].clone();
face.materialIndex = 1;
geometry.faces.push(face);
geometry.faceVertexUvs[0].push(geometry.faceVertexUvs[0][i].slice(0));
}
scene.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials)));
BOOM a Two Faced Plane for ya, the loop will also work with geometries with more faces, replicating each face and applying the BackSide texture to it.
Enjoy!
I was looking for the same thing and you've just used the property THREE.DoubleSide on the wrong object. You should use it on the material rather than on the mesh itself:
material.side = THREE.DoubleSide;
...nothing more !
Update 2019: Imageutil.loadTexture is deprecated,
Use THREE.TextureLoader() instead
new THREE.TextureLoader().load(
WOOD,
//use texture as material Double Side
texture => {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.offset.x = 90/(2*Math.PI);
var woodMaterial = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.DoubleSide
});
// Add Ground
groundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(GRID_SIZE, GRID_SIZE, 32),
woodMaterial
);
//rotate
groundMesh.rotation.x = Math.PI / 2;
this.scene.add(groundMesh);
}
);

Categories

Resources