Search code examples
javascript3dthree.jslinear-algebraplane

Three.js - PlaneGeometry from Math.Plane


I am trying to draw a least squares plane through a set of points in Three.js. I have a plane defined as follows:

var plane = new THREE.Plane();
plane.setFromNormalAndCoplanarPoint(normal, point).normalize();

My understanding is that I need to take that plane and use it to come up with a Geometry in order to create a mesh to add to the scene for display:

var dispPlane = new THREE.Mesh(planeGeometry, planeMaterial);
scene.add(dispPlane);

I've been trying to apply this answer to get the geometry. This is what I came up with:

plane.setFromNormalAndCoplanarPoint(dir, centroid).normalize();
planeGeometry.vertices.push(plane.normal);
planeGeometry.vertices.push(plane.orthoPoint(plane.normal));
planeGeometry.vertices.push(plane.orthoPoint(planeGeometry.vertices[1]));
planeGeometry.faces.push(new THREE.Face3(0, 1, 2));

planeGeometry.computeFaceNormals();
planeGeometry.computeVertexNormals();

But the plane is not displayed at all, and there are no errors to indicate where I may have gone wrong.

So my question is, how can I take my Math.Plane object and use that as a geometry for a mesh?


Solution

  • This approach should create a mesh visualization of the plane. I'm not sure how applicable this would be towards the least-squares fitting however.

     // Create plane
    var dir = new THREE.Vector3(0,1,0);
    var centroid = new THREE.Vector3(0,200,0);
    var plane = new THREE.Plane();
    plane.setFromNormalAndCoplanarPoint(dir, centroid).normalize();
    
    // Create a basic rectangle geometry
    var planeGeometry = new THREE.PlaneGeometry(100, 100);
    
    // Align the geometry to the plane
    var coplanarPoint = plane.coplanarPoint();
    var focalPoint = new THREE.Vector3().copy(coplanarPoint).add(plane.normal);
    planeGeometry.lookAt(focalPoint);
    planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
    
    // Create mesh with the geometry
    var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00, side: THREE.DoubleSide});
    var dispPlane = new THREE.Mesh(planeGeometry, planeMaterial);
    scene.add(dispPlane);