source: experimental/distortionNG/DistortionManipulator.cpp @ 398

Last change on this file since 398 was 398, checked in by Torben Dannhauer, 12 years ago
File size: 23.4 KB
RevLine 
[346]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"
[380]20#include "extViewer.h"
[346]21
[358]22#include <osgViewer/Viewer>
23#include <osg/Point>
24#include <osg/PolygonMode>
[381]25#include <osg/TextureRectangle>
[347]26
[361]27#include <osgDB/Registry>
28#include <osgDB/ReaderWriter>
29#include <osgDB/WriteFile>
30
[371]31#include "DistortionSetupStrategy.h"
32
[346]33using namespace osg;
34using namespace osgViewer;
35
36
[380]37DistortionManipulator::DistortionManipulator(extViewer* viewer, DistortionSet* ds)
38 : _highlightColor( osg::Vec4(1.0f, 1.0f, 0.0f, 1.0f) ), _distortionSet( ds ), _viewer(viewer)
[346]39{
[348]40        activeSetupMode = DISABLED;
41        activeDistortionMode = MESH;
42        activeManualSetupMode = DISTORTION;
43        activeVisualizationMode = NONE;
[349]44
[371]45        _delegatedDistortionSetupStrategy = NULL;
46
[353]47        _highlighter = NULL;
48       
49        createVertexHighlighter();
[356]50        createHUD();
[353]51
52        _camera = 0;
53        //_distortionMesh(distortionMesh)
[361]54
[392]55        // Create Shader to visualize intensitymap during blending setup.
[361]56        osg::Shader* sh = osg::Shader::readShaderFile( osg::Shader::FRAGMENT, "shaderIntensityMapVis.frag" ); 
57        sh->setName("shaderIntensityMapVis");
58        ds->setShaderIntensityMapVis( sh );
[370]59
60        //LF Get Screen Resolution for Cursor Position Scaling
61        osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
62        if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; }
63        wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), _screenPixWidth, _screenPixHeight);
64
65
[346]66}
67
68DistortionManipulator::~DistortionManipulator()
69{
70}
71
72void DistortionManipulator::getUsage(osg::ApplicationUsage& usage) const
73{
[356]74        usage.addKeyboardMouseBinding("Keypad 0","Show/Hide distortion HUD.");
75        usage.addKeyboardMouseBinding("Keypad 1","Reset distortion.");
76        usage.addKeyboardMouseBinding("Keypad 2","Reset intensity blending.");
[346]77        usage.addKeyboardMouseBinding("Keypad 4","Toggles Setup Mode between DISABLED, MANUAL & DELEGATED.");
78        usage.addKeyboardMouseBinding("Keypad 5","MANUAL Mode: Toggle between blending & distortion setup.");
[356]79    usage.addKeyboardMouseBinding("Keypad 6","MANUAL Mode: Toggle if distortion drags affect mesh or rtt texture coordinates.");        // Defaults to Mesh
80        usage.addKeyboardMouseBinding("Keypad 7","Show distortion mesh / intensity map / none.");
81        usage.addKeyboardMouseBinding("Keypad 8","Save distortion set.");       // via plugin
[346]82}
83
[348]84bool DistortionManipulator::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object* obj, osg::NodeVisitor* nv)
[346]85{
[370]86
87
[347]88        switch(ea.getEventType())
[346]89    {
[348]90        case(osgGA::GUIEventAdapter::MOVE): break;
[346]91        case(osgGA::GUIEventAdapter::DRAG):
92                {
[355]93                        if ( activeSetupMode == MANUAL)
94                        {
[357]95                                OSG_ALWAYS<<std::endl<<"Drag:"<<std::endl<<"ea.getGraphicsContext()="<<ea.getGraphicsContext()<<std::endl;
96                                OSG_ALWAYS<<"ea.getXnormalized()="<<ea.getXnormalized()<<std::endl;
97                                OSG_ALWAYS<<"ea.getYnormalized()="<<ea.getYnormalized()<<std::endl;
98                                OSG_ALWAYS<<"ea.getX()="<<ea.getX()<<std::endl;
99                                OSG_ALWAYS<<"ea.getXin()="<<ea.getXmin()<<std::endl;
100                                OSG_ALWAYS<<"ea.getXmax()="<<ea.getXmax()<<std::endl;
101                                OSG_ALWAYS<<"ea.getY()="<<ea.getY()<<std::endl;
102                                OSG_ALWAYS<<"ea.getYin()="<<ea.getYmin()<<std::endl;
103                                OSG_ALWAYS<<"ea.getYmax()="<<ea.getYmax()<<std::endl;
[370]104                               
105                                //LF get X,Y normalized to lowerleftcorner (0,0) / upperrightcorner (1,1)
106                                OSG_ALWAYS<<"getXnormalizedLF()="<<(ea.getXnormalized()+1.0)/2.0<<std::endl;
107                                OSG_ALWAYS<<"getYnormalizedLF()="<<(ea.getYnormalized()+1.0)/2.0<<std::endl;
[353]108
[370]109                                //LF get X,Y in pixels (lowerleftcorner (0,0) / upperrightcorner (screenwidth,screenheigth)
110                                OSG_ALWAYS<<std::endl<<"Screen Resolution: "<<_screenPixWidth<<" x "<<_screenPixHeight<<std::endl;
111                                OSG_ALWAYS<<"getXPixelspaceLF()="<<(int)((float)_screenPixWidth*(ea.getXnormalized()+1.0)/2.0)<<std::endl;
112                                OSG_ALWAYS<<"getYPixelspaceLF()="<<(int)((float)_screenPixHeight*(ea.getYnormalized()+1.0)/2.0)<<std::endl;
[367]113
[357]114                                if(activeDistortionMode == MESH)
115                                {
116                                        OSG_ALWAYS<<"MESH!"<<std::endl;
117                                }
118                                else if (activeDistortionMode == TEXCOORDINATES)
119                                {
120                                        OSG_ALWAYS<<"TEXCOORDINATES!"<<std::endl;
121                                }
122
[355]123                                return true;    // true means event handled: not forwarded to the camera manipulator;
124                        }
125                        break;
[353]126
[346]127                }
128        case(osgGA::GUIEventAdapter::PUSH):
[348]129                {
[353]130                        OSG_ALWAYS<<"mouse click!"<<std::endl;
[361]131                        if ( activeSetupMode == MANUAL /*&& ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL*/ && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON )
[348]132                        {
[353]133                                osgViewer::View* viewer = dynamic_cast<osgViewer::View*>(&aa);
134                                if ( viewer )
135                                {
136                                        osg::notify(osg::ALWAYS)<<std::endl<<"Intersection:"<<std::endl<<"ea.getX()="<<ea.getX()<<std::endl;
137                                        osg::notify(osg::ALWAYS)<<"ea.getY()="<<ea.getY()<<std::endl;
138                                        osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, ea.getX(), ea.getY());
139                                        osgUtil::IntersectionVisitor iv( intersector.get() );
140                                        _distortionSet->getDistortionCamera()->accept( iv );
141                               
142                                        if ( intersector->containsIntersections() )
143                                        {
[370]144                                                //osgUtil::LineSegmentIntersector::Intersection& result = *(intersector->getIntersections().begin());
145                                                osgUtil::LineSegmentIntersector::Intersection *result;
146                                                result=&intersector->getFirstIntersection();
147                                                computeSelectedVertex( *result );
148                                                //computeSelectedVertex( result );
[353]149                                        }
150                                }
[348]151                        }
152                        break;
153                }
154        case(osgGA::GUIEventAdapter::RELEASE): break;
[346]155        case(osgGA::GUIEventAdapter::KEYDOWN):
[347]156                {
[357]157                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Insert) // KP 0: Show/Hide HUD
[356]158                        {
[357]159                                bool oldValue = _distortionSet->getDistortionInternals()->getValue(DistortionSet::HUD);
160                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HUD, !oldValue);
[356]161                                return(true);
162                        }
[347]163                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_End)    // KP 1: reset distortion
164                        {
165                                resetDistortion();
166                                return(true);
167                        }
168                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Down)   // KP 2: reset intensity map
169                        {
170                                resetIntensityMap();
171                                return(true);
172                        }
173                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Left)   // KP 4: Toggles Setup Mode between DISABLED, MANUAL & DELEGATED.
174                        {
[348]175                                switch(activeSetupMode)
176                                {
[353]177                                        case DISABLED : 
178                                        {
179                                                activeSetupMode = MANUAL;
[356]180                                                OSG_NOTICE<<"SetupMode MANUAL activated"<<std::endl;
[357]181                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, true);
[353]182                                                break;
183                                        }
184                                        case MANUAL :
185                                        {
186                                                activeSetupMode = DELEGATED;
[357]187                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, false);
[356]188                                                OSG_NOTICE<<"SetupMode DELEGATED activated"<<std::endl;
[353]189                                                break;
190                                        }
191                                        case DELEGATED :
192                                        {
193                                                activeSetupMode = DISABLED;
[357]194                                                _distortionSet->getDistortionInternals()->setValue(DistortionSet::HIGHLIGHTER, false); 
[356]195                                                OSG_NOTICE<<"SetupMode DISABLED activated"<<std::endl;
[353]196                                                break;
197                                        }
[348]198                                }
[356]199                                updateHUD();
[347]200                                return(true);
201                        }
202                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Begin)  // KP 5: MANUAL Mode: Toggle between blending & distortion setup.
203                        {
[348]204
205                                activeManualSetupMode = (activeManualSetupMode==DISTORTION?BLENDING:DISTORTION);
[356]206                                updateHUD();
[347]207                                return(true);
208                        }
209                        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
210                        {
[348]211                                activeDistortionMode = (activeDistortionMode==MESH?TEXCOORDINATES:MESH);
[356]212                                updateHUD();
[347]213                                return(true);
214                        }
215                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Home)   // KP 7: Show distortion mesh / intensity map / none.
216                        {
[348]217                                switch(activeVisualizationMode)
218                                {       
[349]219                                        case DISTORTION_MESH : 
220                                        {
221                                                activeVisualizationMode = INTENSITY_MAP;
[358]222                                                showDistortionMesh(false);
223                                                showIntensityMap(true);
[349]224                                                break;
225                                        }
226                                        case INTENSITY_MAP :
227                                        {
228                                                activeVisualizationMode = NONE;
229                                                showDistortionMesh(false);
[358]230                                                showIntensityMap(false);
[349]231                                                break;
232                                        }
233                                        case NONE : 
234                                        {
235                                                activeVisualizationMode = DISTORTION_MESH;
[358]236                                                showDistortionMesh(true);
[349]237                                                showIntensityMap(false);
238                                                break;
239                                        }
[348]240                                }
[349]241
[356]242                                updateHUD();
[347]243                                return(true);
244                        }
245                        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Up)     // KP 8: Save distortion set     via plugin
246                        {
[349]247                                OSG_ALWAYS<<"KEY_KP_8 : todo: Save DistortionContainer"<<std::endl;
[361]248
[370]249                                osgDB::writeObjectFile( *_distortionSet, "distortionset.dist" );
[347]250                                return(true);
251                        }
252                       
253                        return false;   // Event ignored
254                }
[348]255        case(osgGA::GUIEventAdapter::KEYUP): break;
[346]256                case(osgGA::GUIEventAdapter::FRAME):
257                {
[371]258                        if ( activeSetupMode == DELEGATED && _delegatedDistortionSetupStrategy.valid())
[356]259                        {
[379]260                                //OSG_ALWAYS<<"Calling delegated class.."<<std::endl;
[371]261                                _delegatedDistortionSetupStrategy->delegateDistortionSetup(_distortionSet);
[380]262                                if( _distortionSet->isDirty() && _viewer.valid())
[379]263                                {
[381]264                                        updateDistortionSetup();
[379]265                                }
266                                //OSG_ALWAYS<<"..done"<<std::endl;
[356]267                        }
[346]268                        break;
269                }
270        case (osgGA::GUIEventAdapter::RESIZE):  // todo: adapt distortion mesh to new screen size
271                {
[349]272                        OSG_ALWAYS<<"RESIZE!"<<std::endl;
[346]273                        break;
274                }
275
276        default:
277            return false;
278    }
279    return false;
[347]280}
281
282void DistortionManipulator::resetIntensityMap()
283{
[349]284        if(!_distortionSet.valid())
285                return;
286
287        osg::ref_ptr<osg::Image> image = _distortionSet->getIntensityMap();
288
289        OSG_ALWAYS<<"Reseting IntensityMap Blending."<<std::endl;
290
[391]291        //isDataContiguous is unknown to MSVS2010 and GCC
292        /*if (!image->isDataContiguous())
[349]293        {
294                OSG_WARN<<"Warning: DistortionManipulator does not support working with non contiguous imagery as blendmaps!"<<std::endl;
295                return;
[391]296        }*/
[349]297
298        // Fill intensity map with 255
299        unsigned char* dataPtr = image->data(); 
300        for(unsigned int i=0;i<image->getTotalSizeInBytes();i++)
301        {
302                *dataPtr++ = 255; 
303        }
304        image->dirty();
[347]305}
306
307void DistortionManipulator::resetDistortion()
308{
[349]309        if(!_distortionSet.valid())
310                return;
311
312        OSG_ALWAYS<<"ToDo: resetDistortion()"<<std::endl;
313}
314
315void DistortionManipulator::showDistortionMesh(bool show)
316{
[358]317        osg::StateSet* stateset = _distortionSet->getDistortionInternals()->getChild(DistortionSet::MESH)->getOrCreateStateSet();
[349]318
[358]319        // Append a PolygonMode stateset if required
320    osg::PolygonMode* polyModeObj = dynamic_cast<osg::PolygonMode*>(stateset->getAttribute(osg::StateAttribute::POLYGONMODE));
[349]321    if (!polyModeObj)
322    {
323        polyModeObj = new osg::PolygonMode;
[361]324        stateset->setAttribute(polyModeObj, osg::StateAttribute::PROTECTED|osg::StateAttribute::ON);
[349]325    }
326 
[358]327        // Set Polygonmode
[349]328        if(show)
329                polyModeObj->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
330        else
[358]331                polyModeObj->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::FILL);
[349]332}
333
334void DistortionManipulator::showIntensityMap(bool show)
335{
[361]336        if(_distortionSet.valid())
337        {
338                osg::StateSet* stateset = _distortionSet->getDistortionInternals()->getChild(DistortionSet::MESH)->getOrCreateStateSet();
339                osg::Program* program = static_cast<osg::Program*>(stateset->getAttribute(::osg::StateAttribute::PROGRAM));
[350]340
[361]341                if(show)
342                {
343                        program->removeShader( _distortionSet->getShaderIntensityMap() );
344                        program->addShader( _distortionSet->getShaderIntensityMapVis() );
345                }
346                else
347                {
348                        program->removeShader( _distortionSet->getShaderIntensityMapVis() );
349                        program->addShader( _distortionSet->getShaderIntensityMap() );
350                }
351        }
[349]352}
[353]353
354void DistortionManipulator::createVertexHighlighter()
355{
356        osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1);
357        (*colors)[0] = _highlightColor;
358
359        _highlighter = new osg::Geometry;
360        _highlighter->setDataVariance( osg::Object::DYNAMIC );
361        _highlighter->setUseDisplayList( false );
362        _highlighter->setUseVertexBufferObjects( true );
363        _highlighter->setVertexArray( new osg::Vec3Array(1) );  // The highlighter vertex is updated by computeSelectedVertex(..)
364        _highlighter->setColorArray( colors.get() );
365        _highlighter->setColorBinding( osg::Geometry::BIND_OVERALL );
366        _highlighter->addPrimitiveSet( new osg::DrawArrays(GL_POINTS, 0, 1) );
367
368       
369        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
370        geode->addDrawable( _highlighter.get() );
371        geode->getOrCreateStateSet()->setAttributeAndModes( new osg::Point(8.0f) );
372        geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
373        geode->setCullingActive(false); // disable the culling for the selector, otherwise the selector is culled away on the edge.
374
[356]375        _distortionSet->getDistortionInternals()->addChild(geode, false);       //  = child #1  :definition: child #0 = mesh, #1 = highlighter, #2 HUD
[353]376}
377
[356]378void DistortionManipulator::createHUD()
379{
380        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
381       
382        osg::StateSet* stateSet = geode->getOrCreateStateSet();
383        stateSet->setRenderBinDetails( 99, "RenderBin");
384        // disable depth test to ensure that it is always drawn.
385        stateSet->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
386        stateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
387
[370]388        // Modify StateSet to protect it against state changes by the stateset Manipulator
389        osg::PolygonMode* polyModeObj = new osg::PolygonMode;
390    stateSet->setAttribute(polyModeObj, osg::StateAttribute::PROTECTED|osg::StateAttribute::ON);
391
[356]392        // Add Text:
393        osg::Vec3 position(20.0f,120.0f,0.0f);
394        osg::Vec3 delta(0.0f,-25.0f,0.0f);
395        std::string timesFont("fonts/arial.ttf");
396        {
397                osg::ref_ptr<osgText::Text> textHeader = new osgText::Text;
398                textHeader->setText("Distortion Setup:");
399                textHeader->setFont(timesFont);
400                textHeader->setPosition(position);
401                textHeader->setCharacterSize(21);
402                textHeader->setDataVariance(osg::Object::STATIC); 
403                geode->addDrawable( textHeader );
404
405                position += delta;
406
407                hudSetupMode = new osgText::Text;
408                hudSetupMode->setFont(timesFont);
409                hudSetupMode->setPosition(position);
410                hudSetupMode->setCharacterSize(21);
411                hudSetupMode->setDataVariance(osg::Object::DYNAMIC); 
412                geode->addDrawable( hudSetupMode );
413
414                position += delta;
415
416                hudDistortionMode = new osgText::Text;
417                hudDistortionMode->setFont(timesFont);
418                hudDistortionMode->setPosition(position);
419                hudDistortionMode->setCharacterSize(21);
420                hudDistortionMode->setDataVariance(osg::Object::DYNAMIC); 
421                geode->addDrawable( hudDistortionMode );
422
423                position += delta;
424
425                hudManualSetupMode = new osgText::Text;
426                hudManualSetupMode->setFont(timesFont);
427                hudManualSetupMode->setPosition(position);
428                hudManualSetupMode->setCharacterSize(21);
429                hudManualSetupMode->setDataVariance(osg::Object::DYNAMIC); 
430                geode->addDrawable( hudManualSetupMode );
431
432                position += delta;
433
434                hudVisualizationMode = new osgText::Text;
435                hudVisualizationMode->setFont(timesFont);
436                hudVisualizationMode->setPosition(position);
437                hudVisualizationMode->setCharacterSize(21);
438                hudVisualizationMode->setDataVariance(osg::Object::DYNAMIC); 
439                geode->addDrawable( hudVisualizationMode );
440        }
441       
442        updateHUD();
[370]443        _distortionSet->getDistortionInternals()->addChild(geode, false);       //  = child #2. The definition is: child #0 = mesh, #1 = highlighter, #2 HUD
[356]444}
445
446void DistortionManipulator::updateHUD()
447{
448        switch(activeSetupMode)
449        {
450                case DISABLED : hudSetupMode->setText("Setup Mode : DISABLED"); break;
451                case MANUAL : hudSetupMode->setText("Setup Mode : MANUAL"); break;
452                case DELEGATED : hudSetupMode->setText("Setup Mode : DELEGATED"); break;
453                default: hudSetupMode->setText("");
454        };
455        switch(activeDistortionMode)
456        {
457                case MESH : hudDistortionMode->setText("Distortion Mode : MESH"); break;
458                case TEXCOORDINATES : hudDistortionMode->setText("Distortion Mode : TEXCOORDINATES"); break;
459                default: hudDistortionMode->setText("");
460        };
461        switch(activeManualSetupMode)
462        {
463                case DISTORTION : hudManualSetupMode->setText("Manual Setup Mode : DISTORTION"); break;
464                case BLENDING : hudManualSetupMode->setText("Manual Setup Mode : BLENDING"); break;
465                default: hudManualSetupMode->setText("");
466        };
467        switch(activeVisualizationMode)
468        {
469                case DISTORTION_MESH : hudVisualizationMode->setText("Visualization Mode : DISTORTION_MESH"); break;
470                case INTENSITY_MAP : hudVisualizationMode->setText("Visualization Mode : INTENSITY_MAP"); break;
471                case NONE : hudVisualizationMode->setText("Visualization Mode : NONE"); break;
472                default: hudVisualizationMode->setText("");
473        };
474}
475
[353]476void DistortionManipulator::computeSelectedVertex( osgUtil::LineSegmentIntersector::Intersection& result )
477{
478        osg::Geometry* geom = dynamic_cast<osg::Geometry*>( result.drawable.get() );
479        if ( !geom || geom==_highlighter )
480                return;
481
482        osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>( geom->getVertexArray() );
483        osg::Vec3Array* selVertices = dynamic_cast<osg::Vec3Array*>( _highlighter->getVertexArray() );
484        if ( !vertices || !selVertices )
485                return;
486       
487        OSG_NOTIFY(osg::ALWAYS)<<"size of vertices="<<vertices->size()<<std::endl;
488        OSG_NOTIFY(osg::ALWAYS)<<"size of selVertices="<<selVertices->size()<<std::endl;
489
490        osg::Vec3 point = result.getWorldIntersectPoint();
491        osg::Matrix matrix = osg::computeLocalToWorld( result.nodePath );       // To compute the intersection vertices in world coordinates not in model coordinates
492        OSG_NOTIFY(osg::ALWAYS) << "Intersection-indices: Size=" << result.indexList.size() << std::endl;
493        const std::vector<unsigned int>& selIndices = result.indexList;
494        {
495                double maxRatio = 0.0;
496                int closestVertexIndex = 0;
497                for ( unsigned int i=0; i<3 && i<result.ratioList.size(); i++ ) //iterate through rations and search for maxRation=nearestVertex
498                {
499                        if(result.ratioList[i] > maxRatio)
500                        {
501                                maxRatio = result.ratioList[i];
502                                closestVertexIndex = result.indexList[i];
503                        }
504                        OSG_NOTIFY(osg::ALWAYS)<<"maxRatio="<<maxRatio<<std::endl;
505                        OSG_NOTIFY(osg::ALWAYS)<<"closestVertexIndex="<<closestVertexIndex<<std::endl;
506                }
507                OSG_NOTIFY(osg::ALWAYS)<<"nearest vertex: X="<<(*vertices)[closestVertexIndex].x()<<" Y="<<(*vertices)[closestVertexIndex].y()<<" Z="<<(*vertices)[closestVertexIndex].z()<<std::endl;
508                osg::Vec3 vertex = (*vertices)[closestVertexIndex] * matrix;
509
510                selVertices->front() = vertex;         
511                OSG_NOTIFY(osg::ALWAYS)<<"selected vertice: X="<<vertex.x()<<" Y="<<vertex.y()<<" Z="<<vertex.z()<<std::endl;
512        }
513        selVertices->dirty();
514        _highlighter->dirtyBound(); 
[370]515}
[381]516
517void DistortionManipulator::updateDistortionSetup()
518{
[396]519        updateDistortionViewProjectionMatrix();
[381]520        updateDistortionMesh();
[384]521        _distortionSet->clearDirtyStatus();
[381]522}
523
524void DistortionManipulator::updateDistortionViewProjectionMatrix()
525{
526        if(!_distortionSet.valid())
527        {
528                osg::notify(osg::WARN) << "You cannot update the distortion without distortion set up." << std::endl;
529                return;
530        }
531
532        if(_viewer.valid())
533        {
[397]534                // Get slave struct to update the offset matrixes.
[398]535                osgViewer::View::Slave* sceneSlave = _viewer->findSlaveForCamera( _distortionSet->getSceneCamera() );
[391]536
[398]537                sceneSlave->_projectionOffset = _distortionSet->getProjectionOffset();
538                sceneSlave->_viewOffset = _distortionSet->getViewOffset();
[391]539
540
[397]541                // LF CameraMainupulators override ViewMatrix, so they have to go...
542                //// alternatively, _viewer->getCameraManipulator()->setByMatrix(_distortionSet->getViewOffset()) could be set
543                //// but this complicates exact camera positioning and rotating
[396]544
[397]545                //_viewer->setCameraManipulator(0);
[396]546
[397]547                //_viewer->getCamera()->setViewMatrix(_distortionSet->getViewOffset());
548                //_viewer->getCamera()->setProjectionMatrix(_distortionSet->getProjectionOffset());
[396]549
[397]550                //// Print viewMatrixAsLookAt for Debug Purposes
551                //osg::Vec3 Eye,Focus,Vertical;
552                //_viewer->getCamera()->getViewMatrixAsLookAt(Eye,Focus,Vertical);
553                //OSG_ALWAYS<<"Camera Eyepoint: X:"<<Eye.x()<<" Y:"<<Eye.y()<<" Z:"<<Eye.z()<<std::endl;
554                //printf("Camera Eyepoint: %.2lf, %.2lf, %.2lf\n",Eye.x(),Eye.y(),Eye.z());
555                //printf("Camera Direction: %.2lf, %.2lf, %.2lf\n",Focus.x()-Eye.x(),Focus.y()-Eye.y(),Focus.z()-Eye.z());
556                //printf("Vertical after: %.2lf, %.2lf, %.2lf\n",Vertical.x()-Eye.x(),Vertical.y()-Eye.y(),Vertical.z()-Eye.z());
[381]557        }
558        else
559                OSG_NOTIFY(osg::ALWAYS)<<"Invalid viewer!"<<std::endl;
560}
561
562void DistortionManipulator::updateDistortionMesh()
563{
[385]564        // Create mesh vertex array & textCoord array
[384]565        osg::Vec3Array* vertices = new osg::Vec3Array;
566        osg::Vec2Array* texCoords = new osg::Vec2Array;
[386]567        osg::Vec4Array* colors = new osg::Vec4Array;
[384]568
569        for(unsigned int i=0;i<_distortionSet->getDistortionMesh()->size();i++)
570        {
[387]571                osg::Vec4 tmpSrc = _distortionSet->getDistortionMesh()->at(i);
572
[384]573                // Scale vector with the screen resolution
[387]574                osg::Vec3 tmpVec = osg::Vec3(   tmpSrc.x()*_screenPixWidth,
575                                                                                tmpSrc.y()*_screenPixHeight,
[384]576                                                                                0.0     );
577                vertices->push_back( tmpVec );
[391]578                //OSG_ALWAYS<<"Transfering mesh vertex : X:"<<tmpVec.x()<<" Y:"<<tmpVec.y()<<" Z:"<<tmpVec.z()<<std::endl;
[384]579
580                // Note texCoords
[387]581                osg::Vec2 tmpTexCoords = osg::Vec2(     tmpSrc.z()*_screenPixWidth,
582                                                                                        tmpSrc.w()*_screenPixHeight );
[393]583
[384]584                texCoords->push_back(tmpTexCoords);
[387]585                //OSG_ALWAYS<<"Transfering texcoord vertex : X:"<<tmpTexCoords.x()<<" Y:"<<tmpTexCoords.y()<<std::endl;
[386]586
587                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
[384]588        }
589
[387]590        // --------- Apply Arrays -----------------
[386]591        osg::Geometry* geom = _distortionSet->getDistortionInternals()->getChild(osgViewer::DistortionSet::MESH)->asGeode()->getDrawable(0)->asGeometry();
592
[387]593        // If arraysize differs: Replace primite sets
594        bool regeneratePrimitiveSets = true;
595        osg::Vec3Array* prevArray = dynamic_cast<osg::Vec3Array*>(geom->getVertexArray());
596        if(prevArray) 
597                regeneratePrimitiveSets = prevArray->size()!=vertices->size()?true:false;
598       
599        // Set new Arrays
[386]600        geom->setVertexArray(vertices);
601        geom->setTexCoordArray(0, texCoords);   // todo: 0 ist hardcoded und müsste durch getTexUnitScene() ersetzt werden
602        geom->setColorArray(colors);
[387]603
604        // If required: regenerate primitiveset:
605        OSG_ALWAYS<<"PrimitiveSet regeneration required!"<<std::endl;
606        geom->removePrimitiveSet(0, geom->getNumPrimitiveSets());       
607        //// Create new primitives : Quads grid
[386]608        unsigned int rows = _distortionSet->getDistortionMeshRows();
609        unsigned int columns = _distortionSet->getDistortionMeshColumns();
610        for ( unsigned int row=0; row<rows-1; row++ )   // each strip consists of two affected vertex rows, so we need only row-1 strips.
611        {
612                osg::ref_ptr<osg::DrawElementsUInt> de = new osg::DrawElementsUInt(osg::PrimitiveSet::QUAD_STRIP, columns*2);   // columns*2 = number of involved vertices for this strip.
613                for ( unsigned int col=0; col<columns; col++ )
614                {
615                        (*de)[col*2 + 0] = row*columns + col;
616                        (*de)[col*2 + 1] = (row+1)*columns + col;
617                }
618                geom->addPrimitiveSet( de.get() );
619        }
[384]620}
Note: See TracBrowser for help on using the repository browser.