Tuesday, May 20, 2008

Automatic array data conversion

You can convert array type like this.
(a and b can be any of MVectorArray, MFloatVectorArray, MPointArray, MFloatPointArray)

MFloatVectorArray a;
//Fill a with values here.
MPointArray b = DataTypeConverter::GenericVectorArray(a);

with this.
#ifndef DataTypeConverter_H
#define DataTypeConverter_H

#include <maya/MVector.h>
#include <maya/MFloatVector.h>
#include <maya/MPoint.h>
#include <maya/MFloatPoint.h>
#include <maya/MVectorArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MPointArray.h>
#include <maya/MFloatPointArray.h>
#include <vector>

namespace DataTypeConverter
{

class GenericValue
{
protected:
 double x_;
 double y_;
 double z_;
 double w_;

public:
 GenericValue(const MPoint& source)       : x_(source.x), y_(source.y), z_(source.z), w_(source.w){}
 GenericValue(const MFloatPoint& source)  : x_(source.x), y_(source.y), z_(source.z), w_(source.w){}
 GenericValue(const MVector& source)      : x_(source.x), y_(source.y), z_(source.z), w_(1){}
 GenericValue(const MFloatVector& source) : x_(source.x), y_(source.y), z_(source.z), w_(1){}
 GenericValue(const float source) : x_(source), y_(0), z_(0), w_(0){}
 GenericValue(const double source) : x_(source), y_(0), z_(0), w_(0){}

 operator MPoint(){return MPoint(x_, y_, z_, w_);}
 operator MFloatPoint(){return MFloatPoint((float)x_, (float)y_, (float)z_, (float)w_);}
 operator MVector(){return MVector(x_, y_, z_);}
 operator MFloatVector(){return MFloatVector((float)x_, (float)y_, (float)z_);}
 operator float(){return (float)x_;}
 operator double(){return x_;}
};


class GenericValueArray
{
protected:
 std::vector < GenericValue > garray_;

public:
 template < typename arrayT >
 GenericValueArray(arrayT& sourcearray);

 template < typename arrayT >
 operator arrayT();
};


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template < typename arrayT >
GenericValueArray::GenericValueArray(arrayT& sourcearray)
{
 unsigned length = sourcearray.length();
 for (unsigned i = 0; i < length; ++i)
 {
  garray_.push_back(sourcearray[i]);
 }
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template < typename arrayT >
GenericValueArray::operator arrayT()
{
 arrayT destarray;
 unsigned length = garray_.size();
 destarray.setLength(length);
 for (unsigned i = 0; i < length; ++i)
 {
  destarray[i] = garray_[i];
 }
 return destarray;
}

};
#endif

No comments: