求三角形和多边形的面积

AREA OF A MESH FACE IN C# IN GRASSHOPPER

James Ramsden | 26 March 2015 | Grasshopper | No Comments

Another quick script for handing meshes – this time to find the area of a mesh face.

This script is in C# and can be easily used with the C# component in Grasshopper. Copy the script into the ‘custom additional code’ section. It is written as a method, so you can easily call it. In the ‘RunScript’ section, call the method with something like:

double area = Area(3, myMesh)

This will return the area of the third face in the mesh called myMesh.

The method itself to calculate the area of a mesh face is below. Of course, you can use this method in any C# application, not just Grasshopper – you’ll just need to modify the code to fit whatever data structure your mesh uses.

  double Area(int meshfaceindex, Mesh m)
  {
    //get points into a nice, concise format
    Point3d[] pts = new Point3d[4];
    pts[0] = m.Vertices[m.Faces[meshfaceindex].A];
    pts[1] = m.Vertices[m.Faces[meshfaceindex].B];
    pts[2] = m.Vertices[m.Faces[meshfaceindex].C];
    if(m.Faces[meshfaceindex].IsQuad) pts[3] = m.Vertices[m.Faces[meshfaceindex].D];

    //calculate areas of triangles
    double a = pts[0].DistanceTo(pts[1]);
    double b = pts[1].DistanceTo(pts[2]);
    double c = pts[2].DistanceTo(pts[0]);
    double p = 0.5 * (a + b + c);
    double area1 = Math.Sqrt(p * (p - a) * (p - b) * (p - c));

    //if quad, calc area of second triangle
    double area2 = 0;
    if(m.Faces[meshfaceindex].IsQuad)
    {
      a = pts[0].DistanceTo(pts[2]);
      b = pts[2].DistanceTo(pts[3]);
      c = pts[3].DistanceTo(pts[0]);
      p = 0.5 * (a + b + c);
      area2 = Math.Sqrt(p * (p - a) * (p - b) * (p - c));
    }

    return area1 + area2;
  }

This script is based upon Heron’s Formula, which calculates the area of a triangle based upon knowing its three lengths. The script also calculates the area for quads. It does this by dividing the quad into two triangles.

mesh-area

 

Heron was one of the great mathematicians of antiquity and came up with this formula sometime in the first century BC, although it may have been known earlier. He also extended it to the area of quadrilaterals and higher-order polygons.

猜你喜欢

转载自blog.csdn.net/yaorongzhen123/article/details/84243547