根据空间线上的两点生成圆柱体 算法
// 根据线上的起点和终点pt0,pt1,计算形成的圆柱体的顶点和法线数组
void computeCylinderVertexs(osg::Vec3d pt0, osg::Vec3d pt1, double radius, osg::Vec3dArray* vts, osg::Vec3Array* nors)
{
osg::Vec3d dir = pt0 - pt1;
dir.normalize();
// 计算平面(pt0,dir)上的一点ptPlane, (pt0,ptPlane)矢量planeDir与dir垂直
double xx,yy,zz;
if (fabs(dir.z()) > 0.001)
{
xx = pt0.x() + 10;
yy = pt0.y();
zz = -(dir.x()*(xx-pt0.x())+dir.y()*(yy-pt0.y()))/dir.z() + pt0.z();
}
else if (dir.x() != 0)
{
yy = pt0.y() + 10;
zz = pt0.z();
xx = -(dir.y()*(yy-pt0.y())+dir.z()*(zz-pt0.z()))/dir.x() + pt0.x();
}
else
{
xx = pt0.x() +10;
zz = pt0.z();
yy = -(dir.x()*(xx-pt0.x())+dir.z()*(zz-pt0.z()))/dir.y() + pt0.y();
}
osg::Vec3d planeDir(xx-pt0.x(),yy-pt0.y(),zz-pt0.z());
planeDir.normalize();
// 按一定弧度实现矢量planeDir绕dir旋转得到矢量A
osg::Matrixd mt;
int edges = 18; //360/20
for (int k = 0; k < edges; k++)
{
mt.makeRotate(osg::DegreesToRadians(k*360.0/edges),dir);
osg::Vec3d newrotDir = planeDir * mt;
newrotDir.normalize();
osg::Vec3d newPt0 = pt0 + newrotDir * radius; // 上顶面顶点
osg::Vec3d newPt1 = pt1 + newrotDir * radius; // 下底面顶点
osg::Vec3d nor0 = newPt0-pt0;
nor0.normalize();
vts->push_back(newPt0);
nors->push_back(nor0);
vts->push_back(newPt1);
nors->push_back(nor0);
}
vts->push_back(vts->at(0));
nors->push_back(nors->at(0));
vts->push_back(vts->at(1));
nors->push_back(nors->at(1));
}