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

Revision 7648, 13.8 kB (checked in by robert, 7 years ago)

From Roland Smeenk, "Attached you will find a large set of small typo fixes (mainly in the comments)."

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