VIZ++ Class: OpenGLTriangleSurfaces

 VIZ++ Class Library  VIZ++ Samples  VIZ++ ClassTree 

Source code

/*
 * OpenGLTriangleSurfaces.h 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


#pragma once

#include <viz++/opengl/Normal3.h>
#include <viz++/Vertex.h>
#include <viz++/opengl/TriangleIndices.h>
#include <viz++/Vector3f.h>
#include <viz++/opengl/FaceIndices.h>

namespace VIZ {
  
class OpenGLTriangleSurfaces {
private:
  const Vertex<3>* vertexArray;
  size_t         numberOfVertices;
  const FaceIndices<3>* faceArray;
  size_t         numberOfFaces;
  
  Normal3*       normals;
  size_t         numberOfNormals;
  
public:
  OpenGLTriangleSurfaces(__in const Vertex<3>* vertices, __in size_t numVertices, 
              __in const FaceIndices<3>* faces, __in size_t numFaces)
  :vertexArray(NULL),
  numberOfVertices(numVertices),
  faceArray(NULL),
  numberOfFaces(numFaces),
  normals(NULL),
  numberOfNormals(0)
  {
    //Deep copy
    if (vertices && numVertices >0) {
      vertexArray = new Vertex<3>[numVertices];
      memcpy((void*)vertexArray, (const void*)vertices, sizeof(Vertex3)* numVertices);
    } else {
      throw IException("Invalid vertices parameters.");
    }
    if (faces && numFaces >0) {
      faceArray = new FaceIndices<3>[numFaces];
      memcpy((void*)faceArray, (const void*)faces, sizeof(FaceIndices<3>)* numFaces);
    } else {
      throw IException("Invalid faces parameters.");
    }
    //calculateNormals();    
  }
  
  
  ~OpenGLTriangleSurfaces()
  {
    delete [] vertexArray;
    vertexArray = NULL;
    delete [] faceArray;
    faceArray   = NULL;
    delete [] normals;
    normals = NULL;
  }
  
  Normal3* calculateSurfaceNormals(__out size_t& numNormals)
  {
    numberOfNormals = numberOfFaces;
    if (normals == NULL) {
      normals = new Normal3[numberOfFaces];
    }
      
    for (int i = 0; i<numberOfFaces; i++) {
        FaceIndices<3> tri = faceArray[i];
        Vector3f v1(vertexArray[ tri.index[0] ]);
        Vector3f v2(vertexArray[ tri.index[1] ]);
        Vector3f v3(vertexArray[ tri.index[2] ]);
        Vector3f normal = Vector3f::crossProduct(v2 - v1, v3 - v1);
        normal.normalize();
        
        normals[i].x = normal[0];
        normals[i].y = normal[1];
        normals[i].z = normal[2];
     // Printf("%d x=%f, y=%f, z=%f\n", i, 
     //    normals[i].x, normals[i].y, normals[i].z);
    } 
    numNormals = numberOfNormals;
    return normals;
    
  }
  
  void displayNormals()
  {
    for (int i =0; i<numberOfFaces; i++) {
      ::printf("%d x=%f, y=%f, z=%f\n", i, 
         normals[i].x, normals[i].y, normals[i].z);      
    }
  }
  
};

}

    

Last modified: 10 Feb 2017

Copyright (c) 2009-2017 Antillia.com ALL RIGHTS RESERVED.