source: experimental/distortionNG/DistortionManipulator.cpp @ 363

Last change on this file since 363 was 361, checked in by Torben Dannhauer, 12 years ago
File size: 18.3 KB
Line 
1/* osgVisual test. distortionNG, experimental.
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 "DistortionManipulator.h"
20
21#include <osgViewer/Viewer>
22#include <osg/Point>
23#include <osg/PolygonMode>
24
25#include <osgDB/Registry>
26#include <osgDB/ReaderWriter>
27#include <osgDB/WriteFile>
28
29using namespace osg;
30using namespace osgViewer;
31
32
33DistortionManipulator::DistortionManipulator(DistortionSet* ds)
34 : _highlightColor( osg::Vec4(1.0f, 1.0f, 0.0f, 1.0f) ), _distortionSet( ds )
35{
36        activeSetupMode = DISABLED;
37        activeDistortionMode = MESH;
38        activeManualSetupMode = DISTORTION;
39        activeVisualizationMode = NONE;
40
41        _highlighter = NULL;
42       
43        createVertexHighlighter();
44        createHUD();
45
46        _camera = 0;
47        //_distortionMesh(distortionMesh)
48
49        // Create Shader to vizualize intensitymap during blending setup.
50        osg::Shader* sh = osg::Shader::readShaderFile( osg::Shader::FRAGMENT, "shaderIntensityMapVis.frag" ); 
51        sh->setName("shaderIntensityMapVis");
52        ds->setShaderIntensityMapVis( sh );
53}
54
55DistortionManipulator::~DistortionManipulator()
56{
57}
58
59void DistortionManipulator::getUsage(osg::ApplicationUsage& usage) const
60{
61        usage.addKeyboardMouseBinding("Keypad 0","Show/Hide distortion HUD.");
62        usage.addKeyboardMouseBinding("Keypad 1","Reset distortion.");
63        usage.addKeyboardMouseBinding("Keypad 2","Reset intensity blending.");
64        usage.addKeyboardMouseBinding("Keypad 4","Toggles Setup Mode between DISABLED, MANUAL & DELEGATED.");
65        usage.addKeyboardMouseBinding("Keypad 5","MANUAL Mode: Toggle between blending & distortion setup.");
66    usage.addKeyboardMouseBinding("Keypad 6","MANUAL Mode: Toggle if distortion drags affect mesh or rtt texture coordinates.");        // Defaults to Mesh
67        usage.addKeyboardMouseBinding("Keypad 7","Show distortion mesh / intensity map / none.");
68        usage.addKeyboardMouseBinding("Keypad 8","Save distortion set.");       // via plugin
69}
70
71bool DistortionManipulator::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object* obj, osg::NodeVisitor* nv)
72{
73        switch(ea.getEventType())
74    {
75        case(osgGA::GUIEventAdapter::MOVE): break;
76        case(osgGA::GUIEventAdapter::DRAG):
77                {
78                        if ( activeSetupMode == MANUAL)
79                        {
80                                OSG_ALWAYS<<std::endl<<"Drag:"<<std::endl<<"ea.getGraphicsContext()="<<ea.getGraphicsContext()<<std::endl;
81                                OSG_ALWAYS<<"ea.getXnormalized()="<<ea.getXnormalized()<<std::endl;
82                                OSG_ALWAYS<<"ea.getYnormalized()="<<ea.getYnormalized()<<std::endl;
83                                OSG_ALWAYS<<"ea.getX()="<<ea.getX()<<std::endl;
84                                OSG_ALWAYS<<"ea.getXin()="<<ea.getXmin()<<std::endl;
85                                OSG_ALWAYS<<"ea.getXmax()="<<ea.getXmax()<<std::endl;
86                                OSG_ALWAYS<<"ea.getY()="<<ea.getY()<<std::endl;
87                                OSG_ALWAYS<<"ea.getYin()="<<ea.getYmin()<<std::endl;
88                                OSG_ALWAYS<<"ea.getYmax()="<<ea.getYmax()<<std::endl;
89
90                                if(activeDistortionMode == MESH)
91                                {
92                                        OSG_ALWAYS<<"MESH!"<<std::endl;
93                                }
94                                else if (activeDistortionMode == TEXCOORDINATES)
95                                {
96                                        OSG_ALWAYS<<"TEXCOORDINATES!"<<std::endl;
97                                }
98
99                                return true;    // true means event handled: not forwarded to the camera manipulator;
100                        }
101                        break;
102
103                }
104        case(osgGA::GUIEventAdapter::PUSH):
105                {
106                        OSG_ALWAYS<<"mouse click!"<<std::endl;
107                        if ( activeSetupMode == MANUAL /*&& ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL*/ && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON )
108                        {
109                                osgViewer::View* viewer = dynamic_cast<osgViewer::View*>(&aa);
110                                if ( viewer )
111                                {
112                                        osg::notify(osg::ALWAYS)<<std::endl<<"Intersection:"<<std::endl<<"ea.getX()="<<ea.getX()<<std::endl;
113                                        osg::notify(osg::ALWAYS)<<"ea.getY()="<<ea.getY()<<std::endl;
114                                        osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, ea.getX(), ea.getY());
115                                        osgUtil::IntersectionVisitor iv( intersector.get() );
116                                        _distortionSet->getDistortionCamera()->accept( iv );
117                               
118                                        if ( intersector->containsIntersections() )
119                                        {
120                                                osgUtil::LineSegmentIntersector::Intersection& result = *(intersector->getIntersections().begin());
121                                                computeSelectedVertex( result );
122                                        }
123                                }
124                        }
125                        break;
126                }
127        case(osgGA::GUIEventAdapter::RELEASE): break;
128        case(osgGA::GUIEventAdapter::KEYDOWN):
129                {
130                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Insert) // KP 0: Show/Hide HUD
131                        {
132                                bool oldValue = _distortionSet->getDistortionInternals()->getValue(DistortionSet::HUD);
133                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HUD, !oldValue);
134                                return(true);
135                        }
136                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_End)    // KP 1: reset distortion
137                        {
138                                resetDistortion();
139                                return(true);
140                        }
141                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Down)   // KP 2: reset intensity map
142                        {
143                                resetIntensityMap();
144                                return(true);
145                        }
146                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Left)   // KP 4: Toggles Setup Mode between DISABLED, MANUAL & DELEGATED.
147                        {
148                                switch(activeSetupMode)
149                                {
150                                        case DISABLED : 
151                                        {
152                                                activeSetupMode = MANUAL;
153                                                OSG_NOTICE<<"SetupMode MANUAL activated"<<std::endl;
154                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, true);
155                                                break;
156                                        }
157                                        case MANUAL :
158                                        {
159                                                activeSetupMode = DELEGATED;
160                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, false);
161                                                OSG_NOTICE<<"SetupMode DELEGATED activated"<<std::endl;
162                                                break;
163                                        }
164                                        case DELEGATED :
165                                        {
166                                                activeSetupMode = DISABLED;
167                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, false); 
168                                                OSG_NOTICE<<"SetupMode DISABLED activated"<<std::endl;
169                                                break;
170                                        }
171                                }
172                                updateHUD();
173                                return(true);
174                        }
175                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Begin)  // KP 5: MANUAL Mode: Toggle between blending & distortion setup.
176                        {
177
178                                activeManualSetupMode = (activeManualSetupMode==DISTORTION?BLENDING:DISTORTION);
179                                updateHUD();
180                                return(true);
181                        }
182                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Right)  // KP 6: MANUAL Mode: Toggle if distortion drags affect mesh or rtt texture coordinates -> defaults to Mesh
183                        {
184                                activeDistortionMode = (activeDistortionMode==MESH?TEXCOORDINATES:MESH);
185                                updateHUD();
186                                return(true);
187                        }
188                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Home)   // KP 7: Show distortion mesh / intensity map / none.
189                        {
190                                switch(activeVisualizationMode)
191                                {       
192                                        case DISTORTION_MESH : 
193                                        {
194                                                activeVisualizationMode = INTENSITY_MAP;
195                                                showDistortionMesh(false);
196                                                showIntensityMap(true);
197                                                break;
198                                        }
199                                        case INTENSITY_MAP :
200                                        {
201                                                activeVisualizationMode = NONE;
202                                                showDistortionMesh(false);
203                                                showIntensityMap(false);
204                                                break;
205                                        }
206                                        case NONE : 
207                                        {
208                                                activeVisualizationMode = DISTORTION_MESH;
209                                                showDistortionMesh(true);
210                                                showIntensityMap(false);
211                                                break;
212                                        }
213                                }
214
215                                updateHUD();
216                                return(true);
217                        }
218                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Up)     // KP 8: Save distortion set     via plugin
219                        {
220                                OSG_ALWAYS<<"KEY_KP_8 : todo: Save DistortionContainer"<<std::endl;
221
222
223
224        // Configure Compression and instantiate read/write-options
225        bool asAscii_ = true;
226        bool compressionEnabled = false;
227
228        std::string readOptionString = "";
229        std::string writeOptionString = "";
230        if(asAscii_)
231        {
232                readOptionString = "Ascii";
233                writeOptionString = "Ascii";
234        }
235        if (compressionEnabled)
236                writeOptionString+=" Compressor=zlib";
237       
238        osg::ref_ptr<osgDB::Options> readOptions = new osgDB::Options( readOptionString.c_str() );
239        osg::ref_ptr<osgDB::Options> writeOptions = new osgDB::Options( writeOptionString.c_str() );
240
241        //// Get ReaderWriter
242        //osg::ref_ptr<osgDB::ReaderWriter> rw = osgDB::Registry::instance()->getReaderWriterForExtension("osgb");     
243
244        //// Writing node to stream
245        //std::stringstream myOstream;
246        //if ( rw )
247        //{
248        //      osgDB::ReaderWriter::WriteResult wr = rw->writeObject( *_distortionSet, myOstream, writeOptions );
249        //      if (wr.success() )                     
250        //      {
251        //              OSG_ALWAYS<<"write node success"<<std::endl;
252        //      }
253        //      else
254        //      {
255        //              OSG_ALWAYS<<"write node failed"<<std::endl;
256        //      }
257        //}
258
259        if( osgDB::writeObjectFile(*_distortionSet, "test.osgt", writeOptions) )
260        {
261                OSG_ALWAYS<<"write node success"<<std::endl;
262        }
263        else
264        {
265                OSG_ALWAYS<<"write node failed"<<std::endl;
266        }
267
268
269
270
271
272
273
274
275
276
277
278
279
280                                return(true);
281                        }
282                       
283                        return false;   // Event ignored
284                }
285        case(osgGA::GUIEventAdapter::KEYUP): break;
286                case(osgGA::GUIEventAdapter::FRAME):
287                {
288                        if ( activeSetupMode == DELEGATED)
289                        {
290                                OSG_ALWAYS<<"Todo: Calling delegated class!"<<std::endl;
291                        }
292                        break;
293                }
294        case (osgGA::GUIEventAdapter::RESIZE):  // todo: adapt distortion mesh to new screen size
295                {
296                        OSG_ALWAYS<<"RESIZE!"<<std::endl;
297                        break;
298                }
299
300        default:
301            return false;
302    }
303    return false;
304}
305
306void DistortionManipulator::resetIntensityMap()
307{
308        if(!_distortionSet.valid())
309                return;
310
311        osg::ref_ptr<osg::Image> image = _distortionSet->getIntensityMap();
312
313        OSG_ALWAYS<<"Reseting IntensityMap Blending."<<std::endl;
314
315        if (!image->isDataContiguous())
316        {
317                OSG_WARN<<"Warning: DistortionManipulator does not support working with non contiguous imagery as blendmaps!"<<std::endl;
318                return;
319        }
320
321        // Fill intensity map with 255
322        unsigned char* dataPtr = image->data(); 
323        for(unsigned int i=0;i<image->getTotalSizeInBytes();i++)
324        {
325                *dataPtr++ = 255; 
326        }
327        image->dirty();
328}
329
330void DistortionManipulator::resetDistortion()
331{
332        if(!_distortionSet.valid())
333                return;
334
335        OSG_ALWAYS<<"ToDo: resetDistortion()"<<std::endl;
336}
337
338void DistortionManipulator::showDistortionMesh(bool show)
339{
340        osg::StateSet* stateset = _distortionSet->getDistortionInternals()->getChild(DistortionSet::MESH)->getOrCreateStateSet();
341
342        // Append a PolygonMode stateset if required
343    osg::PolygonMode* polyModeObj = dynamic_cast<osg::PolygonMode*>(stateset->getAttribute(osg::StateAttribute::POLYGONMODE));
344    if (!polyModeObj)
345    {
346        polyModeObj = new osg::PolygonMode;
347        stateset->setAttribute(polyModeObj, osg::StateAttribute::PROTECTED|osg::StateAttribute::ON);
348    }
349 
350        // Set Polygonmode
351        if(show)
352                polyModeObj->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
353        else
354                polyModeObj->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::FILL);
355}
356
357void DistortionManipulator::showIntensityMap(bool show)
358{
359        if(_distortionSet.valid())
360        {
361                osg::StateSet* stateset = _distortionSet->getDistortionInternals()->getChild(DistortionSet::MESH)->getOrCreateStateSet();
362                osg::Program* program = static_cast<osg::Program*>(stateset->getAttribute(::osg::StateAttribute::PROGRAM));
363
364                if(show)
365                {
366                        program->removeShader( _distortionSet->getShaderIntensityMap() );
367                        program->addShader( _distortionSet->getShaderIntensityMapVis() );
368                }
369                else
370                {
371                        program->removeShader( _distortionSet->getShaderIntensityMapVis() );
372                        program->addShader( _distortionSet->getShaderIntensityMap() );
373                }
374        }
375}
376
377void DistortionManipulator::createVertexHighlighter()
378{
379        osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1);
380        (*colors)[0] = _highlightColor;
381
382        _highlighter = new osg::Geometry;
383        _highlighter->setDataVariance( osg::Object::DYNAMIC );
384        _highlighter->setUseDisplayList( false );
385        _highlighter->setUseVertexBufferObjects( true );
386        _highlighter->setVertexArray( new osg::Vec3Array(1) );  // The highlighter vertex is updated by computeSelectedVertex(..)
387        _highlighter->setColorArray( colors.get() );
388        _highlighter->setColorBinding( osg::Geometry::BIND_OVERALL );
389        _highlighter->addPrimitiveSet( new osg::DrawArrays(GL_POINTS, 0, 1) );
390
391       
392        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
393        geode->addDrawable( _highlighter.get() );
394        geode->getOrCreateStateSet()->setAttributeAndModes( new osg::Point(8.0f) );
395        geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
396        geode->setCullingActive(false); // disable the culling for the selector, otherwise the selector is culled away on the edge.
397
398        _distortionSet->getDistortionInternals()->addChild(geode, false);       //  = child #1  :definition: child #0 = mesh, #1 = highlighter, #2 HUD
399}
400
401void DistortionManipulator::createHUD()
402{
403        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
404       
405        osg::StateSet* stateSet = geode->getOrCreateStateSet();
406        stateSet->setRenderBinDetails( 99, "RenderBin");
407        // disable depth test to ensure that it is always drawn.
408        stateSet->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
409        stateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
410
411        // Add Text:
412        osg::Vec3 position(20.0f,120.0f,0.0f);
413        osg::Vec3 delta(0.0f,-25.0f,0.0f);
414        std::string timesFont("fonts/arial.ttf");
415        {
416                osg::ref_ptr<osgText::Text> textHeader = new osgText::Text;
417                textHeader->setText("Distortion Setup:");
418                textHeader->setFont(timesFont);
419                textHeader->setPosition(position);
420                textHeader->setCharacterSize(21);
421                textHeader->setDataVariance(osg::Object::STATIC); 
422                geode->addDrawable( textHeader );
423
424                position += delta;
425
426                hudSetupMode = new osgText::Text;
427                hudSetupMode->setFont(timesFont);
428                hudSetupMode->setPosition(position);
429                hudSetupMode->setCharacterSize(21);
430                hudSetupMode->setDataVariance(osg::Object::DYNAMIC); 
431                geode->addDrawable( hudSetupMode );
432
433                position += delta;
434
435                hudDistortionMode = new osgText::Text;
436                hudDistortionMode->setFont(timesFont);
437                hudDistortionMode->setPosition(position);
438                hudDistortionMode->setCharacterSize(21);
439                hudDistortionMode->setDataVariance(osg::Object::DYNAMIC); 
440                geode->addDrawable( hudDistortionMode );
441
442                position += delta;
443
444                hudManualSetupMode = new osgText::Text;
445                hudManualSetupMode->setFont(timesFont);
446                hudManualSetupMode->setPosition(position);
447                hudManualSetupMode->setCharacterSize(21);
448                hudManualSetupMode->setDataVariance(osg::Object::DYNAMIC); 
449                geode->addDrawable( hudManualSetupMode );
450
451                position += delta;
452
453                hudVisualizationMode = new osgText::Text;
454                hudVisualizationMode->setFont(timesFont);
455                hudVisualizationMode->setPosition(position);
456                hudVisualizationMode->setCharacterSize(21);
457                hudVisualizationMode->setDataVariance(osg::Object::DYNAMIC); 
458                geode->addDrawable( hudVisualizationMode );
459        }
460       
461        updateHUD();
462        _distortionSet->getDistortionInternals()->addChild(geode, false);       //  = child #2  :definition: child #0 = mesh, #1 = highlighter, #2 HUD
463}
464
465void DistortionManipulator::updateHUD()
466{
467        switch(activeSetupMode)
468        {
469                case DISABLED : hudSetupMode->setText("Setup Mode : DISABLED"); break;
470                case MANUAL : hudSetupMode->setText("Setup Mode : MANUAL"); break;
471                case DELEGATED : hudSetupMode->setText("Setup Mode : DELEGATED"); break;
472                default: hudSetupMode->setText("");
473        };
474        switch(activeDistortionMode)
475        {
476                case MESH : hudDistortionMode->setText("Distortion Mode : MESH"); break;
477                case TEXCOORDINATES : hudDistortionMode->setText("Distortion Mode : TEXCOORDINATES"); break;
478                default: hudDistortionMode->setText("");
479        };
480        switch(activeManualSetupMode)
481        {
482                case DISTORTION : hudManualSetupMode->setText("Manual Setup Mode : DISTORTION"); break;
483                case BLENDING : hudManualSetupMode->setText("Manual Setup Mode : BLENDING"); break;
484                default: hudManualSetupMode->setText("");
485        };
486        switch(activeVisualizationMode)
487        {
488                case DISTORTION_MESH : hudVisualizationMode->setText("Visualization Mode : DISTORTION_MESH"); break;
489                case INTENSITY_MAP : hudVisualizationMode->setText("Visualization Mode : INTENSITY_MAP"); break;
490                case NONE : hudVisualizationMode->setText("Visualization Mode : NONE"); break;
491                default: hudVisualizationMode->setText("");
492        };
493}
494
495void DistortionManipulator::computeSelectedVertex( osgUtil::LineSegmentIntersector::Intersection& result )
496{
497        osg::Geometry* geom = dynamic_cast<osg::Geometry*>( result.drawable.get() );
498        if ( !geom || geom==_highlighter )
499                return;
500
501        osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>( geom->getVertexArray() );
502        osg::Vec3Array* selVertices = dynamic_cast<osg::Vec3Array*>( _highlighter->getVertexArray() );
503        if ( !vertices || !selVertices )
504                return;
505       
506        OSG_NOTIFY(osg::ALWAYS)<<"size of vertices="<<vertices->size()<<std::endl;
507        OSG_NOTIFY(osg::ALWAYS)<<"size of selVertices="<<selVertices->size()<<std::endl;
508
509        osg::Vec3 point = result.getWorldIntersectPoint();
510        osg::Matrix matrix = osg::computeLocalToWorld( result.nodePath );       // To compute the intersection vertices in world coordinates not in model coordinates
511        OSG_NOTIFY(osg::ALWAYS) << "Intersection-indices: Size=" << result.indexList.size() << std::endl;
512        const std::vector<unsigned int>& selIndices = result.indexList;
513        {
514                double maxRatio = 0.0;
515                int closestVertexIndex = 0;
516                for ( unsigned int i=0; i<3 && i<result.ratioList.size(); i++ ) //iterate through rations and search for maxRation=nearestVertex
517                {
518                        if(result.ratioList[i] > maxRatio)
519                        {
520                                maxRatio = result.ratioList[i];
521                                closestVertexIndex = result.indexList[i];
522                        }
523                        OSG_NOTIFY(osg::ALWAYS)<<"maxRatio="<<maxRatio<<std::endl;
524                        OSG_NOTIFY(osg::ALWAYS)<<"closestVertexIndex="<<closestVertexIndex<<std::endl;
525                }
526                OSG_NOTIFY(osg::ALWAYS)<<"nearest vertex: X="<<(*vertices)[closestVertexIndex].x()<<" Y="<<(*vertices)[closestVertexIndex].y()<<" Z="<<(*vertices)[closestVertexIndex].z()<<std::endl;
527                osg::Vec3 vertex = (*vertices)[closestVertexIndex] * matrix;
528
529                selVertices->front() = vertex;         
530                OSG_NOTIFY(osg::ALWAYS)<<"selected vertice: X="<<vertex.x()<<" Y="<<vertex.y()<<" Z="<<vertex.z()<<std::endl;
531        }
532        selVertices->dirty();
533        _highlighter->dirtyBound(); 
534}
Note: See TracBrowser for help on using the repository browser.