osg示例解析之osganimationmorph(1)
本课主要演示了osgAnimation中的变形动画,变形动画通常也称为逐顶点动画(Per-vertex Animation),是一种三维动画的表现形式。它对计算机的运算资源的消耗很大,通常以每帧计算和应用4000~9000个顶点的位置变化为宜,否则系统难以承受其他场景对象的更新和渲染工作。变形动画在osgAnimation中通过MorphGeometry以及UpdateMorph来实现,具体的实现可以参考我的另一篇文章osgAnimation之作用对象中的相关介绍。
该例子首先实现了一个NodeVisitor,用来寻找Geode节点中的Geometry对象:
- struct GeometryFinder : public osg::NodeVisitor
- {
- osg::ref_ptr<osg::Geometry> _geom;
- GeometryFinder() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
- void apply(osg::Geode& geode)
- {
- if (_geom.valid())
- return;
- for (unsigned int i = 0; i < geode.getNumDrawables(); i++)
- {
- osg::Geometry* geom = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));
- if (geom) {
- _geom = geom;
- return;
- }
- }
- }
- };
- osg::ref_ptr<osg::Geometry> getShape(const std::string& name)
- {
- osg::ref_ptr<osg::Node> shape0 = osgDB::readNodeFile(name);
- if (shape0)
- {
- GeometryFinder finder;
- shape0->accept(finder);
- return finder._geom;
- }
- else
- {
- return NULL;
- }
- }
下面我们看看主函数中的实现过程,应该来说还是比较清晰的:
- 首先创建频道
- osgAnimation::Animation* animation = new osgAnimation::Animation;
- osgAnimation::FloatLinearChannel* channel0 = new osgAnimation::FloatLinearChannel;
- channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(0,0.0));
- channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(1,1.0));
- channel0->setTargetName("MorphNodeCallback");
- channel0->setName("0");
- 其次创建动画和动画管理器
- animation->addChannel(channel0);
- animation->setName("Morph");
- animation->computeDuration();
- animation->setPlayMode(osgAnimation::Animation::PPONG);
- osgAnimation::BasicAnimationManager* bam = new osgAnimation::BasicAnimationManager;
- bam->registerAnimation(animation);
- 再次 创建需要变形的几何体和目标几何体
- osg::ref_ptr<osg::Geometry> geom0 = getShape("morphtarget_shape0.osg");
- if (!geom0) {
- std::cerr << "can't read morphtarget_shape0.osg" << std::endl;
- return 0;
- }
- osg::ref_ptr<osg::Geometry> geom1 = getShape("morphtarget_shape1.osg");
- if (!geom1) {
- std::cerr << "can't read morphtarget_shape1.osg" << std::endl;
- return 0;
- }
- //原始形状
- osgAnimation::MorphGeometry* morph = new osgAnimation::MorphGeometry(*geom0);
- //需要变形的形状添加到morph之中,可以是多个,结果将按权重加成
- morph->addMorphTarget(geom1.get());
- 最后 将UpdateMorph添加到Geode之中
- osg::Geode* geode = new osg::Geode;
- geode->addDrawable(morph);
- geode->addUpdateCallback(new osgAnimation::UpdateMorph("MorphNodeCallback"));
这样保证在进入MorphGeometry的Drawable更新回调之前先进入Geode的回调中更新几何体的权值,保证后续顶点的计算用到频道里面最新插值出的权值。
运行结果:
写在后面:在后续的osgNeHe课程中Lesson25会根据顶点进行变形,可以参考本课的实现利用osgAnimation库来实现,在实现过程中我遇到以下的问题:
当绘制的几何体为osg::PrimitiveSet::POINTS时程序会崩溃,描述和osgChina中的帖子类似。后来经过查看发现是由于没有NormalArray导致的问题,解决方法是申请一个法线向量的数组,随便设置一下添加到Geometry就可以解决这个问题了。这可能是osgAnimation代码中的一个Bug,osgAnimation要求必须有NormalArray。