Skip to content

Instantly share code, notes, and snippets.

@ialhashim
Created April 24, 2014 05:41
Show Gist options
  • Save ialhashim/11242782 to your computer and use it in GitHub Desktop.
Save ialhashim/11242782 to your computer and use it in GitHub Desktop.
A Capped 3D Cylinder geoemtry in C++
std::vector<Vector3> spine, spineNormals;
for(int i = 0; i < 10 ; i++){
spine.push_back( Vector3(0,0,0.1 * i) );
#define DEG2RAD 0.01745329
double theta = DEG2RAD * double(i) * M_PI * 2;
spineNormals.push_back(rotatedVec(Vector3(0,0.01,0),theta, Vector3(0,0,1)));
}
// Generate capped cylinder
int numSides = 20, numCaps = numSides * 0.5;
std::vector< std::vector<Vector3> > cylinder;
{
for(size_t i = 0; i < spine.size(); i++)
{
std::vector<Vector3> circle, cap;
Vector3 axis = (i == 0) ? spine[1] - spine[0] : (i+1 == spine.size()) ? spine.back() - spine[spine.size() - 2] : spine[i+1] - spine[i];
axis.normalize();
// First cap
if(i == 0){
for(int sj = 0; sj + 1 < numCaps; sj++){
cap.clear();
for(int si = 0; si < numSides; si++){
double t = double(si) / (numSides-1);
double theta = t * M_PI * 2.0;
double s = std::max(1e-8, (double(sj)/(numCaps-1)));
cap.push_back( spine[i] + rotatedVec(Vector3(s * spineNormals[i]), theta, axis) );
}
cylinder.push_back(cap);
}
}
// Regular
for(int si = 0; si < numSides; si++)
{
double t = double(si) / (numSides-1);
double theta = t * M_PI * 2.0;
circle.push_back( spine[i] + rotatedVec(spineNormals[i], theta, axis) );
}
cylinder.push_back(circle);
// End cap
if(i == spine.size() - 1){
for(int sj = 1; sj < numCaps; sj++){
cap.clear();
for(int si = 0; si < numSides; si++){
double t = double(si) / (numSides-1);
double theta = t * M_PI * 2.0;
double s = std::max(1e-8, 1.0 - (double(sj)/(numCaps-1)));
cap.push_back( spine[i] + rotatedVec(Vector3(s * spineNormals[i]), theta, axis) );
}
cylinder.push_back(cap);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment