ray.interstectObjects not intersecting correctly after geometry is dynamically modified - three.js

My ray.intersectObjects works really well with the objects in my scene until I dynamically modify the geometry of the object. Although the renderer is showing the objects as being modified (vertices moved and faces changed), when an intersect is tried on the modified object, it produces strange results. I need the intersect to work even on the modified geometry!
To help debug and track how the intersect is working in my scene, I've added a function: makeMiniSphere(). This makes a new sphere object in the scene at the point where the intersection occurs. Using this, you can see that after the cube is modified, sometimes the intersect hits the cube and sometimes it goes right through (mostly the faces that have been modified). It isn't a random problem, but the more you click around the modified cube, the more you can see a pattern develop. It is almost as if the renderer for the visuals of the scene know which direction the cube was modified, but the ray.intersectObjects thinks that it has been modified in a different direction!
Here is a link to the test website: http://www.littledrop.net/html/cadiverse/HelloWorld.html
Directions to show problem:
Left click on cube to show intersect points. Mini spheres will be created wherever Three.js sees an intersect. The color of the selected object will change to yellow if not already selected.
Click on any face of the cube. This will A. Turn it yellow if it isn't already yellow. B. It will select the face of the cube, although the selected face won't look any different from the rest of the cube.
Press the "Right" arrow key to move the selected face to the right. This will dynamically change the geometry of the cube.
Now try to click on the cube--especially in the area that it has been modified. Again the Mini spheres will show where the software thinks the intersects are occurring.
Here is the intersect code:
function onDocumentMouseDown (event)
{
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
//event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
document.getElementById('message1').innerHTML = window.innerHeight;
var isinworkingarea = window.innerHeight-menubarh;
if (event.clientY<=isinworkingarea)
{
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
//var ray = new THREE.ReusableRay();
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
// create an array containing all objects in the scene with which the ray intersects
// use this to select anything in the scene:
var intersects = ray.intersectObjects( scene.children );
if ( intersects.length > 0 )
{
if (cadjectNow)
cadjects[cadjectNow].material.color.setHex(cadjects[cadjectNow].oldColor);
if (intersects[0].object.cadNum)
cadjectNow = intersects[0].object.cadNum;
SELECTEDface=intersects[0].face;
if (cadjectNow)
cadjects[cadjectNow].material.color.setHex( selectColor );
document.getElementById('message1').innerHTML = cadjects[cadjectNum].cadNum;
///// Information about selected /////
var facestring = intersects[0].face.a + " " + intersects[0].face.b + " " + intersects[0].face.c;
if(intersects[0].face instanceof THREE.Face4)
{
facestring=facestring + " " + intersects[0].face.d;
}
copyGeometry=cadjects[cadjectNow].geometry;
//makeCopy(copyGeometry,cadjects[cadjectNow].position.x,cadjects[cadjectNow].position.y,cadjects[cadjectNow].position.z);
makeMiniSphere(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);
document.getElementById('message1').innerHTML = facestring;
//document.getElementById('message2').innerHTML = cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].y + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].z;
document.getElementById('message2').innerHTML = intersects[0].point.x + " " + intersects[0].point.y + " " + intersects[0].point.z;
}
}
}
Here is the modify code:
if ( keyboard.pressed("right"))
{
document.getElementById('message1').innerHTML = mouseMode;
cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x+=10;
cadjects[cadjectNow].geometry.vertices[SELECTEDface.b].x+=10;
cadjects[cadjectNow].geometry.vertices[SELECTEDface.c].x+=10;
if(SELECTEDface instanceof THREE.Face4)
{
cadjects[cadjectNow].geometry.vertices[SELECTEDface.d].x+=10;
}
cadjects[cadjectNow].geometry.verticesNeedUpdate = true;
cadjects[cadjectNow].geometry.elementsNeedUpdate = true;
cadjects[cadjectNow].geometry.normalsNeedUpdate = true;
}
Thank you to everyone who has posted past questions and given the answers. By perusing past questions, I've been able to get this far---so you guys have already been a great help. Thanks in advance for help on this one. (As this is my first question to post here, any suggestions on how to better present a question are also more than welcome.)
Update (3/21/13)--I've migrated to r57 as suggested and the updated code is shown above. I've also debugged it so that it is working at least as well as it was before. So now the geometry is still visually being changed dynamically, but the intersect is not detecting the change properly. Thanks #WestLangley for the encouraging posts so far.

Now working correctly. Here is how I did it (thanks to Westlangley for guidance).
Upgrade Three.js to latest revision (r57 from r49).
Migrate my present code to work with r57.
Remove all former code attempting to update the object.
Added the following code to "modify object" section:
cadjects[cadjectNow].geometry.verticesNeedUpdate = true;
cadjects[cadjectNow].geometry.normalsNeedUpdate = true;
cadjects[cadjectNow].geometry.computeFaceNormals();
cadjects[cadjectNow].geometry.computeVertexNormals();
cadjects[cadjectNow].geometry.computeBoundingSphere();

I was having a similar issue with a modified BufferGeometry.
I got raycasting working by calling geometry.computeBoundingSphere() and geometry.computeBoundingBox() after modifying the array with vertex positions.
Setting verticesNeedUpdate was not needed.
Running r112.

Related

Three.js: Object3D added in scene, attached to another object3D doesn't update position on translation

The logic of my code is such as the object3D which are included in the scene, on double click get added with a Line (with BufferGeometry).
I am getting the object3D by using Raycaster intersect.
The way I am adding it is:
scene.add( newLine );
newLine.updateMatrixWorld();
THREE.SceneUtils.attach( newLine, scene, intersects[0].object );
The following is my mousemove code which helps me moving the object3D in XZ plane.
function onDocumentMouseMove( event ) {
var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouseY = - ( event.clientY / window.innerHeight ) * 2 + 1;
var mouse = new THREE.Vector2( mouseX, mouseY );
raycaster.setFromCamera( mouse, camera);
if (selection) {
var intersects = raycaster.intersectObject( plane );
selection.position.copy( intersects[0].point.sub( offset ));
}
}
Nothing complicated. Simple code. And the movement is happening well. I can easily move the object3D around.
When I am checking the console for change in position of object3D on grabbing and moving it, it is changing which is what should happen. But I do not see any change at in the position of the Line, i.e., newLine as in my code. The issue is unless I am calling .updateWorldMatrix() as well which as per THREE docs, should automatically be called in each render cycle. Still I am calling that. Why am not able to get the position of my newLine when clearly its position is moving along with the object3D when I am dragging object3D around?
Why is it needed? Unless the position of the line can show as changing, I can't update an HTML element, which I am attaching to the end of that line. Hence, the position change is imperative. Gif attached which shows, when the cube/ sphere/ cone is moved, render(..) gives me changing position log of that. However, when logging the same for the Line it doesn't change. If any can help me with the issue, it will be amazing. Thanks much.
EDIT
When I am attaching the HTMLElement directly to parent object3D it shows expected result. It moves when I move object3D. This is because as said its position is being updated continuously in the render cycle when I move it.
Gif:
The line's .position attribute is not changing because its local position remains the same. Since the line is attached to the parent, its relative position to the parent doesn't change, only the global position does. To get the global position of line, you can use the .getWorldPosition() method:
// Declare var to store world position
var worldPos = new THREE.Vector3();
// Get world position of line
line.getWorldPosition(worldPos);
// Now global position is stored in Vec3
console.log(worldPos);

Is there a way I can create a Path or Curve to use for TubeGeomety(path,...) from an existing geometry's points/vertices array?

I'm very new to both three.js & to js in general.
1st I select a polyHedron geometry with a dat.gui checkbox
which renders say a tetrahedron. these selections work.
I also have a dat.gui checkbox to either phongfill or wireframe render.
I initially wanted just a wireframe type mesh but not with all of the internal triangles. I found the edgesgeometry() function which draws pretty much what I want(hard edges only). there is however a known issue with linewidth not working in windows anymore. all lines drawn as strokeweight/width 1.
I'd like to use tubeGeometry() to draw tubes of whatever radius as opposed to 1weight lines. I know I'll have to draw something such as a sphere at/over the connection vertices for it to not look ridiculous.
geo = new THREE.TetrahedronBufferGeometry(controls0.Radius,controls0.Detail);
...
egeo = new THREE.EdgesGeometry( geo );
lmat = new THREE.LineBasicMaterial({ color: 0x0099ff, linewidth: 4 });
ph = new THREE.LineSegments( egeo, lmat );
scene.add(ph);
....
playing around in the console I found some geometry/bufferGeomery arrays that are likely the vertices/indices of my selected X-hedron as their sizes change with type(tetra/icosa etc) selection & detail increase/decrease:
//p = dome.geometry.attributes.uv.array;
p = egeo.attributes.position.array
//p = geo.attributes.uv.array
...
var path = new THREE.Curve();
path.getPoint = function (t) {
// trace the arc as t ranges from 0 to 1
var segment = (0 - Math.PI*2) *t;
return new THREE.Vector3( Math.cos(segment), Math.sin(segment), 0);
};
var geomet = new THREE.TubeBufferGeometry( path, 10, 0.2, 12, false );
var mesh = new THREE.Mesh( geomet, mat );
scene.add( mesh );
from above the tubeGeometry() draws fine separately as well but with the "path" made by that curve example. How can I use the vertices from my tetrahedron for example to create that "path" to pass to tubegeometry() ?
maybe a function that creates "segment vectors" from the vertices ?
I think it needs other properties of curve/path as well ?
I'm quite stuck at this point.
ANY Help, suggestions or examples would be greatly appreciated !
thanks.
You can try to create a TubeGeometry for each edge. Generate a LineCurve3 as the input path. Use the vertices of the edge as the start and end vector for the line.
Consider to use something like "triangulated lines" as an alternative in order to visualize the wireframe of a mesh with a linewidth greater than 1. With the next release of three.js(R91) there are new line primitives for this. Demo:
https://rawgit.com/mrdoob/three.js/dev/examples/webgl_lines_fat.html
This approach is much more performant than drawing a bunch of meshes with a TubeGeometry.

Get mouse clicked point's 3D coordinate in three.js

I'm new in THREE.js.
I'm trying to get 3D coordinates of point on mouse click on the object (not simple objects: Box, Sphere,..) in Canvas.
In detail, I'm working with 3D objects viewer - I have camera (THREE.PerspectiveCamera), mouse controls (rotate, zoom, move), add/remove objects (my own object, loaded using loaders for THREE.js) in scene,.. And I want to add a function, which gets 3D coordinates for clicked point in 3D.
Exactly, I want coordinates of the end point of a ray - begining from mouse click on the camera_near_window and ending to the object's point, I've clicked on..
I tried a lot of ways to do it:
Getting coordinates of point on z=0 plane -- It works fine, but it is on z=0 plane and it is not that I need, cause I have OrbitControls..
THREE.js example - clickable objects -- It uses CanvasRenderer (not WebGLRenderer) and works for a little objects (but works for my project): browser crashes when I load many objects (CanvasRenderer needs 5x more memory then WebGLRenderer).
"How to get object in WebGL 3d space from a mouse click coordinate" - I tried this one too, but raycaster.intersectObjects found nothing, intersects was an empty array (maybe it works for only simple objects like box, sphere,..).
Can anyone show me the demo code which gets 3D point coords for clicked point of clicking object in 3D, please..?
So, as I think this question is useful for someone, I'll answer it myself (I'll write my resolve):
var renderer, canvas, canvasPosition, camera, scene, rayCaster, mousePosition;
function init() {
renderer = new THREE.WebGLRenderer({ antialias: false });
canvas = renderer.domElement;
canvasPosition = $(canvas).position();
camera = new THREE.PerspectiveCamera(20, $(canvas).width() / $(canvas).height(), 0.01, 1e10);
scene = new THREE.Scene();
rayCaster = new THREE.Raycaster();
mousePosition = new THREE.Vector2();
scene.add(camera);
var myObjects = new THREE.Object3D();
// myObjects.add( your object );
// myObjects.add( your object );
// myObjects.add( your object );
myObjects.name = 'MyObj_s';
scene.add(myObjects);
};
function getClicked3DPoint(evt) {
evt.preventDefault();
mousePosition.x = ((evt.clientX - canvasPosition.left) / canvas.width) * 2 - 1;
mousePosition.y = -((evt.clientY - canvasPosition.top) / canvas.height) * 2 + 1;
rayCaster.setFromCamera(mousePosition, camera);
var intersects = rayCaster.intersectObjects(scene.getObjectByName('MyObj_s').children, true);
if (intersects.length > 0)
return intersects[0].point;
};

How to fix tiny holes in the Mesh after subtract operation with Three.CSG

I have a Box Mesh where I subtract another Box with Three.CSG to create a wall with a window.
After doing so, there are tiny holes in the Mesh alongside the cut. They are not visible alle the time, but show up when moving around.
How to close these holes?
This is part of the code how I am creating the Mesh:
var wallBsp = new ThreeBSP( myWallMesh );
var subMesh = new THREE.Mesh( mygeo );
var subBsp = new ThreeBSP( subMesh );
var subtract_bsp = wall_bsp.subtract( subBsp );
var result = subtract_bsp.toMesh();
result.material.shading = THREE.FlatShading;
result.geometry.computeVertexNormals();
Update
I have created a jsfiddle, but it is difficult to reproduce the error, I couldnt make it visible there: http://jsfiddle.net/L0rdzbej/23/
However, you can see the full application here.
Like #gaitat suggested, geometry.mergeVertices() does not look like it changes anything for me. Chandler Prall hinted at the source where precisionPoints, which is a variable inside the mergeVertices function, could solve this. Depending on the scale of the scene its value should be lower or negative, but I had no success so far.

three.js and TrackballControls - keeping horizon flat

I'm attempting to modify TrackballControls.js so that its rotation is like that of OrbitControls.js, where the horizon stays flat, but maintain the ability to rotate over and around a scene (specifically, a collada building model). I've been trying to figure this out for the better part of a day now, but I'm a designer, not a programmer. :-) I'm not even sure if I should be focusing on this.rotateCamera and/or this.update.
(BTW, I would just use OrbitControls.js, but it doesn't support panning, which is necessary when looking at large collada building models.)
Any help would be much appreciated.
It's been awhile since this question was asked, but I ran into the same problem and didn't find much discussion online, so I thought I'd post my solution.
If you must use TrackballControls and you want to a flat horizon, you can simply edit the TrackballControls.js library by adding the following line to the end of the 'this.rotateCamera' method
this.object.up = new THREE.Vector3(0,1,0);
This locks the camera up direction in the (0,1,0) direction (i.e in the y direction). The entire modified method function would then read:
this.rotateCamera = function () {
var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
if ( angle ) {
var axis = ( new THREE.Vector3() ).crossVectors( _rotateStart, _rotateEnd ).normalize();
quaternion = new THREE.Quaternion();
angle *= _this.rotateSpeed;
quaternion.setFromAxisAngle( axis, -angle );
_eye.applyQuaternion( quaternion );
_this.object.up.applyQuaternion( quaternion );
_rotateEnd.applyQuaternion( quaternion );
if ( _this.staticMoving ) {
_rotateStart.copy( _rotateEnd );
} else {
quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
_rotateStart.applyQuaternion( quaternion );
}
}
// Lock the camera up direction
this.object.up = new THREE.Vector3(0,1,0);
};

Resources