Quantcast
Channel: openFrameworks - Latest posts
Viewing all articles
Browse latest Browse all 40524

Recalculate normals after transformation

$
0
0

Hello, I'm applying 2 transformation on a ofCylinderPrimitive, getting its vertices and adding them into a mesh. I've some trouble recalculating the normals (i need them later in the shaders because i want to calculate the light that the material should reflects).
This is my actual code:

// .h file
    ofCylinderPrimitive root;
    ofLight light;
    ofVboMesh finalMesh;
    ofShader  shader;

// .cpp
void ofApp::setup(){
    ofSetVerticalSync(true);
    ofEnableDepthTest();
    //light
    light.setPosition(500, 500, 500);
    light.enable();
    
    //mesh
    finalMesh.setMode(OF_PRIMITIVE_TRIANGLES);
    finalMesh.enableColors();
    
    //shader, not used at the moment
    //shader.load("shaders_gl3/render.vert", "shaders_gl3/render.frag");
    
    // root
    root.set(branchDimension, branchLenght, radiusSegments, heightSegments, capSegments, false, OF_PRIMITIVE_TRIANGLES);
    root.setPosition(0, 0, 0);
    root.dolly(branchLenght/2);
    root.tilt(90);
    ofMatrix4x4 normalMatrix = root.getGlobalTransformMatrix().getInverse();
    for(auto v: root.getMesh().getVertices()){
        finalMesh.addVertex(v * root.getGlobalTransformMatrix());
    }
    for(auto i: root.getMesh().getIndices()){
        finalMesh.addIndex(i);
    }
    for(auto i: root.getMesh().getNormals()){
        ofVec3f normalVector = (i * normalMatrix).normalize();
        finalMesh.addNormal(normalVector);
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
    cam.begin();
            drawNormals(10.00);
    cam.end();
}

void ofApp::drawNormals(float size){
    for (int i = 0; i < finalMesh.getNumVertices(); ++i){
        ofVec3f vertex = finalMesh.getVertex(i);
        ofVec3f normal = finalMesh.getNormal(i);
        ofPushStyle();
        ofSetColor(255, 0, 255);
        ofDrawLine(vertex, vertex + size * normal);
        ofPopStyle();
    }
}

As you see in this screenshot, the normals of this vertical cylinder are wrong, they are always parallel to the y axis

P.S. This post is the following of another one, but the title of the previous one has nothing to do with what is now my current issue.


Viewing all articles
Browse latest Browse all 40524

Trending Articles