Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. // TAKES: a polygon 'in', a clipped polygon 'out'
  2. // RETURNS: number of vertices in polygon 'out'; clipped polygon 'out'
  3. // MEMBERS: point on plane 'pos', normal of plane 'nor'
  4. void plane3::clip(const array<vec3> &in, array<vec3> &out) const
  5. {
  6.     out.alloc(in.size() + 1); // make room for max number of out verts
  7.     array<float> dist;
  8.     dist.alloc(in.size());
  9.     int numOut = 0;
  10.     for (int i = 0; i < dist.size(); ++i) {
  11.         dist[i] = dot(in[i] - pos, nor);
  12.         if (dist[i] <= 0.0f) { ++numOut; }
  13.     }
  14.     if (numOut == dist.size()) { // all verts are either behind, or on, plane
  15.         out.dealloc();
  16.         return;
  17.     }
  18.     int numIn = 0;
  19.     for (int i = 0, j = in.size() - 1; i < in.size(); j=i, ++i) {
  20.         if ((dist[i] < 0.0f) == (dist[j] >= 0.0f)) {
  21.             out[numIn++] = in[i] + (in[j] - in[i]) * (dist[i] / (dist[i] - dist[j]));
  22.         }
  23.         if (dist[i] >= 0.0f) {
  24.             out[numIn++] = in[i];
  25.         }
  26.     }
  27.     out.resize(numIn); // resize to actual size of output poly (numIn <= out.size())
  28. }