aneeshtan / jsc3d

Automatically exported from code.google.com/p/jsc3d
0 stars 0 forks source link

How can i calculate volume? #114

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Is any function to calculate volume exists?

Original issue reported on code.google.com by max.lyap...@gmail.com on 9 Sep 2014 at 4:58

GoogleCodeExporter commented 9 years ago
Jsc3d itself hasn't got any function to do this because it mainly aims at 
visualization. But it's not difficult to write one since the vertex and the 
face data are available in the mesh objects.  I have implemented this method 
for someone years before. It may also be of some use for you.

The following method compute the volume of a single mesh:

  function computeVolume(mesh) {
    var sum = 0;
    var ibuf = mesh.indexBuffer;
    var vbuf = mesh.vertexBuffer;
    var i = 0, j = 0;
    // walk through all faces, calculating the volume of the mesh 
    while(i < mesh.faceCount) {
      var v0, v1, v2;
      var x0, y0, z0, x1, y1, z1, x2, y2, z2;
      v0 = ibuf[j++] * 3;
      v1 = ibuf[j++] * 3;
      // calculate volume of the polyhedron formed by the origin point and this face
      do {
        v2 = ibuf[j++] * 3;
        x0 = vbuf[v0    ];
        y0 = vbuf[v0 + 1];
        z0 = vbuf[v0 + 2];
        x1 = vbuf[v1    ];
        y1 = vbuf[v1 + 1]; 
        z1 = vbuf[v1 + 2];
        x2 = vbuf[v2    ];
        y2 = vbuf[v2 + 1];
        z2 = vbuf[v2 + 2];
        sum += - x2 * y1 * z0
               + x1 * y2 * z0 
               + x2 * y0 * z1
               - x0 * y2 * z1
               - x1 * y0 * z2
               + x0 * y1 * z2;
        v1 = v2;
      } while (ibuf[j] != -1);
      // continue to next face
      j++;
      i++;
    }
    return Math.abs(sum/6);
  }

It can be used like this:

  // say we are to compute the volume of the first mesh after the model is loaded completely
  var mesh = viewer.getScene().getChildren()[0];
  var volume = computeVolume(mesh);
  console.info('the volume is ' + volume);

If you just want the total volume of all meshes all over a model, then compute 
it like this:

  // compute the total volume of a model after it has been loaded completely
  var totalVolume = 0;
  viewer.getScene().forEachChild( function(mesh) {
    totalVolume += computeVolume(mesh);
  } );
  console.info('the total volume is: ' + totalVolume);

The algorithm is based on the assumption that all the meshes are closed. 
Otherwise, the result is undefined.

Original comment by Humu2...@gmail.com on 10 Sep 2014 at 2:30

GoogleCodeExporter commented 9 years ago
Thank you. This works very nice!

Original comment by max.lyap...@gmail.com on 10 Sep 2014 at 7:10