Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Mesh from Points Three.js

I'm trying to create a clickable shape in Three from a bunch of points that are generated by mouse click.

This code is kind of working:

mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / player.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / player.height ) * 2 + 1

raycaster.setFromCamera( mouse, camera );

var objects = [];
objects.push(selectedHotspot);

var intersects = raycaster.intersectObjects( objects, true  );

if ( intersects.length > 0 ) {
    var point = new THREE.Mesh( new THREE.SphereGeometry(1, 1, 1), new THREE.MeshBasicMaterial( { color: 0x00ffff } ) );
    point.position.copy(intersects[0].point);
    scene.add(point);
    points.push(intersects[0].point);
}

var geometry = new THREE.Geometry();

points.forEach( function( point ){
    geometry.vertices.push( point );
});
geometry.vertices.push( points[0] );

geometry.faces.push( new THREE.Face3(0, 1, 2));

// material
var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );

// line
var line = new THREE.Mesh( geometry, material );
scene.add( line );
hotspots.push( line );

The points get added, I can draw lines between them I just can't fill in the center so the mouse can detect it!

like image 676
beek Avatar asked Dec 23 '22 21:12

beek


2 Answers

You can create a mesh from points using THREE.ConvexGeometry.

var mesh = new THREE.ConvexGeometry( vertices_array );

See, for example, https://threejs.org/examples/webgl_geometry_convex.html

This is just the convex hull of your points, but it should be sufficient for your use case.

You must include the three.js file examples/jsm/geometries/ConvexGeometry.js explicitly in your source code.

three.js r.147

like image 104
WestLangley Avatar answered Dec 26 '22 12:12

WestLangley


There are different ways to create a mesh out of a point cloud - it all depends on what your specific needs are. I'll try to give you a high-level overview of a few approaches.

Perhaps a bounding box is enough? Calculate the bounding box of the point cloud and raycast against the BBox.

If the BBox happens to contains large volumes that have no points in them, then you may need a tighter-fitting mesh around these points. Given the ray being cast, project all points onto a plane normal to the ray, then construct the 2D convex hull of the points on this plane using the Gift wrapping algorithm. There are most likely existing libraries implementing this algorithm. Use the polygon constructed by this algorithm for the raycast test.

like image 41
Stefan Dragnev Avatar answered Dec 26 '22 11:12

Stefan Dragnev