I'm working on adapting the object loading example on the THREE.js example page to allow for the loaded objects to have their faces selected and colored. My general strategy has been to follow the steps outlined here.
However, since I am not using THREE.geometry objects, I am having trouble piecing together this strategy with the obj loader code.
I currently have ray intersection working so I know when I am clicking on the object, I am just having trouble coloring the faces. I know I need to apply: vertexColors: THREE.FaceColors to the obj material and thats where I'm stuck.
My current obj loading code is as follows:
var loader = new THREE.OBJLoader( manager );
loader.load( path, function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
var faceColorMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff, vertexColors: THREE.VertexColors } );
child.material = faceColorMaterial;
child.geometry.addAttribute( "color", new THREE.BufferAttribute( new Float32Array( 3 * 3 ), 3 ) );
child.geometry.dynamic = true;
}
} );
scene.add( object );
targetList.push(object);
}, onProgress, onError );
And my detection and coloring code:
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
vector.unproject( camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = ray.intersectObjects( targetList, true );
if ( intersects.length > 0 ) {
var colorArray = intersects[0].object.geometry.attributes.color.array;
var face = intersects[0].face;
colorArray[face.a] = 1;
colorArray[face.a + 1] = 0;
colorArray[face.a + 2] = 0;
colorArray[face.b] = 1;
colorArray[face.b + 1] = 0;
colorArray[face.b + 2] = 0;
colorArray[face.c] = 1;
colorArray[face.c + 1] = 0;
colorArray[face.c + 2] = 0;
intersects[0].object.geometry.attributes.color.needsUpdate = true;
}
When I run this, my object is black and when I click the faces, they do not change color.
How can I alter my code to allow for the changes to be colored when selected?
OBJLoader should be returning BufferGeometry objects, which don't use FaceColors. BufferGeometry can use VertexColors to assign colors to a face, but you need to ensure the colors attribute is applied to the BufferGeometry. If you do have a colors attribute, then you're in luck, because OBJLoader gives you unique vertices for each triangle.
When intersectObjects returns, the Face3 should have a, b, and c, which I believe should be indicies into the mesh.geometry.attributes.position.array, but they'll also be indices into the mesh.geometry.attributes.color.array array.
var colorArray = intersects[0].object.geometry.attributes.color.array,
face = intersects[0].face;
colorArray[face.a] = 1;
colorArray[face.a + 1] = 0;
colorArray[face.a + 2] = 0;
colorArray[face.b] = 1;
colorArray[face.b + 1] = 0;
colorArray[face.b + 2] = 0;
colorArray[face.c] = 1;
colorArray[face.c + 1] = 0;
colorArray[face.c + 2] = 0;
intersects[0].object.geometry.attributes.color.needsUpdate = true;
This should turn a particular face red. But I can't stress enough that this will only work if your geometry has a colors attribute, and your material is using THREE.VertexColors.
Related
Hey im using Three meshline an add-on for three js you can find here.
https://github.com/spite/THREE.MeshLine/tree/master/src.
it works great in my code the only thing is, fog does not apply on its special own material new MeshLineMaterial. Is there any way to implement the fog value to the meshline.js file?
Thanks for your help
var geometry = new THREE.Geometry();
for( var k = 0; k < splinePoints.length; k++) {
var v = new THREE.Vector3( splinePoints[k].x + 3* Math.sin(k/4), splinePoints[k].y + 3 *Math.cos(k/4), splinePoints[k].z);
geometry.vertices.push( v );
}
makeLine(geometry, Colors.red);
function makeLine( geo, c ) {
var g = new MeshLine();
g.setGeometry( geo );
var material = new MeshLineMaterial( {
color: new THREE.Color( c ),
opacity: 1,
lineWidth: 1
});
var mesh = new THREE.Mesh( g.geometry, material );
graph.add( mesh );
}
I have an large array (50,000 to 100,000 elements) with each element containing another array of 3 points that define the vertices of a polygon. Some vertices have a parameter addition built in to the array, e.g;
var array = [
[[967.6719, 657.401, -1008.1],[967.6719, 657.401, -1001.1],[967.1551, 657.4806, -1008.1]],
[[967.1551, 657.4806, -1008.1 + LENGTH],[967.6719, 657.401, -1001.1],[967.1551, 657.4806, -1001.1]],
...etc
];
The length parameter is controlled by a slider bar. Currently the initial load time is way too long and any changes to the parameter also takes ages to update. Is there a way to optimise this?
I am currently rendering the polygons with this code;
function drawShapes(array) {
scene.remove( all_shapes );
all_shapes = new THREE.Object3D();
var LENGTH = inpLength.valueAsNumber;
var material = new THREE.LineBasicMaterial( { color: 0x02B700, linewidth: 2 } );
var triangleGeometry = new THREE.Geometry();
for (var i=0; i < array.length; i++){
for (var n=0; n<3; n++){
triangleGeometry.vertices.push(new THREE.Vector3( array[i][n][0], array[i][n][1], array[i][n][2]));
}
triangleGeometry.faces.push(new THREE.Face3(0, 1, 2));
triangleMesh = new THREE.Mesh(triangleGeometry, material);
all_shapes.add(triangleMesh)
var triangleGeometry = new THREE.Geometry();
}
scene.add( all_shapes );
}
It seems like this should be easy, but I have spent nearly a week on this trying every possible combination of how to drag multiple items as a group in Three.js. It started out simple, I used this example https://jsfiddle.net/mz7Lv9dt/1/ to get the ball working. I thought I could just add some TextGeometry, which of course had some major API changes in the last couple releases rendering most examples obsolete.
After finally getting it to work as a single line, I wanted to add in wordwrap and move it as a group, but I can't seem to do so.
Here you can see it working just fine with the ball, but you can't drag the text https://jsfiddle.net/ajhalls/h05v48wd/
By swapping around three lines of code (location line 93-99), I can get it to where you can drag the individual lines around, which you can see here: https://jsfiddle.net/ajhalls/t0e2se3x/
function addText(text, fontSize, boundingWidth) {
var wrapArray;
wrapArray = text.wordwrap(10,2);
var loader = new THREE.FontLoader();
loader.load( 'https://cdn.coursesaver.com/three.js-74/examples/fonts/helvetiker_bold.typeface.js',
function ( font ) {
group = new THREE.Group();
group.name = "infoTag";
for (var i = 0; i < wrapArray.length; i++) {
var objectID=i;
var line = wrapArray[objectID];
var textGeo = new THREE.TextGeometry( line, {font: font,size: fontSize,height: 10,curveSegments: 12,bevelThickness: 0.02,bevelSize: 0.05,bevelEnabled: true});
textGeo.computeBoundingBox();
var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x );
var textMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000, specular: 0xffffff } );
var mesh = new THREE.Mesh( textGeo, textMaterial );
mesh.position.x = centerOffset +200;
mesh.position.y = i*fontSize*-1+11;
mesh.position.z = 280;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.geometry.center();
mesh.lookAt(camera.position);
mesh.name = i;
group.add( mesh ); //this should work - comment out and swap for other two lines to see
scene.add(mesh); // this should work- comment out and swap for other two lines to see
//objects.push(mesh);//works on individual lines if you uncomment this
//scene.add(mesh); //works on individual lines if you uncomment this
}
objects.push( group ); // this should work- comment out and swap for other two lines to see
});
}
That "should" be working according to everything I had researched over the last week. I had one moment where it was "working" but because of the size of the group object, the pivot points were wrong, the setLength function didn't work, and it flipped the object away from the camera. All in all it was a mess.
I did try using 2d objects such as canvases and sprites, but for reasons detailed here Three.js TextGeometry Wordwrap - drag as group couldn't get it working.
Please, someone help me!
The issue ended up being with the group. Previously I was creating it, adding objects to it with a position.z which increased the size of the box around the group, then after doing that I moved the box to in front of the camera and did a group.lookAt which meant that when I was dragging it everything including pivot point and looking at it from the back was wrong. The right way was to create the group, position it, face the camera, then add the text.
function addText(text, fontSize, wrapWidth, tagColor, positionX, positionY, positionZ) {
var wrapArray;
wrapArray = text.wordwrap(wrapWidth,2);
var loader = new THREE.FontLoader();
loader.load( '/js/fonts/helvetiker_bold.typeface.js', function ( font ) {
group = new THREE.Group();
group.position.x=positionX;
group.position.y=positionY;
group.position.z=positionZ;
group.lookAt(camera.position);
group.tourType = "infoTag";
group.name = "infoTag-" + objects.length;
group.dataID=objects.length;
group.textData=text;
for (var i = 0; i < wrapArray.length; i++) {
var objectID=i;
var line = wrapArray[objectID];
var textGeo = new THREE.TextGeometry( line, {
font: font,
size: fontSize,
height: 1,
curveSegments: 12,
bevelThickness: 0.02,
bevelSize: 0.05,
bevelEnabled: true
});
textGeo.computeBoundingBox();
var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x );
var textMaterial = new THREE.MeshPhongMaterial( { color: tagColor, specular: 0xffffff } );
var mesh = new THREE.Mesh( textGeo, textMaterial );
mesh.dataID=objects.length;
mesh.position.x = 0;
mesh.position.y = (i*mesh.geometry.boundingBox.max.y*-1)*1.15;
mesh.position.z = 0;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.geometry.center();
//mesh.lookAt(camera.position);
mesh.name = "infoTag-mesh-" + objects.length;
group.add( mesh );
}
scene.add(group);
objects.push( group );
});
}
Of course there were some changes to be made in the mouse events to take into account that you want to move the parent of the object, which looks something like this:
function onDocumentMouseDown(event) {
event.preventDefault();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
if (intersects[0].object.parent.tourType == 'infoTag') {
var manipulatingInfoTag = true;
SELECTED = intersects[0].object.parent;
}else{
SELECTED = intersects[0].object;
}
var intersects = raycaster.intersectObject(plane);
if (intersects.length > 0) {
offset.copy(intersects[0].point).sub(plane.position);
}
container.style.cursor = 'move';
}
isUserInteracting = true;
onPointerDownPointerX = event.clientX; onPointerDownPointerY = event.clientY; onPointerDownLon = lon; onPointerDownLat = lat;
}
I'm using the ExplodeModifier to duplicate the vertices so I can have individual control over Face3 objects.
For my specific example, this alone looks visually poor, so I decided to add 3 extra faces (per existing face) so I can have a pyramid shape pointing inwards the geometry.
I managed to modify the ExplodeModifier and create the extra faces, however I get several errors:
THREE.DirectGeometry.fromGeometry(): Undefined vertexUv and THREE.BufferAttribute.copyVector3sArray(): vector is undefined
I understand that now I have 9 extra vertices per face, so I need according uv's, and since I don't need a texture but a solid color I don't mind having the wrong uvs... So, I also duplicated the uvs and avoid the first warning but I can't get rid of the copyVector2sArray...
pseudo code:
var geometry = new THREE.IcosahedronGeometry( 200, 1 );
var material = new THREE.MeshPhongMaterial( { shading: THREE.FlatShading } );
var explodeModifier = new THREE.ExplodeModifier();
explodeModifier.modify( geometry );
var mesh = new THREE.Mesh( geometry, material );
scene.addChild( mesh );
The Explode Modifier has this pseudo code:
var vertices = [];
var faces = [];
for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
(...)
var extraFace1 = new THREE.Face3().copy(face)
extraFace1.c = geometry.vertices[0]
var extraFace2 = new THREE.Face3().copy(face)
extraFace2.b = geometry.vertices[0]
var extraFace3 = new THREE.Face3().copy(face)
extraFace3.a = geometry.vertices[0]
faces.push( extraFace1 );
faces.push( extraFace2 );
faces.push( extraFace3 );
}
geometry.vertices = vertices;
geometry.faces = faces;
```
I added an example HERE. It works, but I want to avoid the console warnings...
As pointed out by #mrdoob I was assigning a THREE.Vector3 and not an index to the added THREE.Face3.
var extraFace1 = new THREE.Face3().copy(face)
extraFace1.a = geometry.faces.length * 3 - 1
var extraFace2 = new THREE.Face3().copy(face)
extraFace2.b = geometry.faces.length * 3 - 1
var extraFace3 = new THREE.Face3().copy(face)
extraFace3.c = geometry.faces.length * 3 - 1
jsfiddle updated
Hi folks,
I've got a question belongig surfaces in Three.js:
I got a bunch of Vec3 Points and want want to interpolate a surface through them. While searching, I stumbeled across beziers (three.js bezier - only as lines) and what looked more like I was searching : three.js Nurbs. I've tried to reconstruct the code, but the documentation was terrible (pages like this) and I didn't get how everything worked by reconstructing the code...
So here's the question:
Is there any easy way to get a shape out of my calculated points? (I would still be happy, if it's not interpolated).
Thank you guys!
Mat
Edit: What I want to acchieve is a surface plot. I stumbeled across http://acko.net/blog/making-mathbox/ but it's way too big for my needs...
After some try and error I found a solution: add a plane and than transform the single vertices.
// need to setup 'step', 'xStart', 'xEnd', 'yStart', 'yEnd'
// calc the variables
var width = Math.abs(-xStart+xEnd),
height = Math.abs(-yStart+yEnd);
var stepsX = width*step, stepsY = height*step;
var posX = (xStart+xEnd)/2;
var posZ = (yStart+yEnd)/2;
// add a plane and morph it to a function
var geometry = new THREE.PlaneGeometry( width, height, stepsX - 1, stepsY - 1 );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
var size = stepsX * (stepsY),
data = new Float32Array( size );
var count = 0, scope = {};
mesh = new THREE.Mesh( geometry, new THREE.MeshNormalMaterial( {
side : THREE.DoubleSide,
transparent: true,
shading: THREE.SmoothShading,
opacity : _opacity }));
mesh.updateMatrixWorld();
// calc y value for every vertice
for ( var i = 0; i < size; i ++ ) {
// calculate the current values
// http://stackoverflow.com/questions/11495089/how-to-get-the-absolute-position-of-a-vertex-in-three-js
var vector = mesh.geometry.vertices[i].clone();
vector.applyMatrix4(
mesh.matrixWorld
);
// set them into the scope
scope.x = vector.x + posX;
scope.y = vector.z + posZ;
// calculate point and write it in a temp array
data[i] = math.eval(term, scope);
}
// push the new vertice data
for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) {
geometry.vertices[ i ].y = data[ i ];
}
// update the new normals
geometry.computeFaceNormals();
geometry.computeVertexNormals();
// add to scene
scene.add( mesh );
Only issue is that it is not working for non static functions like tan(x). This snippet is using math.js to calc the term.
Greetings Mat