<commit_before>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#ifndef MemoryChannel_H
#define MemoryChannel_H

//===========================================================================
//
// .DESCRIPTION
//              Pointer based communication channel for communication between two
//              thread. It does not copy any data in or out the channel so the
//              item that is put in can not be used untill the other thread has
//              given it back. There is no support for detecting the return of a
//              item. The channel is half-duplex.
//              For comminication between 1 writer and 1 reader use the MemoryChannel
//              class, for comminication between multiple writer and 1 reader use the
//              MemoryChannelMultipleWriter. There is no support for multiple readers.
//
// .TYPICAL USE:
//              to communicate between threads.
//
// .EXAMPLE:
//              See AsyncFile.C
//===========================================================================
//
//
// MemoryChannel( int size= 256);
//   Constuctor
// Parameters:
//      size : amount of pointer it can hold
//
// void operator ++ ();
//   increments the index with one, if size is reached it is set to zero
//
// virtual void write( T *t);
//   Puts the item in the channel if the channel is full an error is reported.
// Parameters:
//      t: pointer to item to put in the channel, after this the item
//                        is shared with the other thread.
// errors
//                      AFS_ERROR_CHANNALFULL, channel is full
//
// T* read();
//      Reads a itemn from the channel, if channel is empty it blocks untill
//              an item can be read.
// return
//                      T : item from the channel
//
// T* tryRead();
//      Reads a item from the channel, if channel is empty it returns zero.
// return
//                      T : item from the channel or zero if channel is empty.
//

#include "ErrorHandlingMacros.hpp"
#include "CircularIndex.hpp"
#include "NdbMutex.h"
#include "NdbCondition.h"
#include <NdbOut.hpp>

template <class T>
class MemoryChannel
{
public:
  MemoryChannel( int size= 256);
  virtual ~MemoryChannel( );

  void writeChannel( T *t);
  void writeChannelNoSignal( T *t);
  T* readChannel();
  T* tryReadChannel();

private:
  int theSize;
  T **theChannel;
  CircularIndex theWriteIndex;
  CircularIndex theReadIndex;
  NdbMutex* theMutexPtr;
  NdbCondition* theConditionPtr;

  template<class U>
  friend NdbOut& operator<<(NdbOut& out, const MemoryChannel<U> & chn);
};

template <class T>
NdbOut& operator<<(NdbOut& out, const MemoryChannel<T> & chn)
{
  NdbMutex_Lock(chn.theMutexPtr);
  out << "[ theSize: " << chn.theSize
      << " theReadIndex: " << (int)chn.theReadIndex
      << " theWriteIndex: " << (int)chn.theWriteIndex << " ]";
  NdbMutex_Unlock(chn.theMutexPtr);
  return out;
}

template <class T> MemoryChannel<T>::MemoryChannel( int size):
        theSize(size),
        theChannel(new T*[size] ),
        theWriteIndex(0, size),
        theReadIndex(0, size)
{
  theMutexPtr = NdbMutex_Create();
  theConditionPtr = NdbCondition_Create();
}

template <class T> MemoryChannel<T>::~MemoryChannel( )
{
  NdbMutex_Destroy(theMutexPtr);
  NdbCondition_Destroy(theConditionPtr);
  delete [] theChannel;
}

template <class T> void MemoryChannel<T>::writeChannel( T *t)
{

  NdbMutex_Lock(theMutexPtr);
  if(full(theWriteIndex, theReadIndex) || theChannel == NULL) abort();
  theChannel[theWriteIndex]= t;
  ++theWriteIndex;
  NdbMutex_Unlock(theMutexPtr);
  NdbCondition_Signal(theConditionPtr);
}

template <class T> void MemoryChannel<T>::writeChannelNoSignal( T *t)
{

  NdbMutex_Lock(theMutexPtr);
  if(full(theWriteIndex, theReadIndex) || theChannel == NULL) abort();
  theChannel[theWriteIndex]= t;
  ++theWriteIndex;
  NdbMutex_Unlock(theMutexPtr);
}

template <class T> T* MemoryChannel<T>::readChannel()
{
  T* tmp;

  NdbMutex_Lock(theMutexPtr);
  while ( empty(theWriteIndex, theReadIndex) )
  {
    NdbCondition_Wait(theConditionPtr,
                        theMutexPtr);
  }

  tmp= theChannel[theReadIndex];
  ++theReadIndex;
  NdbMutex_Unlock(theMutexPtr);
  return tmp;
}

template <class T> T* MemoryChannel<T>::tryReadChannel()
{
  T* tmp= 0;
  NdbMutex_Lock(theMutexPtr);
  if ( !empty(theWriteIndex, theReadIndex) )
  {
    tmp= theChannel[theReadIndex];
    ++theReadIndex;
  }
  NdbMutex_Unlock(theMutexPtr);
  return tmp;
}

#endif // MemoryChannel_H

<commit_msg>ndb - bug#27942   Increase size of memory channel<commit_after>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#ifndef MemoryChannel_H
#define MemoryChannel_H

//===========================================================================
//
// .DESCRIPTION
//              Pointer based communication channel for communication between two
//              thread. It does not copy any data in or out the channel so the
//              item that is put in can not be used untill the other thread has
//              given it back. There is no support for detecting the return of a
//              item. The channel is half-duplex.
//              For comminication between 1 writer and 1 reader use the MemoryChannel
//              class, for comminication between multiple writer and 1 reader use the
//              MemoryChannelMultipleWriter. There is no support for multiple readers.
//
// .TYPICAL USE:
//              to communicate between threads.
//
// .EXAMPLE:
//              See AsyncFile.C
//===========================================================================
//
//
// MemoryChannel( int size= 256);
//   Constuctor
// Parameters:
//      size : amount of pointer it can hold
//
// void operator ++ ();
//   increments the index with one, if size is reached it is set to zero
//
// virtual void write( T *t);
//   Puts the item in the channel if the channel is full an error is reported.
// Parameters:
//      t: pointer to item to put in the channel, after this the item
//                        is shared with the other thread.
// errors
//                      AFS_ERROR_CHANNALFULL, channel is full
//
// T* read();
//      Reads a itemn from the channel, if channel is empty it blocks untill
//              an item can be read.
// return
//                      T : item from the channel
//
// T* tryRead();
//      Reads a item from the channel, if channel is empty it returns zero.
// return
//                      T : item from the channel or zero if channel is empty.
//

#include "ErrorHandlingMacros.hpp"
#include "CircularIndex.hpp"
#include "NdbMutex.h"
#include "NdbCondition.h"
#include <NdbOut.hpp>

template <class T>
class MemoryChannel
{
public:
  MemoryChannel( int size= 512);
  virtual ~MemoryChannel( );

  void writeChannel( T *t);
  void writeChannelNoSignal( T *t);
  T* readChannel();
  T* tryReadChannel();

private:
  int theSize;
  T **theChannel;
  CircularIndex theWriteIndex;
  CircularIndex theReadIndex;
  NdbMutex* theMutexPtr;
  NdbCondition* theConditionPtr;

  template<class U>
  friend NdbOut& operator<<(NdbOut& out, const MemoryChannel<U> & chn);
};

template <class T>
NdbOut& operator<<(NdbOut& out, const MemoryChannel<T> & chn)
{
  NdbMutex_Lock(chn.theMutexPtr);
  out << "[ theSize: " << chn.theSize
      << " theReadIndex: " << (int)chn.theReadIndex
      << " theWriteIndex: " << (int)chn.theWriteIndex << " ]";
  NdbMutex_Unlock(chn.theMutexPtr);
  return out;
}

template <class T> MemoryChannel<T>::MemoryChannel( int size):
        theSize(size),
        theChannel(new T*[size] ),
        theWriteIndex(0, size),
        theReadIndex(0, size)
{
  theMutexPtr = NdbMutex_Create();
  theConditionPtr = NdbCondition_Create();
}

template <class T> MemoryChannel<T>::~MemoryChannel( )
{
  NdbMutex_Destroy(theMutexPtr);
  NdbCondition_Destroy(theConditionPtr);
  delete [] theChannel;
}

template <class T> void MemoryChannel<T>::writeChannel( T *t)
{

  NdbMutex_Lock(theMutexPtr);
  if(full(theWriteIndex, theReadIndex) || theChannel == NULL) abort();
  theChannel[theWriteIndex]= t;
  ++theWriteIndex;
  NdbMutex_Unlock(theMutexPtr);
  NdbCondition_Signal(theConditionPtr);
}

template <class T> void MemoryChannel<T>::writeChannelNoSignal( T *t)
{

  NdbMutex_Lock(theMutexPtr);
  if(full(theWriteIndex, theReadIndex) || theChannel == NULL) abort();
  theChannel[theWriteIndex]= t;
  ++theWriteIndex;
  NdbMutex_Unlock(theMutexPtr);
}

template <class T> T* MemoryChannel<T>::readChannel()
{
  T* tmp;

  NdbMutex_Lock(theMutexPtr);
  while ( empty(theWriteIndex, theReadIndex) )
  {
    NdbCondition_Wait(theConditionPtr,
                        theMutexPtr);
  }

  tmp= theChannel[theReadIndex];
  ++theReadIndex;
  NdbMutex_Unlock(theMutexPtr);
  return tmp;
}

template <class T> T* MemoryChannel<T>::tryReadChannel()
{
  T* tmp= 0;
  NdbMutex_Lock(theMutexPtr);
  if ( !empty(theWriteIndex, theReadIndex) )
  {
    tmp= theChannel[theReadIndex];
    ++theReadIndex;
  }
  NdbMutex_Unlock(theMutexPtr);
  return tmp;
}

#endif // MemoryChannel_H

<|endoftext|>


<commit_before>#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/BlendFunc>
#include <osg/ClearNode>

#include <osgUtil/Tesselator>
#include <osgUtil/TransformCallback>
#include <osgUtil/CullVisitor>

#include <osgGA/TrackballManipulator>
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>

#include <osgSim/ScalarsToColors>
#include <osgSim/ColorRange>
#include <osgSim/ScalarBar>

#include <sstream>
#include <math.h>

using namespace osgSim;

osg::Node* createScalarBar()
{
#if 1
    //ScalarsToColors* stc = new ScalarsToColors(0.0f,1.0f);
    //ScalarBar* sb = new ScalarBar(2,3,stc,"STC_ScalarBar");

    // Create a custom color set
    std::vector<osg::Vec4> cs;
    cs.push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f));   // R
    cs.push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f));   // G
    cs.push_back(osg::Vec4(1.0f,1.0f,0.0f,1.0f));   // G
    cs.push_back(osg::Vec4(0.0f,0.0f,1.0f,1.0f));   // B
    cs.push_back(osg::Vec4(0.0f,1.0f,1.0f,1.0f));   // R

    // Create a custom scalar printer
    struct MyScalarPrinter: public ScalarBar::ScalarPrinter
    {
        std::string printScalar(float scalar)
        {
            std::cout<<"In MyScalarPrinter::printScalar"<<std::endl;
            if(scalar==0.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Bottom";
            else if(scalar==0.5f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Middle";
            else if(scalar==1.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Top";
            else return ScalarBar::ScalarPrinter::printScalar(scalar);
        }
    };

    ColorRange* cr = new ColorRange(0.0f,1.0f,cs);
    ScalarBar* sb = new ScalarBar(20, 11, cr, "ScalarBar", ScalarBar::VERTICAL, 4.0f, new MyScalarPrinter);
    sb->setScalarPrinter(new MyScalarPrinter);

    return sb;
#else
    ScalarBar *sb = new ScalarBar;
    ScalarBar::TextProperties tp;
    tp._fontFile = "fonts/times.ttf";

    sb->setTextProperties(tp);

    return sb;
#endif

}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates both text, animation and billboard via custom transform to create the OpenSceneGraph logo..");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("ps","Render the Professional Services logo");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::Node* node = createScalarBar();

    // add model to viewer.
    viewer.setSceneData( node );

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();
    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Removed the ScalarBar:: from the from of the ScalarPrinter::printScalar() calls.<commit_after>#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/BlendFunc>
#include <osg/ClearNode>

#include <osgUtil/Tesselator>
#include <osgUtil/TransformCallback>
#include <osgUtil/CullVisitor>

#include <osgGA/TrackballManipulator>
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>

#include <osgSim/ScalarsToColors>
#include <osgSim/ColorRange>
#include <osgSim/ScalarBar>

#include <sstream>
#include <math.h>

using namespace osgSim;

osg::Node* createScalarBar()
{
#if 1
    //ScalarsToColors* stc = new ScalarsToColors(0.0f,1.0f);
    //ScalarBar* sb = new ScalarBar(2,3,stc,"STC_ScalarBar");

    // Create a custom color set
    std::vector<osg::Vec4> cs;
    cs.push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f));   // R
    cs.push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f));   // G
    cs.push_back(osg::Vec4(1.0f,1.0f,0.0f,1.0f));   // G
    cs.push_back(osg::Vec4(0.0f,0.0f,1.0f,1.0f));   // B
    cs.push_back(osg::Vec4(0.0f,1.0f,1.0f,1.0f));   // R

    // Create a custom scalar printer
    struct MyScalarPrinter: public ScalarBar::ScalarPrinter
    {
        std::string printScalar(float scalar)
        {
            std::cout<<"In MyScalarPrinter::printScalar"<<std::endl;
            if(scalar==0.0f) return ScalarPrinter::printScalar(scalar)+" Bottom";
            else if(scalar==0.5f) return ScalarPrinter::printScalar(scalar)+" Middle";
            else if(scalar==1.0f) return ScalarPrinter::printScalar(scalar)+" Top";
            else return ScalarPrinter::printScalar(scalar);
        }
    };

    ColorRange* cr = new ColorRange(0.0f,1.0f,cs);
    ScalarBar* sb = new ScalarBar(20, 11, cr, "ScalarBar", ScalarBar::VERTICAL, 4.0f, new MyScalarPrinter);
    sb->setScalarPrinter(new MyScalarPrinter);

    return sb;
#else
    ScalarBar *sb = new ScalarBar;
    ScalarBar::TextProperties tp;
    tp._fontFile = "fonts/times.ttf";

    sb->setTextProperties(tp);

    return sb;
#endif

}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates both text, animation and billboard via custom transform to create the OpenSceneGraph logo..");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("ps","Render the Professional Services logo");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::Node* node = createScalarBar();

    // add model to viewer.
    viewer.setSceneData( node );

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();
    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <osg/Vec3>
#include <osg/Matrix>
#include <osg/io_utils>

#include <iostream>

void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeFrustum(left,right,bottom,top,zNear,zFar);

    double c_left=0;
    double c_right=0;
    double c_top=0;
    double c_bottom=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testFrustum"<<f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar)<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeOrtho(left,right,bottom,top,zNear,zFar);

    double c_left=0;
    double c_right=0;
    double c_top=0;
    double c_bottom=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testOrtho "<< f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar) << std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testPerspective(double fovy,double aspect,double zNear,double zFar)
{
    osg::Matrix f;
    f.makePerspective(fovy,aspect,zNear,zFar);

    double c_fovy=0;
    double c_aspect=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testPerspective "<< f.getPerspective(c_fovy,c_aspect,c_zNear,c_zFar) << std::endl;
    std::cout << "  fovy = "<<fovy<<" compute "<<c_fovy<<std::endl;
    std::cout << "  aspect = "<<aspect<<" compute "<<c_aspect<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
    osg::Matrix mv;
    mv.makeLookAt(eye,center,up);

    osg::Vec3 c_eye,c_center,c_up;
    mv.getLookAt(c_eye,c_center,c_up);

    std::cout << "testLookAt"<<std::endl;
    std::cout << "  eye "<<eye<< " compute "<<c_eye<<std::endl;
    std::cout << "  eye "<<center<< " compute "<<c_center<<std::endl;
    std::cout << "  eye "<<up<< " compute "<<c_up<<std::endl;

    std::cout << std::endl;

}

void sizeOfTest()
{
  std::cout<<"sizeof(bool)=="<<sizeof(bool)<<std::endl;
  std::cout<<"sizeof(char)=="<<sizeof(char)<<std::endl;
  std::cout<<"sizeof(short)=="<<sizeof(short)<<std::endl;
  std::cout<<"sizeof(int)=="<<sizeof(int)<<std::endl;
  std::cout<<"sizeof(long)=="<<sizeof(long)<<std::endl;
  std::cout<<"sizeof(long int)=="<<sizeof(long int)<<std::endl;

#if defined(_MSC_VER)
  // long long isn't supported on VS6.0...
  std::cout<<"sizeof(__int64)=="<<sizeof(__int64)<<std::endl;
#else
  std::cout<<"sizeof(long long)=="<<sizeof(long long)<<std::endl;
#endif
  std::cout<<"sizeof(float)=="<<sizeof(float)<<std::endl;
  std::cout<<"sizeof(double)=="<<sizeof(double)<<std::endl;

  std::cout<<"sizeof(std::istream::pos_type)=="<<sizeof(std::istream::pos_type)<<std::endl;
  std::cout<<"sizeof(std::istream::off_type)=="<<sizeof(std::istream::off_type)<<std::endl;
  std::cout<<"sizeof(OpenThreads::Mutex)=="<<sizeof(OpenThreads::Mutex)<<std::endl;

}

void testQuatRotate(const osg::Vec3d& from, const osg::Vec3d& to)
{
    osg::Quat q_nicolas;
    q_nicolas.makeRotate(from,to);

    osg::Quat q_original;
    q_original.makeRotate_original(from,to);

    std::cout<<"osg::Quat::makeRotate("<<from<<", "<<to<<")"<<std::endl;
    std::cout<<"  q_nicolas = "<<q_nicolas<<std::endl;
    std::cout<<"  q_original = "<<q_original<<std::endl;
    std::cout<<"  from * M4x4(q_nicolas) = "<<from * osg::Matrixd::rotate(q_nicolas)<<std::endl;
    std::cout<<"  from * M4x4(q_original) = "<<from * osg::Matrixd::rotate(q_original)<<std::endl;
}

void testQuat()
{
    osg::Quat q1;
    q1.makeRotate(osg::DegreesToRadians(30.0),0.0f,0.0f,1.0f);

    osg::Quat q2;
    q2.makeRotate(osg::DegreesToRadians(133.0),0.0f,1.0f,1.0f);

    osg::Quat q1_2 = q1*q2;
    osg::Quat q2_1 = q2*q1;

    osg::Matrix m1 = osg::Matrix::rotate(q1);
    osg::Matrix m2 = osg::Matrix::rotate(q2);

    osg::Matrix m1_2 = m1*m2;
    osg::Matrix m2_1 = m2*m1;

    osg::Quat qm1_2;
    qm1_2.set(m1_2);

    osg::Quat qm2_1;
    qm2_1.set(m2_1);

    std::cout<<"q1*q2 = "<<q1_2<<std::endl;
    std::cout<<"q2*q1 = "<<q2_1<<std::endl;
    std::cout<<"m1*m2 = "<<qm1_2<<std::endl;
    std::cout<<"m2*m1 = "<<qm2_1<<std::endl;

    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,1.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,1.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,1.0,1.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(-1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(-1.0,0.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,1.0,0.0),osg::Vec3d(0.0,-1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,-1.0,0.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,1.0),osg::Vec3d(0.0,0.0,-1.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,-1.0),osg::Vec3d(0.0,0.0,1.0));

}

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
    arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    bool printQualifiedTest = false;
    while (arguments.read("qt")) printQualifiedTest = true;

    bool printMatrixTest = false;
    while (arguments.read("matrix")) printMatrixTest = true;

    bool printSizeOfTest = false;
    while (arguments.read("sizeof")) printSizeOfTest = true;

    bool printQuatTest = false;
    while (arguments.read("quat")) printQuatTest = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (printQuatTest)
    {
        testQuat();
    }

    if (printMatrixTest)
    {
        std::cout<<"******   Running matrix tests   ******"<<std::endl;

        testFrustum(-1,1,-1,1,1,1000);
        testFrustum(0,1,1,2,2.5,100000);

        testOrtho(0,1,1,2,2.1,1000);
        testOrtho(-1,10,1,20,2.5,100000);

        testPerspective(20,1,1,1000);
        testPerspective(90,2,1,1000);

        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));

    }

    if (printSizeOfTest)
    {
        std::cout<<"**** sizeof() tests  ******"<<std::endl;

        sizeOfTest();

        std::cout<<std::endl;
    }

    if (printQualifiedTest)
    {
         std::cout<<"*****   Qualified Tests  ******"<<std::endl;

         osgUtx::QualifiedTestPrinter printer;
         osgUtx::TestGraph::instance().root()->accept( printer );
         std::cout<<std::endl;
    }

    std::cout<<"******   Running tests   ******"<<std::endl;

    // Global Data or Context
    osgUtx::TestContext ctx;
    osgUtx::TestRunner runner( ctx );
    runner.specify("root");

    osgUtx::TestGraph::instance().root()->accept( runner );

    return 0;
}
<commit_msg>Fixed typo in testLookAt debug info.<commit_after>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <osg/Vec3>
#include <osg/Matrix>
#include <osg/io_utils>

#include <iostream>

void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeFrustum(left,right,bottom,top,zNear,zFar);

    double c_left=0;
    double c_right=0;
    double c_top=0;
    double c_bottom=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testFrustum"<<f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar)<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeOrtho(left,right,bottom,top,zNear,zFar);

    double c_left=0;
    double c_right=0;
    double c_top=0;
    double c_bottom=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testOrtho "<< f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar) << std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testPerspective(double fovy,double aspect,double zNear,double zFar)
{
    osg::Matrix f;
    f.makePerspective(fovy,aspect,zNear,zFar);

    double c_fovy=0;
    double c_aspect=0;
    double c_zNear=0;
    double c_zFar=0;

    std::cout << "testPerspective "<< f.getPerspective(c_fovy,c_aspect,c_zNear,c_zFar) << std::endl;
    std::cout << "  fovy = "<<fovy<<" compute "<<c_fovy<<std::endl;
    std::cout << "  aspect = "<<aspect<<" compute "<<c_aspect<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
    osg::Matrix mv;
    mv.makeLookAt(eye,center,up);

    osg::Vec3 c_eye,c_center,c_up;
    mv.getLookAt(c_eye,c_center,c_up);

    std::cout << "testLookAt"<<std::endl;
    std::cout << "  eye "<<eye<< " compute "<<c_eye<<std::endl;
    std::cout << "  center "<<center<< " compute "<<c_center<<std::endl;
    std::cout << "  up "<<up<< " compute "<<c_up<<std::endl;

    std::cout << std::endl;

}

void sizeOfTest()
{
  std::cout<<"sizeof(bool)=="<<sizeof(bool)<<std::endl;
  std::cout<<"sizeof(char)=="<<sizeof(char)<<std::endl;
  std::cout<<"sizeof(short)=="<<sizeof(short)<<std::endl;
  std::cout<<"sizeof(int)=="<<sizeof(int)<<std::endl;
  std::cout<<"sizeof(long)=="<<sizeof(long)<<std::endl;
  std::cout<<"sizeof(long int)=="<<sizeof(long int)<<std::endl;

#if defined(_MSC_VER)
  // long long isn't supported on VS6.0...
  std::cout<<"sizeof(__int64)=="<<sizeof(__int64)<<std::endl;
#else
  std::cout<<"sizeof(long long)=="<<sizeof(long long)<<std::endl;
#endif
  std::cout<<"sizeof(float)=="<<sizeof(float)<<std::endl;
  std::cout<<"sizeof(double)=="<<sizeof(double)<<std::endl;

  std::cout<<"sizeof(std::istream::pos_type)=="<<sizeof(std::istream::pos_type)<<std::endl;
  std::cout<<"sizeof(std::istream::off_type)=="<<sizeof(std::istream::off_type)<<std::endl;
  std::cout<<"sizeof(OpenThreads::Mutex)=="<<sizeof(OpenThreads::Mutex)<<std::endl;

}

void testQuatRotate(const osg::Vec3d& from, const osg::Vec3d& to)
{
    osg::Quat q_nicolas;
    q_nicolas.makeRotate(from,to);

    osg::Quat q_original;
    q_original.makeRotate_original(from,to);

    std::cout<<"osg::Quat::makeRotate("<<from<<", "<<to<<")"<<std::endl;
    std::cout<<"  q_nicolas = "<<q_nicolas<<std::endl;
    std::cout<<"  q_original = "<<q_original<<std::endl;
    std::cout<<"  from * M4x4(q_nicolas) = "<<from * osg::Matrixd::rotate(q_nicolas)<<std::endl;
    std::cout<<"  from * M4x4(q_original) = "<<from * osg::Matrixd::rotate(q_original)<<std::endl;
}

void testQuat()
{
    osg::Quat q1;
    q1.makeRotate(osg::DegreesToRadians(30.0),0.0f,0.0f,1.0f);

    osg::Quat q2;
    q2.makeRotate(osg::DegreesToRadians(133.0),0.0f,1.0f,1.0f);

    osg::Quat q1_2 = q1*q2;
    osg::Quat q2_1 = q2*q1;

    osg::Matrix m1 = osg::Matrix::rotate(q1);
    osg::Matrix m2 = osg::Matrix::rotate(q2);

    osg::Matrix m1_2 = m1*m2;
    osg::Matrix m2_1 = m2*m1;

    osg::Quat qm1_2;
    qm1_2.set(m1_2);

    osg::Quat qm2_1;
    qm2_1.set(m2_1);

    std::cout<<"q1*q2 = "<<q1_2<<std::endl;
    std::cout<<"q2*q1 = "<<q2_1<<std::endl;
    std::cout<<"m1*m2 = "<<qm1_2<<std::endl;
    std::cout<<"m2*m1 = "<<qm2_1<<std::endl;

    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,1.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,1.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,1.0,1.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(1.0,0.0,0.0),osg::Vec3d(-1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(-1.0,0.0,0.0),osg::Vec3d(1.0,0.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,1.0,0.0),osg::Vec3d(0.0,-1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,-1.0,0.0),osg::Vec3d(0.0,1.0,0.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,1.0),osg::Vec3d(0.0,0.0,-1.0));
    testQuatRotate(osg::Vec3d(0.0,0.0,-1.0),osg::Vec3d(0.0,0.0,1.0));

}

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
    arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    bool printQualifiedTest = false;
    while (arguments.read("qt")) printQualifiedTest = true;

    bool printMatrixTest = false;
    while (arguments.read("matrix")) printMatrixTest = true;

    bool printSizeOfTest = false;
    while (arguments.read("sizeof")) printSizeOfTest = true;

    bool printQuatTest = false;
    while (arguments.read("quat")) printQuatTest = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (printQuatTest)
    {
        testQuat();
    }

    if (printMatrixTest)
    {
        std::cout<<"******   Running matrix tests   ******"<<std::endl;

        testFrustum(-1,1,-1,1,1,1000);
        testFrustum(0,1,1,2,2.5,100000);

        testOrtho(0,1,1,2,2.1,1000);
        testOrtho(-1,10,1,20,2.5,100000);

        testPerspective(20,1,1,1000);
        testPerspective(90,2,1,1000);

        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));

    }

    if (printSizeOfTest)
    {
        std::cout<<"**** sizeof() tests  ******"<<std::endl;

        sizeOfTest();

        std::cout<<std::endl;
    }

    if (printQualifiedTest)
    {
         std::cout<<"*****   Qualified Tests  ******"<<std::endl;

         osgUtx::QualifiedTestPrinter printer;
         osgUtx::TestGraph::instance().root()->accept( printer );
         std::cout<<std::endl;
    }

    std::cout<<"******   Running tests   ******"<<std::endl;

    // Global Data or Context
    osgUtx::TestContext ctx;
    osgUtx::TestRunner runner( ctx );
    runner.specify("root");

    osgUtx::TestGraph::instance().root()->accept( runner );

    return 0;
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/algorithm/volume/volumevoronoi.h>

namespace inviwo {
namespace util {

std::shared_ptr<Volume> voronoiSegmentation(
    const size3_t volumeDimensions, const mat4& indexToModelMatrix,
    const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices,
    const std::optional<std::vector<float>>& weights, bool weightedVoronoi) {

    if (seedPointsWithIndices.size() == 0) {
        throw Exception("No seed points, cannot create volume voronoi segmentation",
                        IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    if (weightedVoronoi && weights.has_value() &&
        weights.value().size() != seedPointsWithIndices.size()) {
        throw Exception(
            "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)",
            IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions);
    auto newVolume = std::make_shared<Volume>(newVolumeRep);

    newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size()));
    newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange;

    auto volumeIndices = newVolumeRep->getDataTyped();
    util::IndexMapper3D index(volumeDimensions);

    if (weightedVoronoi && weights.has_value()) {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto zipped = util::zip(seedPointsWithIndices, weights.value());

            auto&& [posWithIndex, weight] = *std::min_element(
                zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) {
                    auto&& [p1, w1] = i1;
                    auto&& [p2, w2] = i2;

                    return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 <
                           glm::distance2(p2.second, transformedVoxelPos) - w2 * w2;
                });
            volumeIndices[index(voxelPos)] = posWithIndex.first;
        });
    } else {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(),
                                       [transformedVoxelPos](const auto& p1, const auto& p2) {
                                           return glm::distance2(p1.second, transformedVoxelPos) <
                                                  glm::distance2(p2.second, transformedVoxelPos);
                                       });
            volumeIndices[index(voxelPos)] = it->first;
        });
    }

    return newVolume;
};

}  // namespace util
}  // namespace inviwo
<commit_msg>Throw when there are no weights but weightedVoronoi = true<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/algorithm/volume/volumevoronoi.h>

namespace inviwo {
namespace util {

std::shared_ptr<Volume> voronoiSegmentation(
    const size3_t volumeDimensions, const mat4& indexToModelMatrix,
    const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices,
    const std::optional<std::vector<float>>& weights, bool weightedVoronoi) {

    if (seedPointsWithIndices.size() == 0) {
        throw Exception("No seed points, cannot create volume voronoi segmentation",
                        IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    if (weightedVoronoi && !weights.has_value()) {
        throw Exception("Cannot use weighted voronoi when no weights are provided",
                        IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    if (weightedVoronoi && weights.has_value() &&
        weights.value().size() != seedPointsWithIndices.size()) {
        throw Exception(
            "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)",
            IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions);
    auto newVolume = std::make_shared<Volume>(newVolumeRep);

    newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size()));
    newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange;

    auto volumeIndices = newVolumeRep->getDataTyped();
    util::IndexMapper3D index(volumeDimensions);

    if (weightedVoronoi && weights.has_value()) {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto zipped = util::zip(seedPointsWithIndices, weights.value());

            auto&& [posWithIndex, weight] = *std::min_element(
                zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) {
                    auto&& [p1, w1] = i1;
                    auto&& [p2, w2] = i2;

                    return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 <
                           glm::distance2(p2.second, transformedVoxelPos) - w2 * w2;
                });
            volumeIndices[index(voxelPos)] = posWithIndex.first;
        });
    } else {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(),
                                       [transformedVoxelPos](const auto& p1, const auto& p2) {
                                           return glm::distance2(p1.second, transformedVoxelPos) <
                                                  glm::distance2(p2.second, transformedVoxelPos);
                                       });
            volumeIndices[index(voxelPos)] = it->first;
        });
    }

    return newVolume;
};

}  // namespace util
}  // namespace inviwo
<|endoftext|>


<commit_before>/*
    Proyecto 2
    Luis Miranda
    Cristian Medina
*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
#include <set>

using namespace std;

/*
    Clase que define la estrutura nodo
*/

class Node
{
public:
    int color, satDegree, posColor;
    vector<int> posibleColor, edge;

    Node(int c=0, int s=0):color(c),satDegree(s),posColor(INT_MAX){};
    ~Node(){};

};

/*
    Compara la conectividad de 2 nodos
*/

class CompareDegree
{
public:
    bool operator()(const Node* left, const Node* right) const{
	return left->edge.size() < right->edge.size();
    }
};

/*
    Compara la saturacion de 2 nodos
*/

class CompareSatur
{
public:
    bool operator()(const Node* left, const Node* right) const{
	// if(left->satDegree == right->satDegree){

	//     cout << "yep"<<endl;
	//     return left->edge.size() < right->edge.size();
	// }else
	    return left->satDegree >= right->satDegree;
    }
};

//==============================================================================
/*
    Heuritica de desaturacion
*/
pair< int, vector< pair<int,int> > > desatur(vector<Node> graph, int n){

    vector< pair<int,Node*> > saturation;
    int max_color = 1, top = 1;
    bool cliq = true;
    set<int> usedColor;
    vector< pair<int,int> > clique;

    // for(int i = 0; i<graph.size(); i++){
    // 	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    // 	cout<<"\t Sat: "<<graph[i].satDegree;
    // 	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    // 	for(int j=0;j<graph[i].edge.size();j++)
    // 	    cout<<graph[i].edge[j]<<" , ";
    // 	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    // }

    for(int i = 0; i<n; i++){

	saturation.push_back(make_pair(i,&(graph[i])));
    }

    sort(saturation.begin(),saturation.end(),
	 [](pair<int,Node*> left, pair<int,Node*> right){
	     if(left.second->color == right.second->color)
		 if(left.second->satDegree == right.second->satDegree){
//	out<<left.second->satDegree<<"\t"<<right.second->satDegree<<endl;
		     return left.second->edge.size() >= right.second->edge.size();
		 }else
		     return left.second->satDegree >= right.second->satDegree;
	     else
		 return left.second->color < right.second->color;
	 }
	);
    saturation[0].second->posColor = 1;
    while(!saturation[0].second->color){
	// cout << "while"<< endl;
	// for(int i = 0; i<graph.size(); i++){
	//     cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
	//     cout<<"\t Sat: "<<graph[i].satDegree;
	//     cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
	//     for(int j=0;j<graph[i].edge.size();j++)
	// 	cout<<graph[i].edge[j]<<" , ";
	//     cout<<"}\t posColor:"<<graph[i].posColor<<endl;
	// }
	saturation[0].second->color = saturation[0].second->posColor;
	top = saturation[0].second->color > top ? saturation[0].second->color :
	    top;

	if(cliq){
	    if(cliq = !usedColor.count(saturation[0].second->color)){
		clique.push_back(make_pair(saturation[0].first,saturation[0].second->color));
		usedColor.insert(saturation[0].second->color);
	    }else{
		cliq=false;
	    }
	}

	max_color = saturation[0].second->posColor;
	int m = saturation[0].second->edge.size();

	for(int i=0; i<m;i++){
	    graph[saturation[0].second->edge[i]].satDegree++;
	    Node node = graph[saturation[0].second->edge[i]];
	    set<int> posiblesColores;
	    graph[saturation[0].second->edge[i]].posColor = max_color+1;

	    for(int l = 1; l<=max_color+1 ; l++ )
		posiblesColores.insert(l);

	    for(int l=0; l<node.edge.size();l++){
		posiblesColores.erase(graph[node.edge[l]].color);
	    }
	    while(!(posiblesColores.empty())){
		graph[saturation[0].second->edge[i]].posColor =
		    graph[saturation[0].second->edge[i]].posColor
		    > (*posiblesColores.begin())?
		    (*posiblesColores.begin()):
		    graph[saturation[0].second->edge[i]].posColor;

		posiblesColores.erase(posiblesColores.begin());
	    }

	}
	sort(saturation.begin(),saturation.end(),
	     [](pair<int,Node*> left, pair<int,Node*> right){
		 if(left.second->color == right.second->color)
		     if(left.second->satDegree == right.second->satDegree){
//	      cout<<left.second->satDegree<<"\t"<<right.second->satDegree<<endl;
			 return left.second->edge.size() >= right.second->edge.size();
		     }else
			 return left.second->satDegree >= right.second->satDegree;
		 else
		     return left.second->color < right.second->color;
	     }
	    );
	// cout<<"sat"<<endl;
	// for(int i = 0; i<n; i++){
	//     cout<<"i: "<<i<<"\t Color: "<<saturation[i].second->color<<"\t Sat: "<<saturation[i].second->satDegree<<"\t Edges: "<<saturation[i].second->edge.size()<<" {";
	//     for(int j=0;j<saturation[i].second->edge.size();j++)
	// 	cout<<saturation[i].second->edge[j]<<" , ";
	//     cout<<"}\t posColor:"<<saturation[i].second->posColor<<endl;
	// }

    }

    cout << "end"<<endl;
    for(int i = 0; i<graph.size(); i++){
    	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    	cout<<"\t Sat: "<<graph[i].satDegree;
    	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    	for(int j=0;j<graph[i].edge.size();j++)
    	    cout<<graph[i].edge[j]<<" , ";
    	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    }

    return make_pair(top,clique);
}

//==============================================================================
/*
    Dado un caracter, separa un string en substring que almacena en un vector dado,
    cada vez que se encuentre con el caracter dado.
*/
void split(const string &s, char c, vector<string> &v){

    string::size_type i = 0;
    string::size_type j = s.find(c);

    while (j != string::npos){
        v.push_back(s.substr(i,j-i));
        i = ++j;
        j = s.find(c, j);

        if (j == string::npos){
            v.push_back(s.substr(i,s.length()));
        }
    }

}

//==============================================================================
/*
    Crea un grafo de
*/
vector<Node> readGraph(char* fileName, int &sizeGraph){

    ifstream currentFile (fileName);
    string rLine, pLine;
    vector<Node> output;

//     if ( !currentFile.is_open() ){
//         cout << "El archivo que especifico no existe.";
//         exit(1);
//     }
//     else {

    while (getline (currentFile, rLine)){

	    if (rLine[0] != 'c'){

	        vector<string> sString;

	        if (rLine[0] == 'p'){

	            split(&rLine[7],' ', sString);

	            int proxyInt;
	            istringstream buffer(sString[0]);
	            buffer >> proxyInt;

	            sizeGraph = proxyInt;
	            for (int i = 0; i < proxyInt; i++){
		        output.push_back(Node());
	            }
	        }
	        else if (rLine[0] == 'e'){

	            split(&rLine[2],' ', sString);

	            int indexEdge1, indexEdge2;
	            istringstream buffer(sString[0]);
	            buffer >> indexEdge1;
	            indexEdge1--;
	            istringstream buffer2(sString[1]);
	            buffer2 >> indexEdge2;
	            indexEdge2--;

	            output[indexEdge1].edge.push_back(indexEdge2);
	            output[indexEdge2].edge.push_back(indexEdge1);
	        }

	        //Muestra lo que se lee
		// for (int i = 0; i < sString.size(); i++){
		//     cout << sString[i] << " " << i << "\n";
		// }

	    }

    }
    currentFile.close();

    return output;
}

//==============================================================================
/*
    Algoritmo de Brelaz Modificado
*/

// void label(int node, vector<Node>& graph){

// }

void brelaz (int n, // Numero de vertices.
             int q, // Numero de colores de la heuristica.
             int w,  // Dimension inicial del Clique.
             vector<Node>& graph
             )
{
    vector<int> colorOrder;

    // bool back = false;
    // int k = w + 1;

    // while (true){
    //     if (!back){
    //         min(colorUsed + 1, q - 1);

    //     }
    //     else {

    //     }
    //     if () {
    //         if (k > n) {
    //             // EXIT IF
    //             if (q == w){
    //                 break;
    //             }
    //         }
    //         else{
    //             back = false;
    //         }
    //     }
    //     else {
    //         back = true;
    //     }
    //     if (back) {

    //         // EXIT IF
    //         if (k<w+1){
    //             break;
    //         }
    //     }
    // }
    // // STOP ??

}

//==============================================================================
/*
    Main
*/

int main( int argc, char *argv[] ){

    char *fileName;
    int nodeNum = 0;
    vector<Node> graph;

    if (argc < 2) {
        cout << "Especifique el nombre del archivo con el grafo por favor:\n";
        cin >> fileName;
    }
    else {
        fileName = argv[1];
    }
    graph = readGraph(fileName, nodeNum);

    // for(int i = 0; i<graph.size(); i++){
    // 	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    // 	cout<<"\t Sat: "<<graph[i].satDegree;
    // 	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    // 	for(int j=0;j<graph[i].edge.size();j++)
    // 	    cout<<graph[i].edge[j]<<" , ";
    // 	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    // }

    pair< int, vector< pair<int,int> > > ans = desatur(graph,graph.size());

    cout<<ans.first<<"\nclique"<<endl;
    for(int i =0; i<ans.second.size();i++)
	cout<<ans.second[i].first<<" c: "<<ans.second[i].second<<endl;

    for(int i = 0; i<graph.size(); i++){
    	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    	cout<<"\t Sat: "<<graph[i].satDegree;
    	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    	for(int j=0;j<graph[i].edge.size();j++)
    	    cout<<graph[i].edge[j]<<" , ";
    	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    }

    //=======

}

<commit_msg>brelaz con errores<commit_after>/*
    Proyecto 2
    Luis Miranda
    Cristian Medina
*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
#include <set>

using namespace std;

/*
    Clase que define la estrutura nodo
*/

class Node
{
public:
    int color, satDegree, posColor;
    vector<int>  edge;
    set<int> U; //posibleColor
    bool label;

    Node(int c=0, int s=0):color(c),satDegree(s),posColor(INT_MAX),label(false){};
    ~Node(){};

};

/*
    Compara la conectividad de 2 nodos
*/

class CompareDegree
{
public:
    bool operator()(const Node* left, const Node* right) const{
	return left->edge.size() < right->edge.size();
    }
};

/*
    Compara la saturacion de 2 nodos
*/

class CompareSatur
{
public:
    bool operator()(const Node* left, const Node* right) const{
	// if(left->satDegree == right->satDegree){

	//     cout << "yep"<<endl;
	//     return left->edge.size() < right->edge.size();
	// }else
	    return left->satDegree >= right->satDegree;
    }
};

//==============================================================================
/*
    Heuritica de desaturacion
*/

struct answer
{
    int w;
    int q;
    vector <pair<int,int> > order;
};

//pair< pair<int,int>,vector<pair<int,int> > >
answer desatur(vector<Node> graph, int n){

    answer ans;
    ans.w = 0;
    ans.q = 1;

    vector< pair<int,Node*> > saturation;
    int max_color = 1;
    //int top = 1;
    bool cliq = true;
    set<int> usedColor;
    //int clique = 0;
    //vector< pair<int,int> > order;

    // for(int i = 0; i<graph.size(); i++){
    // 	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    // 	cout<<"\t Sat: "<<graph[i].satDegree;
    // 	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    // 	for(int j=0;j<graph[i].edge.size();j++)
    // 	    cout<<graph[i].edge[j]<<" , ";
    // 	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    // }

    for(int i = 0; i<n; i++){

	saturation.push_back(make_pair(i,&(graph[i])));
    }

    sort(saturation.begin(),saturation.end(),
	 [](pair<int,Node*> left, pair<int,Node*> right){
	     if(left.second->color == right.second->color)
		 if(left.second->satDegree == right.second->satDegree){
//	out<<left.second->satDegree<<"\t"<<right.second->satDegree<<endl;
		     return left.second->edge.size() >= right.second->edge.size();
		 }else
		     return left.second->satDegree >= right.second->satDegree;
	     else
		 return left.second->color < right.second->color;
	 }
	);
    saturation[0].second->posColor = 1;
    while(!saturation[0].second->color){
	// cout << "while"<< endl;
	// for(int i = 0; i<graph.size(); i++){
	//     cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
	//     cout<<"\t Sat: "<<graph[i].satDegree;
	//     cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
	//     for(int j=0;j<graph[i].edge.size();j++)
	// 	cout<<graph[i].edge[j]<<" , ";
	//     cout<<"}\t posColor:"<<graph[i].posColor<<endl;
	// }
	saturation[0].second->color = saturation[0].second->posColor;
	ans.q = saturation[0].second->color > ans.q ? saturation[0].second->color :
	    ans.q;
	ans.order.push_back(make_pair(saturation[0].first,saturation[0].second->color));
	if(cliq){
	    if(cliq = !usedColor.count(saturation[0].second->color)){
		ans.w++;
		usedColor.insert(saturation[0].second->color);
	    }else{
		cliq=false;
	    }
	}

	max_color = saturation[0].second->posColor;
	int m = saturation[0].second->edge.size();

	for(int i=0; i<m;i++){
	    graph[saturation[0].second->edge[i]].satDegree++;
	    Node node = graph[saturation[0].second->edge[i]];
	    set<int> posiblesColores;
	    graph[saturation[0].second->edge[i]].posColor = max_color+1;

	    for(int l = 1; l<=max_color+1 ; l++ )
		posiblesColores.insert(l);

	    for(int l=0; l<node.edge.size();l++){
		posiblesColores.erase(graph[node.edge[l]].color);
	    }
	    while(!(posiblesColores.empty())){
		graph[saturation[0].second->edge[i]].posColor =
		    graph[saturation[0].second->edge[i]].posColor
		    > (*posiblesColores.begin())?
		    (*posiblesColores.begin()):
		    graph[saturation[0].second->edge[i]].posColor;

		posiblesColores.erase(posiblesColores.begin());
	    }

	}
	sort(saturation.begin(),saturation.end(),
	     [](pair<int,Node*> left, pair<int,Node*> right){
		 if(left.second->color == right.second->color)
		     if(left.second->satDegree == right.second->satDegree){
//	      cout<<left.second->satDegree<<"\t"<<right.second->satDegree<<endl;
			 return left.second->edge.size() >= right.second->edge.size();
		     }else
			 return left.second->satDegree >= right.second->satDegree;
		 else
		     return left.second->color < right.second->color;
	     }
	    );
	// cout<<"sat"<<endl;
	// for(int i = 0; i<n; i++){
	//     cout<<"i: "<<i<<"\t Color: "<<saturation[i].second->color<<"\t Sat: "<<saturation[i].second->satDegree<<"\t Edges: "<<saturation[i].second->edge.size()<<" {";
	//     for(int j=0;j<saturation[i].second->edge.size();j++)
	// 	cout<<saturation[i].second->edge[j]<<" , ";
	//     cout<<"}\t posColor:"<<saturation[i].second->posColor<<endl;
	// }

    }

    cout << "end"<<endl;
    for(int i = 0; i<graph.size(); i++){
    	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    	cout<<"\t Sat: "<<graph[i].satDegree;
    	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    	for(int j=0;j<graph[i].edge.size();j++)
    	    cout<<graph[i].edge[j]<<" , ";
    	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    }

//    return make_pair(make_pair(clique,top),order);
    return ans;
}

//==============================================================================
/*
    Dado un caracter, separa un string en substring que almacena en un vector dado,
    cada vez que se encuentre con el caracter dado.
*/
void split(const string &s, char c, vector<string> &v){

    string::size_type i = 0;
    string::size_type j = s.find(c);

    while (j != string::npos){
        v.push_back(s.substr(i,j-i));
        i = ++j;
        j = s.find(c, j);

        if (j == string::npos){
            v.push_back(s.substr(i,s.length()));
        }
    }

}

//==============================================================================
/*
    Crea un grafo de
*/
vector<Node> readGraph(char* fileName, int &sizeGraph){

    ifstream currentFile (fileName);
    string rLine, pLine;
    vector<Node> output;

//     if ( !currentFile.is_open() ){
//         cout << "El archivo que especifico no existe.";
//         exit(1);
//     }
//     else {

    while (getline (currentFile, rLine)){

	    if (rLine[0] != 'c'){

	        vector<string> sString;

	        if (rLine[0] == 'p'){

	            split(&rLine[7],' ', sString);

	            int proxyInt;
	            istringstream buffer(sString[0]);
	            buffer >> proxyInt;

	            sizeGraph = proxyInt;
	            for (int i = 0; i < proxyInt; i++){
		        output.push_back(Node());
	            }
	        }
	        else if (rLine[0] == 'e'){

	            split(&rLine[2],' ', sString);

	            int indexEdge1, indexEdge2;
	            istringstream buffer(sString[0]);
	            buffer >> indexEdge1;
	            indexEdge1--;
	            istringstream buffer2(sString[1]);
	            buffer2 >> indexEdge2;
	            indexEdge2--;

	            output[indexEdge1].edge.push_back(indexEdge2);
	            output[indexEdge2].edge.push_back(indexEdge1);
	        }

	        //Muestra lo que se lee
		// for (int i = 0; i < sString.size(); i++){
		//     cout << sString[i] << " " << i << "\n";
		// }

	    }

    }
    currentFile.close();

    return output;
}

//==============================================================================
/*
    Algoritmo de Brelaz Modificado
*/

// void label(int node, vector<Node>& graph){

// }

void brelaz (int n, // Numero de vertices.
//             int q, // Numero de colores de la heuristica.
//             int w,  // Dimension inicial del Clique.
	     answer dummy,
             vector<Node>& graph
             )
{

    bool back = false;
    for(int i=0;i<dummy.w;i++)
	graph[dummy.order[i].first].color = dummy.order[i].second;

    int k = dummy.w,
	uk = dummy.w,
	s = dummy.w;

    for(int i = 0; i<graph.size(); i++){
    	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    	cout<<"\t Sat: "<<graph[i].satDegree;
    	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    	for(int j=0;j<graph[i].edge.size();j++)
    	    cout<<graph[i].edge[j]<<" , ";
    	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    }

    cout << "welp" << endl;

    while (true){
    int lenodo;

        if (!back){
	    lenodo = dummy.order[k].first;
	    cout << k <<": " <<lenodo<< endl;

	    for(int i=1; i <= min(uk + 1, dummy.q); i++)
		    graph[lenodo].U.insert(i);

	    for(int i=0; i<graph[lenodo].edge.size();i++){
		Node node = graph[graph[lenodo].edge[i]];
		if(node.color!=0)
		    graph[lenodo].U.erase(node.color);
	    }
	    for(int i : graph[lenodo].U)
		cout << "\t" << i << endl;

	}
	else {
	    graph[dummy.order[k].first].U.erase(
	    	graph[dummy.order[k].first].color);
	    graph[dummy.order[k].first].label = false;
	}

	if(!graph[lenodo].U.empty()){
	    int minColor = dummy.q;
	    for(int i : graph[lenodo].U){
		minColor = i < minColor ? i : minColor;
	    }
	    graph[lenodo].color = minColor;
	    s = graph[lenodo].color > s ? s+1 : s;

	    k++;
	    cout<<"k: "<<k<<"> "<<n<<endl;
	    if(k>=n){
		dummy.q = s;
		if(dummy.q == dummy.w)
		    break;
		int k = 0;
		while(dummy.q != graph[dummy.order[k].first].color)
		    k++;

		// for(int i = 0; i<dummy.order.size();i++){
		//     if(dummy.q == dummy.order[dummy.order[i].first].color){
		// 	k = dummy.order[i].first;
		// 	break;
		//     }
		// }

		for(int i = k; i<dummy.order.size();i++)
		    graph[dummy.order[i].first].label = false;
		back = false;
	    }

	}else{
	    back = true;
	}

	if(back){

	    set<int> colores;
	    for(int i = 0; i < k; i++){
	    	for(int j=0;j<graph[dummy.order[k].first].edge.size();j++){
	    	    if(dummy.order[i].first==graph[dummy.order[k].first].edge[j])
	    	    {
	    		if(!colores.count(graph[dummy.order[i].first].color)){

	    		    graph[dummy.order[i].first].label = true;
	    		    colores.insert(graph[dummy.order[i].first].color);
			    //pinto
	    		}

	    		break;
	    	    }
	    	}
	    }

	    for(int i = dummy.order.size()-1;i>=0;i--){
		if(graph[dummy.order[i].first].label){
		    k = i;
		    break;
		}
	    }
	    cout<<"k: "<<dummy.order[k].first<<"\t Color: "<<graph[dummy.order[k].first].color;
	    cout<<"\tlabel: "<<graph[dummy.order[k].first].label;
	    cout<<"\t Sat: "<<graph[dummy.order[k].first].satDegree;
	    cout<<"\t Edges:"<<graph[dummy.order[k].first].edge.size()<<" {";
	    for(int j=0;j<graph[dummy.order[k].first].edge.size();j++)
		cout<<graph[dummy.order[k].first].edge[j]<<" , ";
	    cout<<"}"<<endl;

	    if(k<=dummy.w){
		cout <<"k: "<<k <<"<= " <<dummy.w<< endl;
		break;
	    }

	}

	// for(int i = 0; i<graph.size(); i++){
	//     cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
	//     cout<<"\t Sat: "<<graph[i].satDegree;
	//     cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
	//     for(int j=0;j<graph[i].edge.size();j++)
	// 	cout<<graph[i].edge[j]<<" , ";
	//     cout<<"}\t posColor:"<<graph[i].posColor<<endl;
	// }
    }

    for(int i = 0; i<graph.size(); i++){
	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
	cout<<"\tlabel: "<<graph[i].label;
	cout<<"\t Sat: "<<graph[i].satDegree;
	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
	for(int j=0;j<graph[i].edge.size();j++)
	    cout<<graph[i].edge[j]<<" , ";
	cout<<"}"<<endl;
    }

    cout << "s: " << s << endl;

    //     }
    //     if () {
    //         if (k > n) {
    //             // EXIT IF
    //             if (q == w){
    //                 break;
    //             }
    //         }
    //         else{
    //             back = false;
    //         }
    //     }
    //     else {
    //         back = true;
    //     }
    //     if (back) {

    //         // EXIT IF
    //         if (k<w+1){
    //             break;
    //         }
    //     }
    // }
    // // STOP ??

}

//==============================================================================
/*
    Main
*/

int main( int argc, char *argv[] ){

    char *fileName;
    int nodeNum = 0;
    vector<Node> graph;

    if (argc < 2) {
        cout << "Especifique el nombre del archivo con el grafo por favor:\n";
        cin >> fileName;
    }
    else {
        fileName = argv[1];
    }
    graph = readGraph(fileName, nodeNum);

    // for(int i = 0; i<graph.size(); i++){
    // 	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    // 	cout<<"\t Sat: "<<graph[i].satDegree;
    // 	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    // 	for(int j=0;j<graph[i].edge.size();j++)
    // 	    cout<<graph[i].edge[j]<<" , ";
    // 	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    // }

//    pair< pair <int,int>,vector< pair<int,int> > >
    answer
	ans = desatur(graph,graph.size());

    cout<<"w: "<<ans.w<<"\tq: "<<ans.q<<endl;

    for(int i =0; i<ans.order.size();i++)
    	cout<<ans.order[i].first<<" c: "<<ans.order[i].second<<endl;

    brelaz (graph.size(),ans,graph);

    // for(int i = 0; i<graph.size(); i++){
    // 	cout<<"i: "<<i<<"\t Color: "<<graph[i].color;
    // 	cout<<"\t Sat: "<<graph[i].satDegree;
    // 	cout<<"\t Edges:"<<graph[i].edge.size()<<" {";
    // 	for(int j=0;j<graph[i].edge.size();j++)
    // 	    cout<<graph[i].edge[j]<<" , ";
    // 	cout<<"}\t posColor:"<<graph[i].posColor<<endl;
    // }

    //=======

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: FilterConfigItem.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: sj $ $Date: 2001-03-05 20:35:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FILTER_CONFIG_ITEM_HXX_
#include "FilterConfigItem.hxx"
#endif
#include <tools/debug.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif

using namespace ::rtl;
using namespace ::utl                       ;   // getProcessServiceFactory
using namespace ::com::sun::star::lang      ;   // XMultiServiceFactory
using namespace ::com::sun::star::beans     ;   // PropertyValue
using namespace ::com::sun::star::uno       ;   // Reference
using namespace ::com::sun::star::util      ;   // XChangesBatch
using namespace ::com::sun::star::awt       ;   // Size

FilterConfigItem::FilterConfigItem( const OUString& rSubTree ) :
    bModified   ( sal_False )
{
    OUString sTree( ConfigManager::GetConfigBaseURL() );
    sTree += rSubTree;
    Reference< XMultiServiceFactory > xSMGR = getProcessServiceFactory();   // get global uno service manager

    Reference< XMultiServiceFactory > xCfgProv(
        xSMGR->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ) ) ),
            UNO_QUERY );

    if ( xCfgProv.is() )
    {
        Any aAny;
        // creation arguments: nodepath
        PropertyValue aPathArgument;
        aAny <<= sTree;
        aPathArgument.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" ) );
        aPathArgument.Value = aAny;

        // creation arguments: commit mode
        PropertyValue aModeArgument;
        sal_Bool bAsyncron = sal_True;
        aAny <<= bAsyncron;
        aModeArgument.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "lazywrite" ) );
        aModeArgument.Value = aAny;

        Sequence< Any > aArguments( 2 );
        aArguments[ 0 ] <<= aPathArgument;
        aArguments[ 1 ] <<= aModeArgument;

        try
        {
            xUpdatableView = xCfgProv->createInstanceWithArguments(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationUpdateAccess" ) ),
                    aArguments );
            if ( xUpdatableView.is() )
                xPropSet = Reference< XPropertySet >( xUpdatableView, UNO_QUERY );
        }
        catch ( ::com::sun::star::uno::Exception& )
        {
            DBG_ERROR( "FilterConfigItem::FilterConfigItem - Could not access configuration Key" );
        }
    }
};

FilterConfigItem::~FilterConfigItem()
{
    if ( xUpdatableView.is() )
    {
        if ( xPropSet.is() && bModified )
        {
            Reference< XChangesBatch > xUpdateControl( xUpdatableView, UNO_QUERY );
            if ( xUpdateControl.is() )
            {
                try
                {
                    xUpdateControl->commitChanges();
                }
                catch ( ::com::sun::star::uno::Exception& )
                {
                    DBG_ERROR( "FilterConfigItem::FilterConfigItem - Could not update configuration data" );
                }
            }
        }
    }
}

sal_Bool FilterConfigItem::ImplGetPropertyValue( Any& rAny, const Reference< XPropertySet >& rXPropSet, const OUString& rString, sal_Bool bTestPropertyAvailability )
{
    sal_Bool bRetValue = sal_True;

    if ( rXPropSet.is() )
    {
        if ( bTestPropertyAvailability )
        {
            bRetValue = sal_False;
            try
            {
                Reference< XPropertySetInfo >
                    aXPropSetInfo( rXPropSet->getPropertySetInfo() );
                if ( aXPropSetInfo.is() )
                    bRetValue = aXPropSetInfo->hasPropertyByName( rString );
            }
            catch( ::com::sun::star::uno::Exception& )
            {
                //
            }
        }
        if ( bRetValue )
        {
            try
            {
                rAny = rXPropSet->getPropertyValue( rString );
                if ( !rAny.hasValue() )
                    bRetValue = sal_False;
            }
            catch( ::com::sun::star::uno::Exception& )
            {
                bRetValue = sal_False;
            }
        }
    }
    else
        bRetValue = sal_False;
    return bRetValue;
}

sal_Bool FilterConfigItem::ReadBool( const OUString& rKey, sal_Bool bDefault )
{
    sal_Bool bRetValue = bDefault;
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        aAny >>= bRetValue;
    return bRetValue;
}

sal_Int32 FilterConfigItem::ReadInt32( const OUString& rKey, sal_Int32 nDefault )
{
    sal_Int32 nRetValue = nDefault;
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        aAny >>= nRetValue;
    return nRetValue;
}

Size FilterConfigItem::ReadSize( const OUString& rKey, const Size& rDefault )
{
    Size aRetValue( rDefault );
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
    {
        try
        {
            Reference< XPropertySet > aXPropSet;
            if ( aAny >>= aXPropSet )
            {
                if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), sal_True ) )
                    aAny >>= aRetValue.Width;
                if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), sal_True ) )
                    aAny >>= aRetValue.Height;
            }
        }
        catch ( ::com::sun::star::uno::Exception& )
        {
            DBG_ERROR( "FilterConfigItem::ReadSize - could not read PropertyValue" );
        }
    }
    return aRetValue;
}

void FilterConfigItem::WriteBool( const OUString& rKey, sal_Bool bNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            sal_Bool bOldValue;
            if ( aAny >>= bOldValue )
            {
                if ( bOldValue != bNewValue )
                {
                    aAny <<= bNewValue;
                    try
                    {
                        xPropSet->setPropertyValue( rKey, aAny );
                        bModified = sal_True;
                    }
                    catch ( ::com::sun::star::uno::Exception& )
                    {
                        DBG_ERROR( "FilterConfigItem::WriteBool - could not set PropertyValue" );
                    }
                }
            }
        }
    }
}

void FilterConfigItem::WriteInt32( const OUString& rKey, sal_Int32 nNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            sal_Int32 nOldValue;
            if ( aAny >>= nOldValue )
            {
                if ( nOldValue != nNewValue )
                {
                    aAny <<= nNewValue;
                    try
                    {
                        xPropSet->setPropertyValue( rKey, aAny );
                        bModified = sal_True;
                    }
                    catch ( ::com::sun::star::uno::Exception& )
                    {
                        DBG_ERROR( "FilterConfigItem::WriteInt32 - could not set PropertyValue" );
                    }
                }
            }
        }
    }
}

void FilterConfigItem::WriteSize( const OUString& rKey, const Size& rNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;
        sal_Int32 nOldWidth = rNewValue.Width;
        sal_Int32 nOldHeight = rNewValue.Height;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            try
            {
                Reference< XPropertySet > aXPropSet;
                if ( aAny >>= aXPropSet )
                {
                    if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), sal_True ) )
                        aAny >>= nOldWidth;
                    if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), sal_True ) )
                        aAny >>= nOldHeight;
                }
                if ( ( nOldWidth != rNewValue.Width ) || ( nOldHeight != rNewValue.Height ) )
                {
                    aAny <<= rNewValue.Width;
                    aXPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), aAny );
                    aAny <<= rNewValue.Height;
                    aXPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), aAny );
                    bModified = sal_True;
                }
            }
            catch ( ::com::sun::star::uno::Exception& )
            {
                DBG_ERROR( "FilterConfigItem::WriteSize - could not read PropertyValue" );
            }
        }
    }
}

// ------------------------------------------------------------------------
<commit_msg>now testing nodepath availability<commit_after>/*************************************************************************
 *
 *  $RCSfile: FilterConfigItem.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: sj $ $Date: 2001-03-08 13:46:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FILTER_CONFIG_ITEM_HXX_
#include "FilterConfigItem.hxx"
#endif
#include <tools/debug.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif

using namespace ::rtl;
using namespace ::utl                       ;   // getProcessServiceFactory
using namespace ::com::sun::star::lang      ;   // XMultiServiceFactory
using namespace ::com::sun::star::beans     ;   // PropertyValue
using namespace ::com::sun::star::uno       ;   // Reference
using namespace ::com::sun::star::util      ;   // XChangesBatch
using namespace ::com::sun::star::awt       ;   // Size
using namespace ::com::sun::star::container ;   //

static sal_Bool ImpIsTreeAvailable( Reference< XMultiServiceFactory >& rXCfgProv, const String& rTree )
{
    sal_Bool    bAvailable = rTree.Len() != 0;
    if ( bAvailable )
    {
        xub_StrLen  nTokenCount = rTree.GetTokenCount( (sal_Unicode)'/' );
        xub_StrLen  i = 0;

        if ( rTree.GetChar( 0 ) == (sal_Unicode)'/' )
            i++;

        Any aAny;
        aAny <<= (OUString)rTree.GetToken( i++, (sal_Unicode)'/' );

        // creation arguments: nodepath
        PropertyValue aPathArgument;
        aPathArgument.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" ) );
        aPathArgument.Value = aAny;

        Sequence< Any > aArguments( 1 );
        aArguments[ 0 ] <<= aPathArgument;

        Reference< XInterface > xReadAccess;
        try
        {
            xReadAccess = rXCfgProv->createInstanceWithArguments(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess" ) ),
                    aArguments );
        }
        catch ( ::com::sun::star::uno::Exception& )
        {
            bAvailable = sal_False;
        }
        if ( xReadAccess.is() )
        {
            for ( ; bAvailable && ( i < nTokenCount ); i++ )
            {
                Reference< XHierarchicalNameAccess > xHierarchicalNameAccess
                    ( xReadAccess, UNO_QUERY );

                if ( !xHierarchicalNameAccess.is() )
                    bAvailable = sal_False;
                else
                {
                    String aNode( rTree.GetToken( i, (sal_Unicode)'/' ) );
                    if ( !xHierarchicalNameAccess->hasByHierarchicalName( aNode ) )
                        bAvailable = sal_False;
                    else
                    {
                        Any aAny( xHierarchicalNameAccess->getByHierarchicalName( aNode ) );
                        try
                        {
                            aAny >>= xReadAccess;
                        }
                        catch ( ::com::sun::star::uno::Exception& )
                        {
                            bAvailable = sal_False;
                        }
                    }
                }
            }
        }
    }
    return bAvailable;
}

FilterConfigItem::FilterConfigItem( const OUString& rSubTree ) :
    bModified   ( sal_False )
{
    OUString sTree( ConfigManager::GetConfigBaseURL() );
    sTree += rSubTree;
    Reference< XMultiServiceFactory > xSMGR = getProcessServiceFactory();   // get global uno service manager

    Reference< XMultiServiceFactory > xCfgProv(
        xSMGR->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ) ) ),
            UNO_QUERY );

    if ( xCfgProv.is() )
    {
        if ( ImpIsTreeAvailable( xCfgProv, String( sTree ) ) )
        {
            Any aAny;
            // creation arguments: nodepath
            PropertyValue aPathArgument;
            aAny <<= sTree;
            aPathArgument.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" ) );
            aPathArgument.Value = aAny;

            // creation arguments: commit mode
            PropertyValue aModeArgument;
            sal_Bool bAsyncron = sal_True;
            aAny <<= bAsyncron;
            aModeArgument.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "lazywrite" ) );
            aModeArgument.Value = aAny;

            Sequence< Any > aArguments( 2 );
            aArguments[ 0 ] <<= aPathArgument;
            aArguments[ 1 ] <<= aModeArgument;

            try
            {
                xUpdatableView = xCfgProv->createInstanceWithArguments(
                    OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationUpdateAccess" ) ),
                        aArguments );
                if ( xUpdatableView.is() )
                    xPropSet = Reference< XPropertySet >( xUpdatableView, UNO_QUERY );
            }
            catch ( ::com::sun::star::uno::Exception& )
            {
                DBG_ERROR( "FilterConfigItem::FilterConfigItem - Could not access configuration Key" );
            }
        }
    }
};

FilterConfigItem::~FilterConfigItem()
{
    if ( xUpdatableView.is() )
    {
        if ( xPropSet.is() && bModified )
        {
            Reference< XChangesBatch > xUpdateControl( xUpdatableView, UNO_QUERY );
            if ( xUpdateControl.is() )
            {
                try
                {
                    xUpdateControl->commitChanges();
                }
                catch ( ::com::sun::star::uno::Exception& )
                {
                    DBG_ERROR( "FilterConfigItem::FilterConfigItem - Could not update configuration data" );
                }
            }
        }
    }
}

sal_Bool FilterConfigItem::ImplGetPropertyValue( Any& rAny, const Reference< XPropertySet >& rXPropSet, const OUString& rString, sal_Bool bTestPropertyAvailability )
{
    sal_Bool bRetValue = sal_True;

    if ( rXPropSet.is() )
    {
        if ( bTestPropertyAvailability )
        {
            bRetValue = sal_False;
            try
            {
                Reference< XPropertySetInfo >
                    aXPropSetInfo( rXPropSet->getPropertySetInfo() );
                if ( aXPropSetInfo.is() )
                    bRetValue = aXPropSetInfo->hasPropertyByName( rString );
            }
            catch( ::com::sun::star::uno::Exception& )
            {
                //
            }
        }
        if ( bRetValue )
        {
            try
            {
                rAny = rXPropSet->getPropertyValue( rString );
                if ( !rAny.hasValue() )
                    bRetValue = sal_False;
            }
            catch( ::com::sun::star::uno::Exception& )
            {
                bRetValue = sal_False;
            }
        }
    }
    else
        bRetValue = sal_False;
    return bRetValue;
}

sal_Bool FilterConfigItem::ReadBool( const OUString& rKey, sal_Bool bDefault )
{
    sal_Bool bRetValue = bDefault;
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        aAny >>= bRetValue;
    return bRetValue;
}

sal_Int32 FilterConfigItem::ReadInt32( const OUString& rKey, sal_Int32 nDefault )
{
    sal_Int32 nRetValue = nDefault;
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        aAny >>= nRetValue;
    return nRetValue;
}

Size FilterConfigItem::ReadSize( const OUString& rKey, const Size& rDefault )
{
    Size aRetValue( rDefault );
    Any aAny;

    if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
    {
        try
        {
            Reference< XPropertySet > aXPropSet;
            if ( aAny >>= aXPropSet )
            {
                if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), sal_True ) )
                    aAny >>= aRetValue.Width;
                if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), sal_True ) )
                    aAny >>= aRetValue.Height;
            }
        }
        catch ( ::com::sun::star::uno::Exception& )
        {
            DBG_ERROR( "FilterConfigItem::ReadSize - could not read PropertyValue" );
        }
    }
    return aRetValue;
}

void FilterConfigItem::WriteBool( const OUString& rKey, sal_Bool bNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            sal_Bool bOldValue;
            if ( aAny >>= bOldValue )
            {
                if ( bOldValue != bNewValue )
                {
                    aAny <<= bNewValue;
                    try
                    {
                        xPropSet->setPropertyValue( rKey, aAny );
                        bModified = sal_True;
                    }
                    catch ( ::com::sun::star::uno::Exception& )
                    {
                        DBG_ERROR( "FilterConfigItem::WriteBool - could not set PropertyValue" );
                    }
                }
            }
        }
    }
}

void FilterConfigItem::WriteInt32( const OUString& rKey, sal_Int32 nNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            sal_Int32 nOldValue;
            if ( aAny >>= nOldValue )
            {
                if ( nOldValue != nNewValue )
                {
                    aAny <<= nNewValue;
                    try
                    {
                        xPropSet->setPropertyValue( rKey, aAny );
                        bModified = sal_True;
                    }
                    catch ( ::com::sun::star::uno::Exception& )
                    {
                        DBG_ERROR( "FilterConfigItem::WriteInt32 - could not set PropertyValue" );
                    }
                }
            }
        }
    }
}

void FilterConfigItem::WriteSize( const OUString& rKey, const Size& rNewValue )
{
    if ( xPropSet.is() )
    {
        Any aAny;
        sal_Int32 nOldWidth = rNewValue.Width;
        sal_Int32 nOldHeight = rNewValue.Height;

        if ( ImplGetPropertyValue( aAny, xPropSet, rKey, sal_True ) )
        {
            try
            {
                Reference< XPropertySet > aXPropSet;
                if ( aAny >>= aXPropSet )
                {
                    if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), sal_True ) )
                        aAny >>= nOldWidth;
                    if ( ImplGetPropertyValue( aAny, aXPropSet, OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), sal_True ) )
                        aAny >>= nOldHeight;
                }
                if ( ( nOldWidth != rNewValue.Width ) || ( nOldHeight != rNewValue.Height ) )
                {
                    aAny <<= rNewValue.Width;
                    aXPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ), aAny );
                    aAny <<= rNewValue.Height;
                    aXPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ), aAny );
                    bModified = sal_True;
                }
            }
            catch ( ::com::sun::star::uno::Exception& )
            {
                DBG_ERROR( "FilterConfigItem::WriteSize - could not read PropertyValue" );
            }
        }
    }
}

// ------------------------------------------------------------------------
<|endoftext|>