void SunApp::updateSpline(const vector<Vec2>& cp, u32 numPoints, MeshPtr& triangles) { vector<Vec2> ip; // interpolated points vector<Vec2> nv; // tangent vectors catmullRom(cp, numPoints, ip); calculateNormals(ip, nv); // adjust triangle mesh, only writes to points f32 halfWidth = splineWidth / 2; u32 j=0; f32 falloff = halfWidth / numPoints; f32 hw = halfWidth; for(u32 i=0; i<numPoints; i+=1) { Vec2 p = ip[i]; Vec2 n = nv[i]; Vec2 halfdir = (n*hw); Vec2 leftPoint = p+halfdir; Vec2 rightPoint = p-halfdir; triangles->set(j, UT_position, leftPoint); triangles->set(j+1, UT_position, rightPoint); triangles->set(j, UT_texcoord0, Vec2(0,0)); triangles->set(j+1, UT_texcoord0, Vec2(1,0)); // DOUT("p "<< p << " n "<<n); // DOUT("left "<<leftPoint<<" right "<<rightPoint ); j+=2; hw -= falloff; } }
void testApp::updateBack() { backTriangles.clear(); Triangle cur; ofVec3f offset(0, 0, backOffset); ofVec3f nw = surface[getSurfaceIndex(roiStart.x, roiStart.y)]; ofVec3f ne = surface[getSurfaceIndex(roiEnd.x - 1, roiStart.y)]; ofVec3f sw = surface[getSurfaceIndex(roiStart.x, roiEnd.y - 1)]; ofVec3f se = surface[getSurfaceIndex(roiEnd.x - 1, roiEnd.y - 1)]; ofVec3f nwo = nw + offset; ofVec3f swo = sw + offset; ofVec3f neo = ne + offset; ofVec3f seo = se + offset; addBack(nwo, neo, ne, nw); // top addBack(ne, neo, seo, se); // right addBack(sw, se, seo, swo); // bottom addBack(nwo, nw, sw, swo); // left // two back faces addBack(nwo, swo, seo, neo); calculateNormals(backTriangles, backNormals); }
void Mesh::createVPlane(Number w, Number h) { Polygon *imagePolygon = new Polygon(); imagePolygon->addVertex(0,0,0,0,0); imagePolygon->addVertex(w,0,0, 1, 0); imagePolygon->addVertex(w,h,0, 1, 1); imagePolygon->addVertex(0,h,0,0,1); addPolygon(imagePolygon); for(int i=0; i < polygons.size(); i++) { for(int j=0; j < polygons[i]->getVertexCount(); j++) { polygons[i]->getVertex(j)->x = polygons[i]->getVertex(j)->x - (w/2.0f); polygons[i]->getVertex(j)->y = polygons[i]->getVertex(j)->y - (h/2.0f); } } calculateNormals(); calculateTangents(); arrayDirtyMap[RenderDataArray::VERTEX_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::COLOR_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::TEXCOORD_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::NORMAL_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::TANGENT_DATA_ARRAY] = true; }
Heightmap::Heightmap(int columns, int rows) { setColumns(columns); setRows(rows); vector<vec3> vertices; vector<unsigned int> indices; vector<vec2> texcoords; for(int z = 0; z <= rows; z++) { for(int x = 0; x <= columns; x++) { vertices.push_back(vec3(x*(1.0f/columns), 0, z*(1.0f/rows))); texcoords.push_back(vec2(x*0.5f, z*0.5f)); } } for(int row = 0; row < rows; row++) { for(int column = 0; column < columns; column++) { indices.push_back(column + row * (columns + 1)); indices.push_back(column + (row + 1) * (columns + 1)); indices.push_back(column + 1 + row * (columns + 1)); indices.push_back(column + 1 + row * (columns + 1)); indices.push_back(column + (row + 1) * (columns + 1)); indices.push_back(column + 1 + (row + 1) * (columns + 1)); } } setVertices(vertices); setIndices(indices); setTexcoords(texcoords); material.setSpecularReflectance(0.05f); material.setShininess(1.0f); material.setAmbientReflectance(0.5f); init(); calculateNormals(); }
/* ================ Terrain::init ================ */ bool Terrain::init( ID3D10Device* device, char* heightmapFilename, WCHAR* textureFilename ) { bool result; result = loadHeightMap(heightmapFilename); if (!result) { return false; } normalizeHeightMap(); result = calculateNormals(); if (!result) { return true; } calculateTextureCoordinates(); result = loadTexture(device, textureFilename); if (!result) { return false; } result = initBuffers(device); if (!result) { return false; } return true; }
poMesh3D::poMesh3D( int _numRows, int _numColumns ) { numRows = _numRows; numColumns = _numColumns; vertexList.resize( numRows*numColumns ); for( int i=0; i<numRows; i++ ) { for( int j=0; j<numColumns; j++ ) { getVertex( i,j ).position.set( i*10,j*10, 0 ); } } for( int i=0; i<numRows-1; i++ ) { for( int j=0; j<numColumns-1; j++ ) { int indexA = getVertexIndex(i,j); int indexB = getVertexIndex(i+1,j); int indexC = getVertexIndex(i,j+1); int indexD = getVertexIndex(i+1,j+1); addTriangle( indexA, indexB, indexC ); addTriangle( indexD, indexC, indexB ); } } calculateNormals(); }
void Drawable::init() { // Create a vertex array object glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); // BUFFERS // Create and initialize a buffer object // First vertex buffer glGenBuffers( 1, &vbuffer ); glBindBuffer( GL_ARRAY_BUFFER, vbuffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(vec4) * pointsNum, points, GL_STATIC_DRAW ); // Initialize the vertex position attribute from the vertex shader GLuint loc = glGetAttribLocation( shaderProgram, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); // Second normals buffer // Init normals before copying them to buffer calculateNormals(); glGenBuffers( 1, &nbuffer ); glBindBuffer( GL_ARRAY_BUFFER, nbuffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(vec4) * pointsNum, normals, GL_STATIC_DRAW ); // Initialize the vertex color attribute from the vertex shader GLuint loc2 = glGetAttribLocation( shaderProgram, "vNormal" ); glEnableVertexAttribArray( loc2 ); glVertexAttribPointer( loc2, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); //===================================== }
poSphere3D::poSphere3D( int _numRows, int _numColumns, float _radius ) : poMesh3D(_numRows,_numColumns) { radius = _radius; float dA = 360.f / (float)(numColumns-1); float dB = 180.f / (float)(numRows-1); for( int i=0; i<numRows; i++ ) { for( int j=0; j<numColumns; j++ ) { int N = getVertexIndex(i,j); if ( N==-1 || N < 0 || N >= (int)vertexList.size() ) { printf("ERROR\n"); continue; } float A = -1.f * dA * j; float B = 90 - dB * i; vertexList[N].position.set( cos_deg(B)*cos_deg(A)*radius, sin_deg(B)*radius, cos_deg(B)*sin_deg(A)*radius ); } } calculateNormals(); }
void Heightmap::normalizeHeight() { for(int row = 0; row <= rows; row++) { for(int column = 0; column <= columns; column++) { changeHeightAt(column, row, -averageHeight); } } calculateNormals(); }
/* Define the vertex array that specifies the terrain (x, y) specifies the pixel dimensions of the heightfield (x * y) vertices (xs, ys) specifies the size of the heightfield region */ void terrain_object::createTerrain(GLuint xp, GLuint zp, GLfloat xs, GLfloat zs, GLfloat freq, GLfloat scale) { xsize = xp; zsize = zp; width = xs; height = zs; /* Scale heights in relation to the terrain size */ height_scale = xs; /* Create array of vertices */ GLuint numvertices = xsize * zsize; vertices = new glm::vec3[numvertices]; normals = new glm::vec3[numvertices]; /* First calculate the noise array which we'll use for our vertex height values */ calculateNoise(freq, scale); /* Debug code to check that noise values are sensible */ // for (int i = 0; i < (xsize*zsize*perlin_octaves); i++) // { // printf("\n noise[%d] = %f", i, noise[i]); // } /* Define starting (x,z) positions and the step changes */ GLfloat xpos = -width / 2.f; GLfloat xpos_step = width / GLfloat(xp); GLfloat zpos_step = height / GLfloat(zp); GLfloat zpos_start = -height / 2.f; /* Define the vertex positions and the initial normals for a flat surface */ for (GLuint x = 0; x < xsize; x++) { GLfloat zpos = zpos_start; for (GLuint z = 0; z < zsize; z++) { GLfloat height = noise[(x*zsize + z) * 4+3]; vertices[x*xsize + z] = glm::vec3(xpos, (height-0.5f)*height_scale, zpos); normals[x*xsize + z] = glm::vec3(0, 1.0f, 0); // Normals for a flat surface zpos += zpos_step; } xpos += xpos_step; } /* Define vertices for triangle strips */ for (GLuint x = 0; x < xsize - 1; x++) { GLuint top = x * zsize; GLuint bottom = top + zsize; for (GLuint z = 0; z < zsize; z++) { elements.push_back(top++); elements.push_back(bottom++); } } calculateNormals(); }
void Mesh::createCone(Number height, Number radius, int numSegments) { setMeshType(Mesh::TRI_MESH); Number lastx = -1; Number lastz = -1; for (int i=0 ; i < numSegments+1; i++) { Number pos = ((PI*2.0)/((Number)numSegments)) * i; Number x = sinf(pos) * radius; Number z = cosf(pos) * radius; if(i > 0) { // ie only construct faces one we have vertexes from i-1 to use. Polygon *polygon = new Polygon(); polygon->addVertex(lastx,0,lastz,0,0); polygon->addVertex(x,0,z, 1, 0); polygon->addVertex(0,height,0, 1, 1); addPolygon(polygon); polygon = new Polygon(); polygon->addVertex(x,0,z, 1, 1); polygon->addVertex(lastx,0,lastz, 1, 1); polygon->addVertex(0,0,0,0,0); addPolygon(polygon); } lastx = x; lastz = z; /* Polygon *polygon = new Polygon(); polygon->addVertex(w,0,h, 1, 1); polygon->addVertex(0,0,h, 1, 0); polygon->addVertex(0,0,0,0,0); polygon->addVertex(w,0,0,0,1); addPolygon(polygon); */ } for(int i=0; i < polygons.size(); i++) { for(int j=0; j < polygons[i]->getVertexCount(); j++) { // polygons[i]->getVertex(j)->x = polygons[i]->getVertex(j)->x - (radius/2.0f); polygons[i]->getVertex(j)->y = polygons[i]->getVertex(j)->y - (height/2.0f); // polygons[i]->getVertex(j)->z = polygons[i]->getVertex(j)->z - (radius/2.0f); } } calculateNormals(); calculateTangents(); arrayDirtyMap[RenderDataArray::VERTEX_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::COLOR_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::TEXCOORD_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::NORMAL_DATA_ARRAY] = true; arrayDirtyMap[RenderDataArray::TANGENT_DATA_ARRAY] = true; }
/* ========================================================================= */ void WaterMesh::updateMesh(Real timeSinceLastFrame) { int x, y ; lastFrameTime = timeSinceLastFrame ; lastTimeStamp += timeSinceLastFrame ; // do rendering to get ANIMATIONS_PER_SECOND while(lastAnimationTimeStamp <= lastTimeStamp) { // switch buffer numbers currentBuffNumber = (currentBuffNumber + 1) % 3 ; float *buf = vertexBuffers[currentBuffNumber] + 1 ; // +1 for Y coordinate float *buf1 = vertexBuffers[(currentBuffNumber+2)%3] + 1 ; float *buf2 = vertexBuffers[(currentBuffNumber+1)%3] + 1; /* we use an algorithm from * http://collective.valve-erc.com/index.php?go=water_simulation * The params could be dynamically changed every frame of course */ Real C = PARAM_C; // ripple speed Real D = PARAM_D; // distance Real U = PARAM_U; // viscosity Real T = PARAM_T; // time Real TERM1 = ( 4.0f - 8.0f*C*C*T*T/(D*D) ) / (U*T+2) ; Real TERM2 = ( U*T-2.0f ) / (U*T+2.0f) ; Real TERM3 = ( 2.0f * C*C*T*T/(D*D) ) / (U*T+2) ; for(y=1;y<complexity;y++) { // don't do anything with border values float *row = buf + 3*y*(complexity+1) ; float *row1 = buf1 + 3*y*(complexity+1) ; float *row1up = buf1 + 3*(y-1)*(complexity+1) ; float *row1down = buf1 + 3*(y+1)*(complexity+1) ; float *row2 = buf2 + 3*y*(complexity+1) ; for(x=1;x<complexity;x++) { row[3*x] = TERM1 * row1[3*x] + TERM2 * row2[3*x] + TERM3 * ( row1[3*x-3] + row1[3*x+3] + row1up[3*x]+row1down[3*x] ) ; } } lastAnimationTimeStamp += (1.0f / ANIMATIONS_PER_SECOND); } if (useFakeNormals) { calculateFakeNormals(); } else { calculateNormals(); } // set vertex buffer posVertexBuffer->writeData(0, posVertexBuffer->getSizeInBytes(), // size vertexBuffers[currentBuffNumber], // source true); // discard? }
void rawReader::rotate(const float degrees, const vec3& axis) { mat3 R = Transform::rotate(degrees, axis); for(unsigned int m = 0; m < vertices.size(); m++){ vertices[m] = vertices[m] * R; } calculateNormals(); }
void Cube::init() { generateBuffers(); centre = glm::vec3(0, 0, 0); width = 0.2; height = 0.2; vertices.resize(8); colors.resize(8); normals.resize(8); // Vertices are // On the y = -0.1 plane, On the y = 0.1 plane // v2 - v3 v6 - v7 // v1 - v0 v5 - v4 //Eight vertices of the cube vertices[0] = glm::vec3(-0.1, -0.1, -0.1); vertices[1] = glm::vec3(0.1, -0.1, -0.1); vertices[2] = glm::vec3(0.1, -0.1, 0.1); vertices[3] = glm::vec3(-0.1, -0.1, 0.1); vertices[4] = glm::vec3(-0.1, 0.1, -0.1); vertices[5] = glm::vec3(0.1, 0.1, -0.1); vertices[6] = glm::vec3(0.1, 0.1, 0.1); vertices[7] = glm::vec3(-0.1, 0.1, 0.1); // 12 Triangles, 3 vertices indices.reserve(36); indexVec3.push_back(glm::vec3(0, 1, 2)); indexVec3.push_back(glm::vec3(0, 2, 3)); indexVec3.push_back(glm::vec3(4, 5, 6)); indexVec3.push_back(glm::vec3(4, 6, 7)); indexVec3.push_back(glm::vec3(0, 3, 4)); indexVec3.push_back(glm::vec3(3, 4, 7)); indexVec3.push_back(glm::vec3(1, 2, 5)); indexVec3.push_back(glm::vec3(2, 5, 6)); indexVec3.push_back(glm::vec3(2, 6, 7)); indexVec3.push_back(glm::vec3(2, 3, 7)); indexVec3.push_back(glm::vec3(1, 4, 5)); indexVec3.push_back(glm::vec3(0, 1, 4)); for (unsigned int i = 0; i < indexVec3.size(); i++) { indices.push_back(indexVec3.at(i).x); indices.push_back(indexVec3.at(i).y); indices.push_back(indexVec3.at(i).z); } calculateNormals(); // 12 triangles for a cube primitivePar.setValues(GL_TRIANGLES, 0, indices.size()); updateBuffers(); }
void Disk::initializeCone(const float yValue) { //top point of cone points[index][0] = 0.0; points[index][1] = yValue; points[index][2] = 0.0; //points[index][3] = 1.0; normals[index][0] = 0.0; normals[index][1] = 0.0; normals[index][2] = 0.0; index++; float theta; size_t tIndices = 0; for (size_t i = 0; i < NumConePoints; ++i, index++) { theta = static_cast<float>(i*20.0f*kPI / 180.0f); points[index][0] = 10 * cos(theta); points[index][1] = yValue; points[index][2] = 10 * -sin(theta); //points[index][3] = 1.0; normals[index][0] = 0.0; normals[index][1] = 0.0; normals[index][2] = 0.0; if (i <= (NumConePoints - 2)) { indices[tIndices] = 0u; tIndices++; indices[tIndices] = index; tIndices++; indices[tIndices] = index + 1; tIndices++; } //last triangle else { indices[tIndices] = 0u; tIndices++; indices[tIndices] = index; tIndices++; indices[tIndices] = 1u; tIndices++; } } calculateNormals(); }
// Constructor ConvexMesh::ConvexMesh(const openglframework::Vector3 &position, reactphysics3d::CollisionWorld* world, const std::string& meshPath) : openglframework::Mesh(), mVBOVertices(GL_ARRAY_BUFFER), mVBONormals(GL_ARRAY_BUFFER), mVBOTextureCoords(GL_ARRAY_BUFFER), mVBOIndices(GL_ELEMENT_ARRAY_BUFFER) { // Load the mesh from a file openglframework::MeshReaderWriter::loadMeshFromFile(meshPath, *this); // Calculate the normals of the mesh calculateNormals(); // Initialize the position where the sphere will be rendered translateWorld(position); // Compute the scaling matrix mScalingMatrix = openglframework::Matrix4::identity(); // Vertex and Indices array for the triangle mesh (data in shared and not copied) mPhysicsTriangleVertexArray = new rp3d::TriangleVertexArray(getNbVertices(), &(mVertices[0]), sizeof(openglframework::Vector3), getNbFaces(0), &(mIndices[0][0]), sizeof(int), rp3d::TriangleVertexArray::VERTEX_FLOAT_TYPE, rp3d::TriangleVertexArray::INDEX_INTEGER_TYPE); // Create the collision shape for the rigid body (convex mesh shape) and // do not forget to delete it at the end mConvexShape = new rp3d::ConvexMeshShape(mPhysicsTriangleVertexArray); // Initial position and orientation of the rigid body rp3d::Vector3 initPosition(position.x, position.y, position.z); rp3d::Quaternion initOrientation = rp3d::Quaternion::identity(); rp3d::Transform transform(initPosition, initOrientation); mPreviousTransform = transform; // Create a rigid body corresponding to the sphere in the dynamics world mBody = world->createCollisionBody(transform); // Add a collision shape to the body and specify the mass of the collision shape mProxyShape = mBody->addCollisionShape(mConvexShape, rp3d::Transform::identity()); // Create the VBOs and VAO createVBOAndVAO(); mTransformMatrix = mTransformMatrix * mScalingMatrix; }
// Constructor Sphere::Sphere(float radius, const openglframework::Vector3 &position, float mass, reactphysics3d::DynamicsWorld* world, const std::string& meshFolderPath) : openglframework::Mesh(), mRadius(radius) { // Load the mesh from a file openglframework::MeshReaderWriter::loadMeshFromFile(meshFolderPath + "sphere.obj", *this); // Calculate the normals of the mesh calculateNormals(); // Compute the scaling matrix mScalingMatrix = openglframework::Matrix4(mRadius, 0, 0, 0, 0, mRadius, 0, 0, 0, 0, mRadius, 0, 0, 0, 0, 1); // Initialize the position where the sphere will be rendered translateWorld(position); // Create the collision shape for the rigid body (sphere shape) // ReactPhysics3D will clone this object to create an internal one. Therefore, // it is OK if this object is destroyed right after calling RigidBody::addCollisionShape() mCollisionShape = new rp3d::SphereShape(mRadius); // Initial position and orientation of the rigid body rp3d::Vector3 initPosition(position.x, position.y, position.z); rp3d::Quaternion initOrientation = rp3d::Quaternion::identity(); rp3d::Transform transform(initPosition, initOrientation); // Create a rigid body corresponding to the sphere in the dynamics world rp3d::RigidBody* body = world->createRigidBody(transform); // Add a collision shape to the body and specify the mass of the shape mProxyShape = body->addCollisionShape(mCollisionShape, rp3d::Transform::identity(), mass); mBody = body; mTransformMatrix = mTransformMatrix * mScalingMatrix; // Create the VBOs and VAO if (totalNbSpheres == 0) { createVBOAndVAO(); } totalNbSpheres++; }
void Segmenter::createTrainFile() { if( (!have_cloud) || (!have_cloud_l) ) { char* error_message = new char[200]; sprintf(error_message,"[%s::segment()]: I suggest you first set the point cloud.",ClassName.c_str()); // and normals throw std::runtime_error(error_message); } calculateNormals(); calculatePatches(); // v4r::View view; view.Reset(); view.setPointCloud(pcl_cloud); view.normals = normals; view.setSurfaces(surfaces); surfaces = view.surfaces; view.createPatchImage(); view.computeNeighbors(); surfaces = view.surfaces; view.calculateBorders(view.cloud); ngbr3D_map = view.ngbr3D_map; ngbr2D_map = view.ngbr2D_map; preComputeRelations(); initModelSurfaces(); modelSurfaces(); computeRelations(); addGroundTruth.setInputCloud(pcl_cloud_l); addGroundTruth.setSurfaces(surfaces); addGroundTruth.setRelations(validRelations); addGroundTruth.compute(v4r::STRUCTURAL_RELATIONS); surfaces = addGroundTruth.getSurfaces(); validRelations = addGroundTruth.getRelations(); svmFileCreator.setSurfaces(surfaces); svmFileCreator.setRelations(validRelations); svmFileCreator.setAnalyzeOutput(false); svmFileCreator.setFeatureNumber(-1); svmFileCreator.setFilenameBase(train_ST_file_name); svmFileCreator.setFilenameAsBase(train_AS_file_name); svmFileCreator.process(); }
void Cube::setDepth(double depth) { glm::vec3 offset; offset.z = (depth - (vertices[2].z - vertices[1].z)) * 0.5; vertices[0] -= offset; vertices[1] -= offset; vertices[4] -= offset; vertices[5] -= offset; vertices[2] += offset; vertices[3] += offset; vertices[6] += offset; vertices[7] += offset; calculateNormals(); updateBuffers(); }
void Cube::setHeight(double height) { glm::vec3 offset; offset.y = (height - (vertices[4].y - vertices[0].y)) * 0.5; vertices[0] -= offset; vertices[1] -= offset; vertices[2] -= offset; vertices[3] -= offset; vertices[4] += offset; vertices[5] += offset; vertices[6] += offset; vertices[7] += offset; calculateNormals(); updateBuffers(); }
// Constructor Cylinder::Cylinder(float radius, float height, const openglframework::Vector3& position, float mass, reactphysics3d::DynamicsWorld* dynamicsWorld, const std::string& meshFolderPath) : openglframework::Mesh(), mRadius(radius), mHeight(height) { // Load the mesh from a file openglframework::MeshReaderWriter::loadMeshFromFile(meshFolderPath + "cylinder.obj", *this); // Calculate the normals of the mesh calculateNormals(); // Compute the scaling matrix mScalingMatrix = openglframework::Matrix4(mRadius, 0, 0, 0, 0, mHeight, 0, 0, 0, 0, mRadius, 0, 0, 0, 0, 1); // Initialize the position where the cylinder will be rendered translateWorld(position); // Create the collision shape for the rigid body (cylinder shape) and do // not forget to delete it at the end mCylinderShape = new rp3d::CylinderShape(mRadius, mHeight); // Initial position and orientation of the rigid body rp3d::Vector3 initPosition(position.x, position.y, position.z); rp3d::Quaternion initOrientation = rp3d::Quaternion::identity(); rp3d::Transform transform(initPosition, initOrientation); // Create a rigid body corresponding to the cylinder in the dynamics world rp3d::RigidBody* body = dynamicsWorld->createRigidBody(transform); // Add a collision shape to the body and specify the mass of the shape mProxyShape = body->addCollisionShape(mCylinderShape, rp3d::Transform::identity(), mass); mTransformMatrix = mTransformMatrix * mScalingMatrix; mBody = body; // Create the VBOs and VAO if (totalNbCylinders == 0) { createVBOAndVAO(); } totalNbCylinders++; }
void Cone::create(int subdivision) { // Center and Top vertices vertices.push_back(Vector3d(0,0,0)); //center vertex vertices.push_back(Vector3d(0,0,1)); //top vertex // Circle vertices double dTheta = 2.0 * M_PI / (5.0 + subdivision); double theta = 0; for(int i = 0; i < 5+subdivision; i++) { vertices.push_back(Vector3d(cos(theta), sin(theta), 0)); theta = theta + dTheta; } // Indices / Triangles for(int i = 0; i < 5 + subdivision; i++) { indices.push_back(0); if(i != 4 + subdivision) { indices.push_back(i+3); } else { indices.push_back(2); } indices.push_back(i+2); indices.push_back(1); indices.push_back(i+2); if(i != 4 + subdivision) { indices.push_back(i+3); } else { indices.push_back(2); } triangleCount = triangleCount + 2; } calculateNormals(); }
poCube3D::poCube3D( float W, float H, float D ) { cubeWidth = W; cubeHeight = H; cubeDepth = D; // front vertices int FTL = addVertex( poPoint(0,0,0) ); int FTR = addVertex( poPoint(W,0,0) ); int FBR = addVertex( poPoint(W,H,0) ); int FBL = addVertex( poPoint(0,H,0) ); // back vertices int BTL = addVertex( poPoint(0,0,D) ); int BTR = addVertex( poPoint(W,0,D) ); int BBR = addVertex( poPoint(W,H,D) ); int BBL = addVertex( poPoint(0,H,D) ); // front face addTriangle( FTL, FTR, FBR ); addTriangle( FBR, FBL, FTL ); // back face addTriangle( BTL, BTR, BBR ); addTriangle( BBR, BBL, BTL ); // left face addTriangle( FTL, BTL, FBL ); addTriangle( BBL, FBL, BTL ); // right face addTriangle( FTR, BTR, FBR ); addTriangle( BBR, FBR, BTR ); // top face addTriangle( FTL, FTR, BTL ); addTriangle( BTR, FTR, BTL ); // bottom face addTriangle( FBL, FBR, BBL ); addTriangle( BBR, FBR, BBL ); calculateNormals(); }
void LightWaveParser::loadModel(string fname) { in.open(fname.c_str(), ios::in | ios::binary); if (!in.good()) { fprintf(stderr, "Lightwave Parser: Error opening %s\n", fname.c_str()); return ; } string chunkID = readChunkID(in, 4); int size = readIntBE(in); int count = 0; readChunkID(in, 4); // read LWO2 count += 4; while(count < size) { chunkID = readChunkID(in, 4); count += 4; fprintf(stderr, "ID = %s\n", chunkID.c_str()); if(chunkID == "TAGS") { count += parseTags(); } else if(chunkID == "PNTS") { count += parsePoints(); } else if(chunkID == "POLS") { count += parsePolygons(); } else if(chunkID == "PTAG") { parsePTag(); } else if(chunkID == "SURF") { parseSurface(); } else { count += skipChunk(); } } in.close(); calculateNormals(); setupCells(); }
void Cube::setWidth(double width, const glm::vec3& offset) { glm::vec3 widthOffset; widthOffset.x = (width - (vertices[1].x - vertices[0].x)) * 0.5; //widthOffset += offset; vertices[1] = vertices[1] + widthOffset + offset; vertices[2] = vertices[2] + widthOffset + offset; vertices[5] = vertices[5] + widthOffset + offset; vertices[6] = vertices[6] + widthOffset + offset; vertices[0] = vertices[0] - widthOffset + offset; vertices[3] = vertices[3] - widthOffset + offset; vertices[4] = vertices[4] - widthOffset + offset; vertices[7] = vertices[7] - widthOffset + offset; calculateNormals(); updateBuffers(); }
std::vector<std::shared_ptr<Mesh>> Mesh::createSphere() { auto m = std::shared_ptr<Mesh>(new Mesh()); int stacks = 100; int slices = 100; float radius = 1.0; for (int i = 0; i <= stacks; ++i) { float V = i / (float)stacks; float phi = V * glm::pi <float>(); for (int j = 0; j <= slices; ++j) { float U = j / (float)slices; float theta = U * (glm::pi <float>() * 2); float x = cosf(theta) * sinf(phi); float y = cosf(phi); float z = sinf(theta) * sinf(phi); m->vertices.push_back({ glm::vec3(x, y, z) * radius }); } } for (int i = 0; i < slices * stacks + slices; ++i) { m->indices.push_back(i); m->indices.push_back(i + slices + 1); m->indices.push_back(i + slices); m->indices.push_back(i + slices + 1); m->indices.push_back(i); m->indices.push_back(i + 1); } m->calculateNormals(); m->setupArrays(); return { m }; }
/** * init opens and parses the raw file "filename". * .raw files consist of lines as such: * f1 f2 f3 f4 f5 f6 f7 f8 f9 * These are all floats, where each triplet specifies one vertice of the triangle (to be read as: * v1: (f1, f2, f3); v2: (f4, f5, f6); v3: (f7, f8, f9) * init populates class variable vertices with this information */ int rawReader::init(const char* filename){ std::string str = "" ; plint = true; // open .raw file std::cout << "Reading .raw file " << filename << std::endl; std::ifstream in ; in.open(filename) ; if (!in.is_open()) { std::cerr << "Unable to open file " << filename << "\n" ; return 1 ; } // parse .raw file while(in){ getline(in, str); if(str.empty()){ // do nothing } // read and store vertices else{ float x1,y1,z1; float x2,y2,z2; float x3,y3,z3; sscanf(str.c_str(), "%f %f %f %f %f %f %f %f %f", &x1, &y1, &z1, &x2, &y2, &z2, &x3, &y3, &z3); vec3 vertex1(x1,y1,z1); vec3 vertex2(x2,y2,z2); vec3 vertex3(x3,y3,z3); vertices.push_back(vertex1); vertices.push_back(vertex2); vertices.push_back(vertex3); } } calculateNormals(); std::cout << ".raw file read successful" << std::endl; return 0; }
void CalPhysique::update() { // get the attached meshes vector std::vector<CalMesh *>& vectorMesh = m_pModel->getVectorMesh(); // loop through all the attached meshes std::vector<CalMesh *>::iterator iteratorMesh; for(iteratorMesh = vectorMesh.begin(); iteratorMesh != vectorMesh.end(); ++iteratorMesh) { // get the submesh vector of the mesh std::vector<CalSubmesh *>& vectorSubmesh = (*iteratorMesh)->getVectorSubmesh(); // loop through all the submeshes of the mesh std::vector<CalSubmesh *>::iterator iteratorSubmesh; for(iteratorSubmesh = vectorSubmesh.begin(); iteratorSubmesh != vectorSubmesh.end(); ++iteratorSubmesh) { // check if the submesh handles vertex data internally if((*iteratorSubmesh)->hasInternalData()) { // calculate the transformed vertices and store them in the submesh std::vector<CalVector>& vectorVertex = (*iteratorSubmesh)->getVectorVertex(); calculateVertices(*iteratorSubmesh, (float *)&vectorVertex[0]); // calculate the transformed normals and store them in the submesh std::vector<CalVector>& vectorNormal = (*iteratorSubmesh)->getVectorNormal(); calculateNormals(*iteratorSubmesh, (float *)&vectorNormal[0]); unsigned mapId; for(mapId=0;mapId< (*iteratorSubmesh)->getVectorVectorTangentSpace().size();mapId++) { if((*iteratorSubmesh)->isTangentsEnabled(mapId)) { std::vector<CalSubmesh::TangentSpace>& vectorTangentSpace = (*iteratorSubmesh)->getVectorVectorTangentSpace()[mapId]; calculateTangentSpaces(*iteratorSubmesh, mapId,(float *)&vectorTangentSpace[0]); } } } } } }
void Heightmap::loadHeightmap(string filename, float strength) { TextureLoader tl; Texture t = tl.loadTexture(filename, 1); if(t.getWidth() < columns || t.getHeight() < rows) { cout << "The provided file " << filename << " (" << t.getWidth() << "x" << t.getHeight() << ") is too small and cannot be used for this heightmap (" << columns << "x" << rows << ")" << endl; return; } int dx = t.getWidth()/columns; int dy = t.getHeight()/rows; for(int row = 0; row <= rows; row++) { for(int column = 0; column <= columns; column++) { setHeightAt(column, row, (t.getData()[row * t.getWidth() * dy + column * dx] / 255.0f) * strength); //assert(0.0f <= getHeightAt(column, row) && getHeightAt(column, row) <= strength); } } calculateNormals(); }
void MeditParser::readMesh(string fname) { ifstream fp(fname.c_str(), ios::in); fprintf(stderr, "failbit = %d\n", fp.fail()); string line; // while(line != "Vertices") { // fp >> line; // } int count; double x, y, z; int i; fp >> count; for (int vidx = 0; vidx < count; vidx++) { fp >> x >> y >> z >> i; addPoint(new Point3D(x, y, z)); } std::string shape; fp >> shape; bool done = false; while (!done) { if (shape == "End") { done = true; } else { fp >> count; if (shape == "Triangles") { readTriangles(count, fp); } else if (shape == "Quadrilaterals") { } } fp >> shape; } fp.close(); calculateNormals(); }