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

Revision 5022, 13.7 kB (checked in by robert, 8 years ago)

Compile fix.

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