root/OpenSceneGraph/trunk/examples/osgprerendercubemap/osgprerendercubemap.cpp @ 4713

Revision 4713, 13.8 kB (checked in by robert, 9 years ago)

Added the support in AnimationPathCallback? for taking a pivot, axis and rotation rate
paramters in its constructor to allow it to be used to create rotations around a point.
This provides the same interface and functionality as osgUtil::TransformCallback? but
has the advantage and AnimationPathCallback? is fully supported by the .osg and .ive file formats.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/Viewer>
2
3#include <osg/Projection>
4#include <osg/Geometry>
5#include <osg/Texture>
6#include <osg/TexGen>
7#include <osg/Geode>
8#include <osg/ShapeDrawable>
9#include <osg/PolygonOffset>
10#include <osg/CullFace>
11#include <osg/TextureCubeMap>
12#include <osg/TexMat>
13#include <osg/MatrixTransform>
14#include <osg/Light>
15#include <osg/LightSource>
16#include <osg/PolygonOffset>
17#include <osg/CullFace>
18#include <osg/Material>
19#include <osg/RefNodePath>
20#include <osg/PositionAttitudeTransform>
21
22#include <osg/CameraNode>
23#include <osg/TexGenNode>
24
25using namespace osg;
26
27
28ref_ptr<Group> _create_scene()
29{
30  ref_ptr<Group> scene = new Group;
31  ref_ptr<Geode> geode_1 = new Geode;
32  scene->addChild(geode_1.get());
33
34  ref_ptr<Geode> geode_2 = new Geode;
35  ref_ptr<MatrixTransform> transform_2 = new MatrixTransform;
36  transform_2->addChild(geode_2.get());
37  transform_2->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f)));
38  scene->addChild(transform_2.get());
39
40  ref_ptr<Geode> geode_3 = new Geode;
41  ref_ptr<MatrixTransform> transform_3 = new MatrixTransform;
42  transform_3->addChild(geode_3.get());
43  transform_3->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f)));
44  scene->addChild(transform_3.get());
45
46  const float radius = 0.8f;
47  const float height = 1.0f;
48  ref_ptr<TessellationHints> hints = new TessellationHints;
49  hints->setDetailRatio(2.0f);
50  ref_ptr<ShapeDrawable> shape;
51
52  shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get());
53  shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f));
54  geode_1->addDrawable(shape.get());
55
56
57  shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
58  shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f));
59  geode_2->addDrawable(shape.get());
60
61  shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
62  shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f));
63  geode_2->addDrawable(shape.get());
64
65  shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get());
66  shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f));
67  geode_2->addDrawable(shape.get());
68
69  shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get());
70  shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f));
71  geode_2->addDrawable(shape.get());
72
73  shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get());
74  shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f));
75  geode_3->addDrawable(shape.get());
76
77  // material
78  ref_ptr<Material> matirial = new Material;
79  matirial->setColorMode(Material::DIFFUSE);
80  matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1));
81  matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
82  matirial->setShininess(Material::FRONT_AND_BACK, 64.0f);
83  scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON);
84
85  return scene;
86}
87
88osg::RefNodePath createReflector()
89{
90  ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform;
91  pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
92  pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f)));
93 
94  ref_ptr<Geode> geode_1 = new Geode;
95  pat->addChild(geode_1.get());
96
97  const float radius = 0.8f;
98  ref_ptr<TessellationHints> hints = new TessellationHints;
99  hints->setDetailRatio(2.0f);
100  ref_ptr<ShapeDrawable> shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get());
101  shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f));
102  geode_1->addDrawable(shape.get());
103 
104  osg::RefNodePath refNodeList;
105  refNodeList.push_back(pat.get());
106  refNodeList.push_back(geode_1.get());
107 
108  return refNodeList;
109}
110
111class UpdateCameraAndTexGenCallback : public osg::NodeCallback
112{
113    public:
114   
115        typedef std::vector< osg::ref_ptr<osg::CameraNode> >  CameraList;
116
117        UpdateCameraAndTexGenCallback(osg::RefNodePath& reflectorNodePath, CameraList& cameraNodes):
118            _reflectorNodePath(reflectorNodePath),
119            _cameraNodes(cameraNodes)
120        {
121        }
122       
123        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
124        {
125            // first update subgraph to make sure objects are all moved into postion
126            traverse(node,nv);
127
128            // compute the position of the center of the reflector subgraph
129            osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath);
130            osg::BoundingSphere bs = _reflectorNodePath.back()->getBound();
131            osg::Vec3 position = bs.center();
132
133            typedef std::pair<osg::Vec3, osg::Vec3> ImageData;
134            const ImageData id[] =
135            {
136                ImageData( osg::Vec3( 1,  0,  0), osg::Vec3( 0, -1,  0) ), // +X
137                ImageData( osg::Vec3(-1,  0,  0), osg::Vec3( 0, -1,  0) ), // -X
138                ImageData( osg::Vec3( 0,  1,  0), osg::Vec3( 0,  0,  1) ), // +Y
139                ImageData( osg::Vec3( 0, -1,  0), osg::Vec3( 0,  0, -1) ), // -Y
140                ImageData( osg::Vec3( 0,  0,  1), osg::Vec3( 0, -1,  0) ), // +Z
141                ImageData( osg::Vec3( 0,  0, -1), osg::Vec3( 0, -1,  0) )  // -Z
142            };
143
144            for(unsigned int i=0;
145                i<6 && i<_cameraNodes.size();
146                ++i)
147            {
148                osg::Matrix localOffset;
149                localOffset.makeLookAt(position,position+id[i].first,id[i].second);
150               
151                osg::Matrix viewMatrix = worldToLocal*localOffset;
152           
153                _cameraNodes[i]->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF);
154                _cameraNodes[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0);
155                _cameraNodes[i]->setViewMatrix(viewMatrix);
156            }
157        }
158       
159    protected:
160   
161        virtual ~UpdateCameraAndTexGenCallback() {}
162       
163        osg::RefNodePath            _reflectorNodePath;       
164        CameraList                  _cameraNodes;
165};
166
167class TexMatCullCallback : public osg::NodeCallback
168{
169    public:
170   
171        TexMatCullCallback(osg::TexMat* texmat):
172            _texmat(texmat)
173        {
174        }
175       
176        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
177        {
178            // first update subgraph to make sure objects are all moved into postion
179            traverse(node,nv);
180           
181            osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
182            if (cv)
183            {
184                osg::Quat quat;
185                cv->getModelViewMatrix().get(quat);
186                _texmat->setMatrix(osg::Matrix::rotate(quat.inverse()));
187            }
188        }
189       
190    protected:
191   
192        osg::ref_ptr<TexMat>    _texmat;
193};
194
195
196osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::RefNodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation)
197{
198
199    osg::Group* group = new osg::Group;
200   
201    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
202    texture->setTextureSize(tex_width, tex_height);
203
204    texture->setInternalFormat(GL_RGB);
205    texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
206    texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
207    texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
208    texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR);
209    texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR);
210   
211    // set up the render to texture cameras.
212    UpdateCameraAndTexGenCallback::CameraList cameraNodes;
213    for(unsigned int i=0; i<6; ++i)
214    {
215        // create the camera
216        osg::CameraNode* camera = new osg::CameraNode;
217
218        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
219        camera->setClearColor(clearColor);
220
221        // set viewport
222        camera->setViewport(0,0,tex_width,tex_height);
223
224        // set the camera to render before the main camera.
225        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
226
227        // tell the camera to use OpenGL frame buffer object where supported.
228        camera->setRenderTargetImplementation(renderImplementation);
229
230        // attach the texture and use it as the color buffer.
231        camera->attach(osg::CameraNode::COLOR_BUFFER, texture, 0, i);
232
233        // add subgraph to render
234        camera->addChild(reflectedSubgraph);
235       
236        group->addChild(camera);
237       
238        cameraNodes.push_back(camera);
239    }
240   
241    // create the texgen node to project the tex coords onto the subgraph
242    osg::TexGenNode* texgenNode = new osg::TexGenNode;
243    texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP);
244    texgenNode->setTextureUnit(unit);
245    group->addChild(texgenNode);
246
247    // set the reflected subgraph so that it uses the texture and tex gen settings.   
248    {
249        osg::Node* reflectorNode = reflectorNodePath.front().get();
250        group->addChild(reflectorNode);
251               
252        osg::StateSet* stateset = reflectorNode->getOrCreateStateSet();
253        stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
254        stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
255        stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
256        stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
257        stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
258
259        osg::TexMat* texmat = new osg::TexMat;
260        stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON);
261       
262        reflectorNode->setCullCallback(new TexMatCullCallback(texmat));
263    }
264   
265    // add the reflector scene to draw just as normal
266    group->addChild(reflectedSubgraph);
267   
268    // set an update callback to keep moving the camera and tex gen in the right direction.
269    group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, cameraNodes));
270
271    return group;
272}
273
274
275int main(int argc, char** argv)
276{
277    // use an ArgumentParser object to manage the program arguments.
278    ArgumentParser arguments(&argc, argv);
279
280    // set up the usage document, in case we need to print out how to use this program.
281    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
282    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
283    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
284    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
285    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
286    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
287    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
288    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
289    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
290
291    // construct the viewer.
292    osgProducer::Viewer viewer(arguments);
293
294    // set up the value with sensible default event handlers.
295    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
296
297    // get details on keyboard and mouse bindings used by the viewer.
298    viewer.getUsage(*arguments. getApplicationUsage());
299
300    // if user request help write it out to cout.
301    if (arguments.read("-h") || arguments.read("--help"))
302    {
303        arguments.getApplicationUsage()->write(std::cout);
304        return 1;
305    }
306   
307    unsigned tex_width = 512;
308    unsigned tex_height = 512;
309    while (arguments.read("--width", tex_width)) {}
310    while (arguments.read("--height", tex_height)) {}
311
312    osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
313   
314    while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; }
315    while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; }
316    while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; }
317    while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; }
318   
319
320    // any option left unread are converted into errors to write out later.
321    arguments.reportRemainingOptionsAsUnrecognized();
322
323    // report any errors if they have occured when parsing the program aguments.
324    if (arguments.errors())
325    {
326      arguments.writeErrorMessages(std::cout);
327      return 1;
328    }
329
330    ref_ptr<MatrixTransform> scene = new MatrixTransform;
331    scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0));
332
333    ref_ptr<Group> reflectedSubgraph = _create_scene();   
334    if (!reflectedSubgraph.valid()) return 1;
335
336    ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getClearColor(),
337                                                        tex_width, tex_height, renderImplementation);
338
339    scene->addChild(reflectedScene.get());
340
341    viewer.setSceneData(scene.get());
342
343    // create the windows and run the threads.
344    viewer.realize();
345
346    while (!viewer.done())
347    {
348      // wait for all cull and draw threads to complete.
349      viewer.sync();
350
351      // update the scene by traversing it with the the update visitor which will
352      // call all node update callbacks and animations.
353      viewer.update();
354         
355      // fire off the cull and draw traversals of the scene.
356      viewer.frame();
357    }
358   
359    // wait for all cull and draw threads to complete before exit.
360    viewer.sync();
361
362    return 0;
363}
Note: See TracBrowser for help on using the browser.