I create a simple heightfield type mesh, initially constant z(x,y), then modify a small rectangular area to experiment with perspective parameters. With this code block inside setup(), the little raised area is shown in draw(). But – and this makes me wonder about my sanity – when I package the identical code in a function which is called at the same point in setup() where the inline code was (now commented out) the draw() loop does not show the “bump”.
Further (in)sanity check: near the end of setup() is a function call to setNormals(mesh) which I have copied out of the book “Mastering openFrameworks”. This function call appears to work as you would expect!
int numVertsX = 100;
int numVertsY = 50;
int Z = 10; // Initial field height. Later subject field to "ripples".
int Skip = 10; // Spacing between vertices.
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofEnableDepthTest(); // Z-buffering
// Create mesh
for (int y = 0; y < numVertsY; y++) {
for (int x = 0; x < numVertsX; x++) {
ofPoint p = ofPoint(x * Skip, y * Skip, Z);
mesh.addVertex(p);
mesh.addColor(darkSeaGreen);
}
}
// Set up triangles' indices
for (int y = 0; y < numVertsY - 1; y++) {
for (int x = 0; x < numVertsX - 1; x++) {
int i1 = x + numVertsX * y;
int i2 = x + 1 + numVertsX * y;
int i3 = x + numVertsX * (y + 1);
int i4 = x + 1 + numVertsX * (y + 1);
mesh.addTriangle(i1, i2, i3); // e.g. (0,0)-->(1,0)-->(0,1)
mesh.addTriangle(i2, i4, i3); // and (1,0)-->(1,1)-->(0,1)
}
}
// Perturb mesh beginning at vertex (offsetX, offsetY)
// with rectangle dX-by-dY and dZ high
/**/
int offsetX = 5;
int offsetY = 5;
int dX = 10;
int dY = 10;
int dZ = 40;
//tweakMesh(mesh, offsetX, offsetY, dX, dY, dZ);
// Modify mesh here:
/**/
for (int y = offsetX; y <= (offsetX + dY); y++) {
for (int x = offsetX; x <= (offsetX + dX); x++) {
int index = x + y * numVertsX;
ofVec3f v = mesh.getVertex(index);
v.z += dZ;
mesh.setVertex(index, v);
mesh.setColor(index, red);
cout << "at (" << x << "," << y << ") z becomes " << v.z << endl;
}
}
/**/
setNormals(mesh);
// Place mesh in middle of window
meshOffset.x = (ofGetWidth() - numVertsX * Skip) / 2.;
meshOffset.y = (ofGetHeight() - numVertsY * Skip) / 2.;
// Reports:
showMeshParams(numVertsX, numVertsY, Skip);
showCameraProps(cam);
}
Here’s the function with same tweaking as inline version:
void tweakMesh(ofMesh mesh, int offsetX, int offsetY, int dX, int dY, int dZ) {
for (int y = offsetX; y <= (offsetX + dY); y++) {
for (int x = offsetX; x <= (offsetX + dX); x++) {
int index = x + y * numVertsX;
ofVec3f v = mesh.getVertex(index);
v.z += dZ;
mesh.setVertex(index, v);
mesh.setColor(index, red);
cout << "at (" << x << "," << y << ") z becomes " << v.z << endl;
}
}
}
I would appreciate any input including psychotherapist referral.