code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#pragma once #include <zGraphicsConfig.hpp> #include <Math/Vector3.hpp> namespace zzz{ ZGRAPHICS_FUNC float Ft_in(float costheta1,float eta); ZGRAPHICS_FUNC float Ft_out(float costheta2,float eta); ZGRAPHICS_FUNC float Ft_out2(float costheta1,float eta); ZGRAPHICS_FUNC bool RefractTo(Vector3f inray,Vector3f &outray,float eta,const Vector3f &normal=Vector3f(0,0,1)); ZGRAPHICS_FUNC bool RefractFrom(Vector3f outray,Vector3f &inray,float eta,const Vector3f &normal=Vector3f(0,0,1)); }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/RayTransform.hpp
C++
gpl3
496
#pragma once #include <common.hpp> #include <Math/Vector.hpp> namespace zzz{ template <unsigned int N, typename T > class AABB { public: #undef max #undef min AABB():min_(numeric_limits<T>::max()),max_(-numeric_limits<T>::max()){} AABB(const Vector<N,T> &min,const Vector<N,T> &max):min_(min),max_(max){} AABB(const Vector<N,T> &p):min_(p),max_(p){} AABB(const vector<Vector<N,T> > &data):min_(numeric_limits<T>::max()),max_(-numeric_limits<T>::max()){ *this += data; } // create from list of vertex void Reset() { min_=Vector<N,T>(numeric_limits<T>::max()); max_=Vector<N,T>(-numeric_limits<T>::max()); } // min and max Vector<N,T> &Min(){return min_;} const Vector<N,T> &Min() const{return min_;} T Min(zuint i) const {return min_[i];} Vector<N,T> &Max(){return max_;} const Vector<N,T> &Max() const{return max_;} T Max(zuint i) const {return max_[i];} // range Vector<2,T> Range(zuint i) const {return Vector<2,T>(Min(i), Max(i));} Vector<2,Vector<N,T> > Range() const {return Vector<2,Vector<N,T> >(Min(), Max());} // Offset void SetOffset(const Vector<N,T> &offset) { min_+=offset; max_+=offset; } // Box center Vector<N,T> Center() const{return (min_+max_)*0.5;} T Center(zuint i) const{return (min_[i]+max_[i])*0.5;} /// Box diffrence (width/height/depth) Vector<N,T> Diff() const{return max_-min_;} T Diff(zuint i) const{return max_[i]-min_[i];} bool IsLegal() const { bool good=true; for (zuint i=0; i<N; i++) if (min_[i]>max_[i]) { good=false; break; } return good; } bool IsEmpty() const { return min_==max_; } void AddData(const Vector<N,T> &p) { for (zuint i=0; i<N; i++) { if (min_[i]>p[i]) min_[i]=p[i]; if (max_[i]<p[i]) max_[i]=p[i]; } } template<typename T1> void AddData(const T1 &_begin, const T1 &_end) { for (T1 x=_begin; x!=_end; x++) AddData(*x); } /// Boolean union void operator+=(const Vector<N,T> &p) { AddData(p); } /// Boolean union void operator+=(const std::vector<Vector<N,T> > &p) { AddData(p.begin(), p.end()); } /// Boolean union void operator+=(const AABB<N,T> &box) { *this+=box.min_; *this+=box.max_; } const AABB<N,T>& operator+(const AABB<N,T> &box) const { AABB<N,T> ret(*this); ret+=box; return ret; } /// Boolean intersection void operator*=(const AABB<N,T> &box) { for (zuint i=i; i<N; i++) { if (min_[i]<box.min_[i]) min_[i]=box.min_[i]; if (max_[i]>box.max_[i]) max_[i]=box.max_[i]; } } const AABB<N,T>& operator*(const AABB<N,T> &box) const { AABB<N,T> ret(*this); ret*=box; return ret; } /// Box equality operator bool operator==(const AABB<N,T> &box) const { return min_==box.min_ && max_==box.max_; } /// Volumetric classification bool IsInside(const Vector<N,T> &pos) const { for (zuint i=0; i<N; i++) if (!Within<T>(min_[i],pos[i],max_[i])) return false; return true; } /// Intersection between boxes bool IsIntersect(const AABB<N,T> &box) const { for (zuint i=0; i<N; i++) { if (min_[i] > box.max_[i]) return false; if (max_[i] < box.min_[i]) return false; } return true; } /// Whether it intersect a sphere bool AABB::sphereIntersect(const Vector<N,T>& center, T r) const { Vector<N,T> minpos(center-r); Vector<N,T> maxpos(center+r); //the sphere's AABB do not intersect with it, it absolutly is not if(!IsIntersect(AABB<N,T>(minpos, maxpos))) return false; //TODO: more accurate testing return true; } static AABB<N,T> ZERO() { return AABB(Vector<N,T>(T(0)), Vector<N,T>(T(0))); } static AABB<N,T> INFINITY() { return AABB(Vector<N,T>(-numeric_limits<T>::max()), Vector<N,T>(numeric_limits<T>::max())); } protected: Vector<N,T> min_, max_; }; typedef AABB<2,zint32> AABB2i32; typedef AABB<2,zfloat32> AABB2f32; typedef AABB<2,zfloat64> AABB2f64; typedef AABB<3,zfloat32> AABB3f32; typedef AABB<3,zfloat64> AABB3f64; typedef AABB<4,zfloat32> AABB4f32; typedef AABB<4,zfloat64> AABB4f64; typedef AABB<2,int> AABB2i; typedef AABB<2,float> AABB2f; typedef AABB<2,double> AABB2d; typedef AABB<3,float> AABB3f; typedef AABB<3,double> AABB3d; typedef AABB<4,float> AABB4f; typedef AABB<4,double> AABB4d; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/AABB.hpp
C++
gpl3
4,568
#pragma once #include <zGraphicsConfig.hpp> #include "Graphics.hpp" #include "Quaternion.hpp" #include "Rotation.hpp" #include "Transformation.hpp" #include "Translation.hpp" #include "Coordinate.hpp" #include <Utility/Uncopyable.hpp> //stupid MFC define... #undef near #undef far namespace zzz { class ZGRAPHICS_CLASS Camera { public: Vector3d Position_; void SetPerspective(const int cw, const int ch, const double near=-1, const double far=-1, const double angle=-1); void SetOrthoMode(bool mode); void SetPosition(const Vector<3,double> &pos); void SetPosition(const double &x, const double &y, const double &z); void OffsetPosition(const Vector<3,double> &offset); void OffsetPosition(const double &x, const double &y, const double &z); void MoveForwards(double dist); void MoveLeftwards(double dist); void MoveUpwards(double dist); void ChangeYaw(double degrees); void ChangePitch(double degrees); void LookAt(const Vector3d &from, const Vector3d &to, const Vector3d &up); void ApplyGL(void) const; GLTransformationd GetGLTransformation(); void Reset(); Camera(); //private: void Update(); double fovy_; double aspect_; double zNear_; double zFar_; double MaxPitchRate_; double MaxYawRate_; double YawDegrees_; double PitchDegrees_; Quaterniond qHeading_; Quaterniond qPitch_; GLTransformationd Transform_; CartesianDirCoord<double> DirectionVector_; bool orthoMode_; double orthoScale_; int width_, height_; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/Camera.hpp
C++
gpl3
1,557
#pragma once #include <zGraphicsConfig.hpp> namespace zzz{ #define MAP_SIZE 128 class ZGRAPHICS_CLASS HeightMap { public: int ToIndex(int x, int y) const; void Generate(); void GetVertexColor(int x, int y, float *col); bool SetVertexColor(int x, int y); float GetHeight(int x, int y); void SetHeight(int x, int y, float h); void DrawHeightMap(float drawsize); HeightMap(); virtual ~HeightMap(); float ScaleValue_; private: float HeightMap_[(MAP_SIZE+1)*(MAP_SIZE+1)]; float Left_, Right_, Front_, Back_; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/HeightMap.hpp
C++
gpl3
558
#pragma once #include <Math/Vector3.hpp> #include <Math/Matrix4x4.hpp> #include <Math/Matrix3x3.hpp> #include <Graphics/Translation.hpp> #include <Graphics/Rotation.hpp> namespace zzz{ template <typename T> class Transformation : public Matrix<4,4,T> { public: Transformation(){Matrix<4,4,T>::Identical();} Transformation(const Transformation<T> &other):Matrix<4,4,T>(other){} explicit Transformation(const MatrixBase<4,4,T> &other):Matrix<4,4,T>(other){} explicit Transformation(const Translation<T> &t) { Matrix<4,4,T>::Identical(); T* v=Data(); v[3]=t[0]; v[7]=t[1]; v[11]=t[2]; } explicit Transformation(const Rotation<T> &r) { Matrix<4,4,T>::Identical(); T* v=Data(); v[0]=r[0]; v[1]=r[1]; v[2]=r[2]; v[4]=r[3]; v[5]=r[4]; v[6]=r[5]; v[8]=r[6]; v[9]=r[7]; v[10]=r[8]; } Transformation(const MatrixBase<3,3,T> &r, const VectorBase<3,T> &t) { Matrix<4,4,T>::Identical(); Set(r,t); } using Matrix<4,4,T>::operator =; using Matrix<4,4,T>::operator *; using Matrix<4,4,T>::Data; void Set(const MatrixBase<3,3,T> &r, const VectorBase<3,T> &t) { T* v=Data(); v[0]=r[0]; v[1]=r[1]; v[2]=r[2]; v[3]=t[0]; v[4]=r[3]; v[5]=r[4]; v[6]=r[5]; v[7]=t[1]; v[8]=r[6]; v[9]=r[7]; v[10]=r[8]; v[11]=t[2]; v[12]=0; v[13]=0; v[14]=0; v[15]=1; } VectorBase<3,T> Apply(const VectorBase<3,T> &other) const { VectorBase<4,T> v(other,(T)1); VectorBase<4,T> res=(*this)*v; res/=res[3]; return VectorBase<3,T>(res); } Transformation<T> RelativeTo(const Transformation<T> &other) { return (*this)*other.Inverted(); } //Fast inverse of a rigid transform matrix //M=[r t] // [0 1] //inv(M)=[r' -r'*t] // [0 1] void Invert() { *this=Inverted(); } Transformation<T> Inverted() const { const T* v=Data(); Matrix<3,3,T> r(v[0],v[4],v[8],v[1],v[5],v[9],v[2],v[6],v[10]); Vector<3,T> t(-v[3],-v[7],-v[11]); return Transformation<T>(Rotation<T>(r),Translation<T>(r*t)); } inline void ApplyGL() const; }; template <typename T> class GLTransformation : public Matrix<4,4,T> { public: GLTransformation(){Matrix<4,4,T>::Identical();} GLTransformation(const GLTransformation<T> &other):Matrix<4,4,T>(other){} explicit GLTransformation(const MatrixBase<4,4,T> &other):Matrix<4,4,T>(other){} explicit GLTransformation(const Transformation<T> &other):Matrix<4,4,T>(other.Transposed()){} explicit GLTransformation(const Translation<T> &t) { Matrix<4,4,T>::Identical(); T* v=Data(); v[12]=t[0]; v[13]=t[1]; v[14]=t[2]; } explicit GLTransformation(const Rotation<T> &r) { Matrix<4,4,T>::Identical(); T* v=Data(); v[0]=r[0]; v[4]=r[1]; v[8]=r[2]; v[1]=r[3]; v[5]=r[4]; v[9]=r[5]; v[2]=r[6]; v[6]=r[7]; v[10]=r[8]; } explicit GLTransformation(const Rotation<T> &r, const Translation<T> &t){Set(r,t);} using Matrix<4,4,T>::operator=; using Matrix<4,4,T>::Data; void operator=(const Transformation<T> &other) { *this=other.Transposed(); } void Set(const Rotation<T> &r, const Translation<T> &t) { Matrix<4,4,T>::Identical(); T* v=Data(); v[0]=r[0]; v[4]=r[1]; v[8]=r[2]; v[12]=t[0]; v[1]=r[3]; v[5]=r[4]; v[9]=r[5]; v[13]=t[1]; v[2]=r[6]; v[6]=r[7]; v[10]=r[8]; v[14]=t[2]; v[3]=0; v[7]=0; v[11]=0; v[15]=1; } T& operator()(const zuint x, const zuint y) { return Matrix<4,4,T>::operator()(y,x); } const T& operator()(const zuint x, const zuint y) const { return Matrix<4,4,T>::operator()(y,x); } inline void ApplyGL() const; using Matrix<4,4,T>::operator *; }; template<> void Transformation<float>::ApplyGL() const { glMultMatrixf(Transposed().Data()); } template<> void Transformation<double>::ApplyGL() const { glMultMatrixd(Transposed().Data()); } template<> void GLTransformation<float>::ApplyGL() const { glMultMatrixf(Data()); } template<> void GLTransformation<double>::ApplyGL() const { glMultMatrixd(Data()); } typedef Transformation<zfloat32> Transformationf32; typedef Transformation<zfloat64> Transformationf64; typedef GLTransformation<zfloat32> GLTransformationf32; typedef GLTransformation<zfloat64> GLTransformationf64; typedef Transformation<float> Transformationf; typedef Transformation<double> Transformationd; typedef GLTransformation<float> GLTransformationf; typedef GLTransformation<double> GLTransformationd; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/Transformation.hpp
C++
gpl3
4,644
#include <Math/Vector2.hpp> #include <Math/Vector3.hpp> #include <Math/Vector4.hpp> #include <Graphics/aabb.hpp> namespace zzz { template<typename T> class BoundingBox3 { public: BoundingBox3() : ori_boundary_good_(false) { rot_.Identical(); rot_back_.Identical(); } BoundingBox3(const Matrix<3, 3, T> &rot) : rot_(rot), ori_boundary_good_(false) { rot_back_ = rot_.Inverted(); } void SetRot(const Matrix<3, 3, T> &rot) { rot_ = rot; rot_back_ = rot_.Inverted(); ori_boundary_good_ = false; } void Reset() { aabb_.Reset(); ori_boundary_good_ = false; } void AddData(const Vector<3,T> &p) { aabb_.AddData(rot_ * p); ori_boundary_good_ = false; } template<typename T1> void AddData(const T1 &_begin, const T1 &_end) { for (T1 x=_begin; x!=_end; x++) AddData(*x); } void operator+=(const Vector<3,T> &p) { AddData(p); } void operator+=(const std::vector<Vector<3,T> > &p) { AddData(p.begin(), p.end()); } bool operator==(const BoundingBox3<T> &box) const { return rot_==box.rot_ && aabb_==box.aabb_; } bool IsInside(const Vector<3,T> &pos) const { return aabb_.IsInside(rot_ * pos); } Vector<3, T> Center() { return rot_back_ * aabb_.Center(); } static const int L = 0; static const int M = 1; static const int R = 2; Vector3i RelativePos(const Vector<3, T>& p) const { Vector<3, T> relp = Rotate(p); Vector3i pos; for (zuint i = 0; i < 3; ++i) { if (relp[i] < aabb_.Min(i)) pos[i] = L; else if (relp[i] > aabb_.Max(i)) pos[i] = R; else pos[i] = M; } return pos; } static int ToIndex(const Vector3i& pos) { return FastDot(pos, Vector3i(1, 3, 9)); } static bool IsSpace(const Vector3i& pos) { if (ToIndex(pos) == ToIndex(Vector3i(M, M, M))) return true; return false; } static bool IsPoint(const Vector3i& pos) { int n = ToIndex(pos); if (n == ToIndex(Vector3i(L, L, L)) || n == ToIndex(Vector3i(R, L, L)) || n == ToIndex(Vector3i(L, R, L)) || n == ToIndex(Vector3i(R, R, L)) || n == ToIndex(Vector3i(L, L, R)) || n == ToIndex(Vector3i(R, L, R)) || n == ToIndex(Vector3i(L, R, R)) || n == ToIndex(Vector3i(R, R, R))) return true; return false; } Vector<3, T> GetBoundaryPoint(const Vector3i& pos) const { if (!ori_boundary_good_) CalculateOriBoundary(); int n = ToIndex(pos); if (n == ToIndex(Vector3i(L, L, L))) return ori_boundary_[0][0][0]; if (n == ToIndex(Vector3i(R, L, L))) return ori_boundary_[1][0][0]; if (n == ToIndex(Vector3i(L, R, L))) return ori_boundary_[0][1][0]; if (n == ToIndex(Vector3i(R, R, L))) return ori_boundary_[1][1][0]; if (n == ToIndex(Vector3i(L, L, R))) return ori_boundary_[0][0][1]; if (n == ToIndex(Vector3i(R, L, R))) return ori_boundary_[1][0][1]; if (n == ToIndex(Vector3i(L, R, R))) return ori_boundary_[0][1][1]; if (n == ToIndex(Vector3i(R, R, R))) return ori_boundary_[1][1][1]; ZLOGF << "This coordinate is not a point" << ZVAR(pos); return Vector<3, T>(); } static bool IsLine(const Vector3i& pos) { int n = ToIndex(pos); if (n == ToIndex(Vector3i(M, L, L)) || n == ToIndex(Vector3i(M, L, R)) || n == ToIndex(Vector3i(M, R, R)) || n == ToIndex(Vector3i(M, R, L)) || n == ToIndex(Vector3i(L, M, L)) || n == ToIndex(Vector3i(R, M, R)) || n == ToIndex(Vector3i(R, M, L)) || n == ToIndex(Vector3i(L, M, R)) || n == ToIndex(Vector3i(L, L, M)) || n == ToIndex(Vector3i(R, L, M)) || n == ToIndex(Vector3i(R, R, M)) || n == ToIndex(Vector3i(L, R, M))) return true; return false; } Vector<2, Vector<3, T> > GetBoundaryLine(const Vector3i& pos) const { if (!ori_boundary_good_) CalculateOriBoundary(); int n = ToIndex(pos); if (n == ToIndex(Vector3i(M, L, L))) return Vector<2, Vector<3, T> >(ori_boundary_[0][0][0], ori_boundary_[1][0][0]); if (n == ToIndex(Vector3i(M, L, R))) return Vector<2, Vector<3, T> >(ori_boundary_[0][0][1], ori_boundary_[1][0][1]); if (n == ToIndex(Vector3i(M, R, R))) return Vector<2, Vector<3, T> >(ori_boundary_[0][1][1], ori_boundary_[1][1][1]); if (n == ToIndex(Vector3i(M, R, L))) return Vector<2, Vector<3, T> >(ori_boundary_[0][1][0], ori_boundary_[1][1][0]); if (n == ToIndex(Vector3i(L, M, L))) return Vector<2, Vector<3, T> >(ori_boundary_[0][0][0], ori_boundary_[0][1][0]); if (n == ToIndex(Vector3i(R, M, L))) return Vector<2, Vector<3, T> >(ori_boundary_[1][0][0], ori_boundary_[1][1][0]); if (n == ToIndex(Vector3i(R, M, R))) return Vector<2, Vector<3, T> >(ori_boundary_[1][0][1], ori_boundary_[1][1][1]); if (n == ToIndex(Vector3i(L, M, R))) return Vector<2, Vector<3, T> >(ori_boundary_[0][0][1], ori_boundary_[0][1][1]); if (n == ToIndex(Vector3i(L, L, M))) return Vector<2, Vector<3, T> >(ori_boundary_[0][0][0], ori_boundary_[0][0][1]); if (n == ToIndex(Vector3i(R, L, M))) return Vector<2, Vector<3, T> >(ori_boundary_[1][0][0], ori_boundary_[1][0][1]); if (n == ToIndex(Vector3i(R, R, M))) return Vector<2, Vector<3, T> >(ori_boundary_[1][1][0], ori_boundary_[1][1][1]); if (n == ToIndex(Vector3i(L, R, M))) return Vector<2, Vector<3, T> >(ori_boundary_[0][1][0], ori_boundary_[0][1][1]); ZLOGF << "This coordinate is not a line" << ZVAR(pos); return Vector<2, Vector<3, T> >(); } static bool IsPlane(const Vector3i &pos) { int n = ToIndex(pos); if (n == ToIndex(Vector3i(R, M, M)) || n == ToIndex(Vector3i(L, M, M)) || n == ToIndex(Vector3i(M, R, M)) || n == ToIndex(Vector3i(M, L, M)) || n == ToIndex(Vector3i(M, M, R)) || n == ToIndex(Vector3i(M, M, L))) return true; return false; } Vector<4, Vector<3, T> > GetBoundaryPlane(const Vector3i& pos) const { if (!ori_boundary_good_) CalculateOriBoundary(); int n = ToIndex(pos); if (n == ToIndex(Vector3i(R, M, M))) return Vector<4, Vector<3, T> >( ori_boundary_[1][0][1], ori_boundary_[1][0][0], ori_boundary_[1][1][0], ori_boundary_[1][1][1]); if (n == ToIndex(Vector3i(L, M, M))) return Vector<4, Vector<3, T> >( ori_boundary_[0][0][1], ori_boundary_[0][0][0], ori_boundary_[0][1][0], ori_boundary_[0][1][1]); if (n == ToIndex(Vector3i(M, R, M))) return Vector<4, Vector<3, T> >( ori_boundary_[0][1][0], ori_boundary_[1][1][0], ori_boundary_[1][1][1], ori_boundary_[0][1][1]); if (n == ToIndex(Vector3i(M, L, M))) return Vector<4, Vector<3, T> >( ori_boundary_[0][0][0], ori_boundary_[1][0][0], ori_boundary_[1][0][1], ori_boundary_[0][0][1]); if (n == ToIndex(Vector3i(M, M, R))) return Vector<4, Vector<3, T> >( ori_boundary_[0][0][1], ori_boundary_[1][0][1], ori_boundary_[1][1][1], ori_boundary_[0][1][1]); if (n == ToIndex(Vector3i(M, M, L))) return Vector<4, Vector<3, T> >( ori_boundary_[1][0][0], ori_boundary_[0][0][0], ori_boundary_[0][0][1], ori_boundary_[1][0][1]); ZLOGF << "This coordinate is not a plane" << ZVAR(pos); return Vector<4, Vector<3, T> >(); } const Matrix<3, 3, T>& GetRot() const {return rot_;} const Matrix<3, 3, T>& GetRotBack() const {return rot_back_;} const AABB<3, T>& GetAABB() const {return aabb_;} Vector<3, T> Rotate(const Vector<3, T>& x) const {return rot_ * x;} Vector<3, T> RotateBack(const Vector<3, T>& x) const {return rot_back_ * x;} private: AABB<3, T> aabb_; Matrix<3, 3, T> rot_; Matrix<3, 3, T> rot_back_; mutable Vector<3, T> ori_boundary_[2][2][2]; mutable bool ori_boundary_good_; void CalculateOriBoundary() const { const Vector<3, T> &a = aabb_.Min(); const Vector<3, T> &b = aabb_.Max(); ori_boundary_[0][0][0] = rot_back_ * Vector<3, T>(a[0], a[1], a[2]); ori_boundary_[1][0][0] = rot_back_ * Vector<3, T>(b[0], a[1], a[2]); ori_boundary_[0][1][0] = rot_back_ * Vector<3, T>(a[0], b[1], a[2]); ori_boundary_[1][1][0] = rot_back_ * Vector<3, T>(b[0], b[1], a[2]); ori_boundary_[0][0][1] = rot_back_ * Vector<3, T>(a[0], a[1], b[2]); ori_boundary_[1][0][1] = rot_back_ * Vector<3, T>(b[0], a[1], b[2]); ori_boundary_[0][1][1] = rot_back_ * Vector<3, T>(a[0], b[1], b[2]); ori_boundary_[1][1][1] = rot_back_ * Vector<3, T>(b[0], b[1], b[2]); ori_boundary_good_ = true; } }; typedef BoundingBox3<zfloat32> BoundingBox3f32; typedef BoundingBox3<zfloat64> BoundingBox3f64; SIMPLE_IOOBJECT(BoundingBox3f32); SIMPLE_IOOBJECT(BoundingBox3f64); } // namespace zzz
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/BoundingBox3.hpp
C++
gpl3
9,053
#pragma once #include <zGraphicsConfig.hpp> #include <Utility/Singleton.hpp> #include <Math/Vector2.hpp> namespace zzz { class ZGRAPHICS_CLASS BMPFont : public Singleton<BMPFont> { public: BMPFont(); Vector2i Size(const string &msg); void Draw(const string &msg); void DrawFont(); zuint FontHeight() const; zuint FontWidth() const; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/BMPFont.hpp
C++
gpl3
364
#include "Coordinate.hpp" namespace zzz{ CubeCoord::CubeCoord() { cubeface=POSX; x=0; y=0; size=0; } CubeCoord::CubeCoord(const CUBEFACE _face,const zuint _x,const zuint _y, const zuint _size) { cubeface=_face; x=_x; y=_y; size=_size; } CubeCoord::CubeCoord(const CubeCoord& c) { *this=c; } const CubeCoord& CubeCoord::operator=(const CubeCoord& c) { x=c.x; y=c.y;size=c.size;cubeface=c.cubeface; return *this; } void CubeCoord::Standardize() { int ox=x,oy=y; int osize=size; if (ox>=0 && oy>=0 && ox<osize && oy<osize) return ; switch(cubeface) { case POSX: if (ox<0) {cubeface=POSZ; x+=size;Standardize();return;} if (ox>=osize) {cubeface=NEGZ; x-=size;Standardize();return;} if (oy<0) {cubeface=POSY; x=oy+osize; y=osize-1-ox;Standardize();return;} if (oy>=osize) {cubeface=NEGY; x=osize-1-(oy-osize); y=ox;Standardize();return;} break; case POSY: if (ox<0) {cubeface=NEGX; x=oy; y=-1-ox;Standardize();return;} if (ox>=osize) {cubeface=POSX; x=osize-1-oy; y=ox-osize;Standardize();return;} if (oy<0) {cubeface=NEGZ; x=osize-1-ox; y=-1-oy;Standardize();return;} if (oy>=osize) {cubeface=POSZ; x=ox; y=oy-osize;Standardize();return;} break; case POSZ: if (ox<0) {cubeface=NEGX; x+=osize;Standardize();return;} if (ox>=osize) {cubeface=POSX; x-=osize;Standardize();return;} if (oy<0) {cubeface=POSY; x=ox; y=oy+osize;Standardize();return;} if (oy>=osize) {cubeface=NEGY; x=ox; y=oy-osize;Standardize();return;} break; case NEGX: if (ox<0) {cubeface=NEGZ; x+=osize;Standardize();return;} if (ox>=osize) {cubeface=POSZ; x-=osize;Standardize();return;} if (oy<0) {cubeface=POSY; x=-1-oy; y=ox;Standardize();return;} if (oy>=osize) {cubeface=NEGY; x=oy-osize; y=osize-1-ox;Standardize();return;} break; case NEGY: if (ox<0) {cubeface=NEGX; x=osize-1-oy; y=ox+osize;Standardize();return;} if (ox>=osize) {cubeface=POSX; x=oy; y=osize-1-(ox-osize);Standardize();return;} if (oy<0) {cubeface=POSZ; x=ox; y=oy+osize;Standardize();return;} if (oy>=osize) {cubeface=NEGZ; x=osize-1-ox; y=osize-1-(oy-osize);Standardize();return;} break; case NEGZ: if (ox<0) {cubeface=POSX; x+=osize;Standardize();return;} if (ox>=osize) {cubeface=NEGX; x-=osize;Standardize();return;} if (oy<0) {cubeface=POSY; x=osize-1-ox; y=-1-oy;Standardize();return;} if (oy>=osize) {cubeface=NEGY; x=osize-1-ox; y=osize-1-(oy-osize);Standardize();return;} break; default: break; } return; } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/Coordinate.cpp
C++
gpl3
2,739
#include <common.hpp> #include "OpenGLTools.hpp" #include "../Resource/Shader/ShaderSpecify.hpp" #include <Utility/Log.hpp> namespace zzz{ GLfloat GLPointSize::old=1; GLfloat GLLineWidth::old=1; Vector<2, GLint> GLPolygonMode::old(GL_FILL,GL_FILL); Color<GLfloat> GLClearColor::old(1,1,1,1); GLfloat GLClearDepth::old=1.0f; GLint GLDrawBuffer::old=GL_BACK; GLint GLReadBuffer::old=GL_BACK; Vector<4,GLint> GLViewport::old; Vector<4,GLboolean> GLColorMask::old; Vector<4,double> GLRasterPos::old; GLint GLBindTexture1D::old; GLint GLBindTexture2D::old; GLint GLBindTexture3D::old; GLint GLBindTextureCube::old; GLint GLBindRenderBuffer::old; GLint GLBindFrameBuffer::old; GLint GLActiveTexture::old; bool InitGLEW() { // May be run more than once, for multiple renderer. GLenum err = glewInit(); if (GLEW_OK != err) { ZLOG(ZERROR) << "Error:" << glewGetErrorString(err) << endl; // GLEWinited = false; return false; } ZLOG(ZVERBOSE) << "OpenGL Vendor: " << (char*) glGetString(GL_VENDOR) << "\n"; ZLOG(ZVERBOSE) << "OpenGL Renderer: " << (char*) glGetString(GL_RENDERER) << "\n"; ZLOG(ZVERBOSE) << "OpenGL Version: " << (char*) glGetString(GL_VERSION) << "\n\n"; CheckGLVersion(); if (CheckGLSL()) MakeShaders(); return true; } void CheckGLVersion() { if (GLEW_VERSION_4_0) ZLOG(ZVERBOSE) << "OpenGL 4.0 is available!" << endl; else if (GLEW_VERSION_3_3) ZLOG(ZVERBOSE) << "OpenGL 3.3 is available!" << endl; else if (GLEW_VERSION_3_2) ZLOG(ZVERBOSE) << "OpenGL 3.2 is available!" << endl; else if (GLEW_VERSION_3_1) ZLOG(ZVERBOSE) << "OpenGL 3.1 is available!" << endl; else if (GLEW_VERSION_3_0) ZLOG(ZVERBOSE) << "OpenGL 3.0 is available!" << endl; else if (GLEW_VERSION_2_1) ZLOG(ZVERBOSE) << "OpenGL 2.1 is available!" << endl; else if (GLEW_VERSION_2_0) ZLOG(ZVERBOSE) << "OpenGL 2.0 is available!" << endl; else if (GLEW_VERSION_1_5) ZLOG(ZVERBOSE) << "OpenGL 1.5 core functions are available\n!!!!!!!!Graphics Card Driver may not be installed correctly!!!!!!!!" << endl; else if (GLEW_VERSION_1_4) ZLOG(ZVERBOSE) << "OpenGL 1.4 core functions are available\n!!!!!!!!Graphics Card Driver may not be installed correctly!!!!!!!!" << endl; else if (GLEW_VERSION_1_3) ZLOG(ZVERBOSE) << "OpenGL 1.3 core functions are available\n!!!!!!!!Graphics Card Driver may not be installed correctly!!!!!!!!" << endl; else if (GLEW_VERSION_1_2) ZLOG(ZVERBOSE) << "OpenGL 1.2 core functions are available\n!!!!!!!!Graphics Card Driver may not be installed correctly!!!!!!!!" << endl; } bool CheckGLSL() { static bool GLSL=false; if (GLSL==true) return true; GLSL=true; if (!CheckSupport("GL_ARB_fragment_shader")) GLSL=false; if (!CheckSupport("GL_ARB_vertex_shader")) GLSL=false; CheckSupport("GL_ARB_geometry_shader4"); if (!CheckSupport("GL_ARB_shader_objects")) GLSL=false; if (GLSL) ZLOG(ZVERBOSE) << "GLSL is available!\n"; else ZLOG(ZVERBOSE) << "GLSL is NOT available!\n"; return GLSL; } bool CheckSupport(const string &ext) { if (glewIsSupported(ext.c_str())==GL_TRUE) { ZLOGI<<ext<<" is supported!\n"; return true; } else { ZLOGI<<ext<<" is NOT supported\n"; return false; } } int CheckGLError(char *file, int line) { if (Context::current_context_==NULL) return 0; GLenum glErr; int retCode = 0; glErr = glGetError(); while (glErr != GL_NO_ERROR) { ZLOG(ZERROR) << "GL Error #" << glErr << "(" ; const GLubyte *x=gluErrorString(glErr); if (x != NULL) ZLOG(ZERROR) << x; ZLOG(ZERROR) << ") in File " << file << " at line: " << line << endl; retCode = 1; glErr = glGetError(); } return retCode; } //////////////////////////////////////////////////////////// OpenGLProjector::OpenGLProjector() { Refresh(); } void OpenGLProjector::Refresh() { glGetIntegerv(GL_VIEWPORT, viewport_); glGetDoublev(GL_MODELVIEW_MATRIX, modelview_); glGetDoublev(GL_PROJECTION_MATRIX, projection_); } zzz::Vector3d OpenGLProjector::UnProject(double winx, double winy, double winz) { Vector3d obj; gluUnProject(winx, winy, winz, modelview_, projection_, viewport_, &obj[0], &obj[1], &obj[2]); return obj; } zzz::Vector3d OpenGLProjector::Project(double objx, double objy, double objz) { Vector3d win; gluProject(objx, objy, objz, modelview_, projection_, viewport_, &win[0], &win[1], &win[2]); return win; } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/OpenGLTools.cpp
C++
gpl3
4,610
// SHRotationMatrix Class Definition // --------------------------------- // // Takes a rotation matrix of the form: // (r[0], r[3], r[6]) // (r[1], r[4], r[7]) // (r[2], r[5], r[8]) // and an order. Computes an order^2 x order^2 matrix. // #pragma once //#include "../../common.hpp" #include "SHCoeff.hpp" namespace zzz{ template <int SHN,typename T> class SHRotationMatrix { public: // You can set the inMatrix outside and then call computeMatrix SHRotationMatrix(){} // Constructor. Input the desired SH order and the original 3x3 transformation matrix SHRotationMatrix(T matrix[9], bool colmajor=true) { // copy the input matrix into local stroage. if (colmajor) memcpy(inMatrix,matrix,sizeof(T)*9); else { inMatrix[0]=matrix[0]; inMatrix[3]=matrix[1]; inMatrix[6]=matrix[2]; inMatrix[1]=matrix[3]; inMatrix[4]=matrix[4]; inMatrix[7]=matrix[5]; inMatrix[2]=matrix[6]; inMatrix[5]=matrix[7]; inMatrix[8]=matrix[8]; } // actually compute the matrix. computeMatrix(); } // Computes the order^2 x order^2 matrix void computeMatrix(void) { // initialize the matrix to 0's for (int i=0; i<order*order; i++) for (int j=0; j<order*order; j++) outMatrix[matIndex(i,j)] = 0; // 0th band {1x1 matrix} is the identity outMatrix[0] = 1; if (order < 2) return; // 1st band is a permutation of the 3D rotation matrix for (int count=0, i=-1; i<=1; i++) for (int j=-1; j<=1; j++) outMatrix[ matIndex((i+3)%3 + 1, (j+3)%3 + 1) ] = inMatrix[count++]; // 2nd+ bands use a recurrance relation. for (int l=2; l<order; l++) { int ctr = l*(l+1); for (int n=-l; n<=l; n++) for (int m=-l; m<=l; m++) outMatrix[ matIndex(ctr + n, ctr + m) ] = u_i_st(l, m, n) * U_i_st(l, m, n) + v_i_st(l, m, n) * V_i_st(l, m, n) + w_i_st(l, m, n) * W_i_st(l, m, n); } } // Applies the order^2 x order^2 matrix to vector 'in', stores the result in the vector 'out' void applyMatrix(const SHCoeff<SHN,T> &insh, SHCoeff<SHN,T> &outsh) { const T *in=insh.v; T *out=outsh.v; // first band (order 0) is a 1x1 identity rotation matrix out[0] = in[0]; // set up data for multiplying 2nd band (order 1) coefs int ord=1; int minIdx=1; int maxIdx=4; // multiply the rest of the matrix for (int idx=1; idx<order*order; idx++) { // multiply coefs from current band out[idx]=0; for (int j=minIdx; j<maxIdx; j++) out[idx] += outMatrix[ matIndex(j, idx) ] * in[j]; // increase the band, reset indices. if (idx>=maxIdx-1) { ord++; minIdx=maxIdx; maxIdx+=2*ord+1; } } } T inMatrix[9]; private: static const int order=SHN; T outMatrix[SHN*SHN*SHN*SHN]; // Compute a 1D index for (col,row) in the matrix int matIndex(int col, int row) { return col*order*order+row; } // Computed as desribed in Table B.1 T u_i_st (int i, int s, int t) { return sqrt(double((i+s)*(i-s) / (abs(t)==i ? 2*i*(2*i-1) : (i+t)*(i-t)))); } T v_i_st (int i, int s, int t) { int delta = (s==0 ? 1 : 0); T factor = 0.5 * (1 - 2*delta); T numerator = (1+delta)*(i+abs(s)-1)*(i+abs(s)); T denominator = (abs(t)==i ? 2*i*(2*i-1) : (i+t)*(i-t)); return factor * sqrt(numerator / denominator); } T w_i_st (int i, int s, int t) { int delta = (s==0 ? 1 : 0); T factor = -0.5 * (1 - delta); T numerator = (i-abs(s)-1)*(i-abs(s)); T denominator = (abs(t)==i ? 2*i*(2*i-1) : (i+t)*(i-t)); return factor * sqrt(numerator / denominator); } // Computed as described in Table B.2 T U_i_st (int i, int s, int t) { return P_r_i_st(0,i,s,t); } T V_i_st (int i, int s, int t) { int delta = (abs(s)==1 ? 1 : 0); if (s == 0) return P_r_i_st(1,i,1,t) + P_r_i_st(-1,i,-1,t); if (s > 0) return sqrt(1.0+delta) * P_r_i_st(1,i,s-1,t) - (1-delta) * P_r_i_st(-1,i,-s+1,t); return (1-delta) * P_r_i_st(1,i,s+1,t) + sqrt(1.0+delta) * P_r_i_st(-1,i,-s-1,t); } T W_i_st (int i, int s, int t) { if (s==0) return 0; if (s > 0) return P_r_i_st(1,i,s+1,t) + P_r_i_st(-1,i,-s-1,t); return P_r_i_st(1,i,s-1,t) - P_r_i_st(-1,i,-s+1,t); } // Computed as described in Table B.3 T P_r_i_st (int r, int i, int s, int t) { if (abs(t) < i) return R(r,0)*M(i-1,s,t); if (t == i) return R(r,1)*M(i-1,s,i-1) - R(r,-1)*M(i-1,s,-i+1); return R(r,1)*M(i-1,s,-i+1) + R(r,-1)*M(i-1,s,i-1); } // Index into the input matrix for -1 <= i,j <= 1, as per Equation B.40 T R (int i, int j) { int jp = ((j+2) % 3); // 0 <= jp < 3 int ip = ((i+2) % 3); // 0 <= ip < 3 return inMatrix[jp*3+ip]; // index into input matrix } // Index into band l, element (a,b) of the result (-l <= a,b <= l) T M(int l, int a, int b) { if (l<=0) return outMatrix[0]; // Find the center of band l (outMatrix[ctr,ctr]) int ctr = l*(l+1); return outMatrix[ matIndex(ctr + b, ctr + a) ]; } }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/SH/SHRotationMatrix.hpp
C++
gpl3
5,126
#ifdef ZZZ_SSE #include "SHCoeff4f_SSE.hpp" namespace zzz{ SHCoeff4f_SSE::SHCoeff4f_SSE(void) { } SHCoeff4f_SSE::SHCoeff4f_SSE(float *data) { *this=data; } SHCoeff4f_SSE::SHCoeff4f_SSE(const SHCoeff4f_SSE &coef) { *this=coef; } SHCoeff4f_SSE::~SHCoeff4f_SSE(void) { } void SHCoeff4f_SSE::TripleProduct4Appr(SHCoeff4f_SSE *ret,const SHCoeff4f_SSE &coef) { if (ret==this) { SHCoeff4f_SSE tmp(*this); tmp.TripleProduct4Appr(this,coef); return; } ret->Zero(); float *c=ret->v; const float *a=v,*b=coef.v; c[0]=0.282095f*Dot(coef); c[6]+=0.090109f*a[5]*b[5]; c[8]+=-0.058340f*(a[3]*b[13]+a[13]*b[3]); c[7]+=0.059470f*(a[12]*b[13]+a[13]*b[12]); c[5]+=0.059471f*(a[11]*b[12]+a[12]*b[11]); c[3]+=-0.058340f*(a[8]*b[13]+a[13]*b[8]); c[13]+=-0.058340f*(a[3]*b[8]+a[8]*b[3]); c[11]+=0.058369f*(a[1]*b[8]+a[8]*b[1]); c[1]+=0.058369f*(a[8]*b[11]+a[11]*b[8]); c[4]+=-0.058452f*(a[3]*b[11]+a[11]*b[3]); c[12]+=0.059470f*(a[7]*b[13]+a[13]*b[7]); c[6]+=0.090120f*a[7]*b[7]; c[8]+=0.058369f*(a[1]*b[11]+a[11]*b[1]); c[7]+=0.090120f*(a[6]*b[7]+a[7]*b[6]); c[5]+=0.090109f*(a[5]*b[6]+a[6]*b[5]); c[3]+=-0.058452f*(a[4]*b[11]+a[11]*b[4]); c[13]+=-0.058452f*(a[1]*b[4]+a[4]*b[1]); c[11]+=-0.058452f*(a[3]*b[4]+a[4]*b[3]); c[1]+=-0.058452f*(a[4]*b[13]+a[13]*b[4]); c[4]+=-0.058452f*(a[1]*b[13]+a[13]*b[1]); c[10]+=0.115150f*(a[5]*b[13]+a[13]*b[5]); c[6]+=0.126182f*a[11]*b[11]; c[8]+=-0.094025f*(a[9]*b[11]+a[11]*b[9]); c[7]+=0.115150f*(a[10]*b[11]+a[11]*b[10]); c[5]+=0.115150f*(a[10]*b[13]+a[13]*b[10]); c[3]+=-0.126223f*(a[3]*b[6]+a[6]*b[3]); c[13]+=0.059470f*(a[7]*b[12]+a[12]*b[7]); c[11]+=0.059471f*(a[5]*b[12]+a[12]*b[5]); c[1]+=-0.126236f*(a[1]*b[6]+a[6]*b[1]); c[4]+=-0.094033f*(a[9]*b[13]+a[13]*b[9]); c[14]+=0.115169f*(a[7]*b[13]+a[13]*b[7]); c[6]+=-0.126223f*a[3]*b[3]; c[8]+=-0.094056f*(a[13]*b[15]+a[15]*b[13]); c[7]+=0.115169f*(a[13]*b[14]+a[14]*b[13]); c[5]+=-0.115175f*(a[11]*b[14]+a[14]*b[11]); c[3]+=-0.142912f*(a[7]*b[12]+a[12]*b[7]); c[13]+=-0.094033f*(a[4]*b[9]+a[9]*b[4]); c[11]+=-0.094025f*(a[8]*b[9]+a[9]*b[8]); c[1]+=-0.143046f*(a[5]*b[12]+a[12]*b[5]); c[4]+=0.094033f*(a[11]*b[15]+a[15]*b[11]); c[2]+=0.184449f*(a[8]*b[14]+a[14]*b[8]); c[6]+=-0.126236f*a[1]*b[1]; c[8]+=-0.145674f*a[11]*b[11]; c[7]+=-0.142912f*(a[3]*b[12]+a[12]*b[3]); c[5]+=-0.143046f*(a[1]*b[12]+a[12]*b[1]); c[3]+=0.184557f*(a[5]*b[10]+a[10]*b[5]); c[13]+=-0.094056f*(a[8]*b[15]+a[15]*b[8]); c[11]+=0.094033f*(a[4]*b[15]+a[15]*b[4]); c[1]+=0.184557f*(a[7]*b[10]+a[10]*b[7]); c[4]+=0.145561f*(a[11]*b[13]+a[13]*b[11]); c[12]+=0.059471f*(a[5]*b[11]+a[11]*b[5]); c[6]+=0.126282f*a[13]*b[13]; c[8]+=0.145785f*a[13]*b[13]; c[7]+=0.148543f*(a[14]*b[15]+a[15]*b[14]); c[5]+=0.148600f*(a[9]*b[14]+a[14]*b[9]); c[9]+=-0.094025f*(a[8]*b[11]+a[11]*b[8]); c[15]+=0.094033f*(a[4]*b[11]+a[11]*b[4]); c[10]+=0.115150f*(a[7]*b[11]+a[11]*b[7]); c[11]+=0.115150f*(a[7]*b[10]+a[10]*b[7]); c[13]+=0.115150f*(a[5]*b[10]+a[10]*b[5]); c[14]+=-0.115175f*(a[5]*b[11]+a[11]*b[5]); c[6]+=0.168126f*a[12]*b[12]; c[8]+=-0.156112f*a[5]*b[5]; c[7]+=0.148683f*(a[9]*b[10]+a[10]*b[9]); c[5]+=-0.148673f*(a[10]*b[15]+a[15]*b[10]); c[4]+=0.155967f*(a[5]*b[7]+a[7]*b[5]); c[2]+=0.184558f*(a[4]*b[10]+a[10]*b[4]); c[1]+=-0.184781f*(a[5]*b[14]+a[14]*b[5]); c[3]+=0.184955f*(a[7]*b[14]+a[14]*b[7]); c[9]+=-0.094033f*(a[4]*b[13]+a[13]*b[4]); c[15]+=-0.094056f*(a[8]*b[13]+a[13]*b[8]); c[6]+=0.180199f*a[6]*b[6]; c[8]+=0.156254f*a[7]*b[7]; c[13]+=0.115169f*(a[7]*b[14]+a[14]*b[7]); c[11]+=-0.115175f*(a[5]*b[14]+a[14]*b[5]); c[12]+=-0.142912f*(a[3]*b[7]+a[7]*b[3]); c[14]+=0.148543f*(a[7]*b[15]+a[15]*b[7]); c[10]+=-0.148673f*(a[5]*b[15]+a[15]*b[5]); c[5]+=0.155967f*(a[4]*b[7]+a[7]*b[4]); c[7]+=0.155967f*(a[4]*b[5]+a[5]*b[4]); c[4]+=-0.180333f*(a[4]*b[6]+a[6]*b[4]); c[6]+=-0.180333f*a[4]*b[4]; c[8]+=-0.180343f*(a[6]*b[8]+a[8]*b[6]); c[3]+=0.202190f*(a[6]*b[13]+a[13]*b[6]); c[1]+=0.202243f*(a[6]*b[11]+a[11]*b[6]); c[2]+=0.218414f*(a[3]*b[7]+a[7]*b[3]); c[11]+=0.126182f*(a[6]*b[11]+a[11]*b[6]); c[13]+=0.126282f*(a[6]*b[13]+a[13]*b[6]); c[12]+=-0.143046f*(a[1]*b[5]+a[5]*b[1]); c[15]+=0.148543f*(a[7]*b[14]+a[14]*b[7]); c[14]+=0.148600f*(a[5]*b[9]+a[9]*b[5]); c[6]+=-0.180343f*a[8]*b[8]; c[8]+=0.184449f*(a[2]*b[14]+a[14]*b[2]); c[9]+=0.148600f*(a[5]*b[14]+a[14]*b[5]); c[10]+=0.148683f*(a[7]*b[9]+a[9]*b[7]); c[5]+=-0.156112f*(a[5]*b[8]+a[8]*b[5]); c[7]+=0.156254f*(a[7]*b[8]+a[8]*b[7]); c[4]+=0.184558f*(a[2]*b[10]+a[10]*b[2]); c[1]+=0.218374f*(a[3]*b[4]+a[4]*b[3]); c[3]+=0.218374f*(a[1]*b[4]+a[4]*b[1]); c[2]+=0.218461f*(a[1]*b[5]+a[5]*b[1]); c[6]+=0.202190f*(a[3]*b[13]+a[13]*b[3]); c[8]+=-0.187900f*(a[12]*b[14]+a[14]*b[12]); c[11]+=0.145561f*(a[4]*b[13]+a[13]*b[4]); c[13]+=0.145561f*(a[4]*b[11]+a[11]*b[4]); c[15]+=-0.148673f*(a[5]*b[10]+a[10]*b[5]); c[9]+=0.148683f*(a[7]*b[10]+a[10]*b[7]); c[12]+=0.168126f*(a[6]*b[12]+a[12]*b[6]); c[14]+=0.184449f*(a[2]*b[8]+a[8]*b[2]); c[5]+=0.184557f*(a[3]*b[10]+a[10]*b[3]); c[10]+=0.184557f*(a[3]*b[5]+a[5]*b[3]); c[6]+=0.202243f*(a[1]*b[11]+a[11]*b[1]); c[7]+=0.184558f*(a[1]*b[10]+a[10]*b[1]); c[4]+=-0.188019f*(a[10]*b[12]+a[12]*b[10]); c[3]+=0.218414f*(a[2]*b[7]+a[7]*b[2]); c[1]+=0.218461f*(a[2]*b[5]+a[5]*b[2]); c[8]+=-0.218732f*a[1]*b[1]; c[2]+=0.233572f*(a[5]*b[11]+a[11]*b[5]); c[11]+=-0.145674f*(a[8]*b[11]+a[11]*b[8]); c[13]+=0.145785f*(a[8]*b[13]+a[13]*b[8]); c[10]+=0.184558f*(a[1]*b[7]+a[7]*b[1]); c[6]+=-0.210482f*a[9]*b[9]; c[5]+=-0.184781f*(a[1]*b[14]+a[14]*b[1]); c[14]+=-0.184781f*(a[1]*b[5]+a[5]*b[1]); c[7]+=0.184955f*(a[3]*b[14]+a[14]*b[3]); c[12]+=-0.187900f*(a[8]*b[14]+a[14]*b[8]); c[9]+=-0.210482f*(a[6]*b[9]+a[9]*b[6]); c[15]+=-0.210522f*(a[6]*b[15]+a[15]*b[6]); c[4]+=0.218374f*(a[1]*b[3]+a[3]*b[1]); c[1]+=-0.218732f*(a[1]*b[8]+a[8]*b[1]); c[8]+=0.218821f*a[3]*b[3]; c[3]+=0.218821f*(a[3]*b[8]+a[8]*b[3]); c[6]+=-0.210522f*a[15]*b[15]; c[2]+=0.233583f*(a[7]*b[13]+a[13]*b[7]); c[10]+=0.184558f*(a[2]*b[4]+a[4]*b[2]); c[14]+=0.184955f*(a[3]*b[7]+a[7]*b[3]); c[12]+=-0.188019f*(a[4]*b[10]+a[10]*b[4]); c[13]+=0.202190f*(a[3]*b[6]+a[6]*b[3]); c[11]+=0.202243f*(a[1]*b[6]+a[6]*b[1]); c[7]+=0.218414f*(a[2]*b[3]+a[3]*b[2]); c[5]+=0.218461f*(a[1]*b[2]+a[2]*b[1]); c[15]+=0.226034f*(a[3]*b[8]+a[8]*b[3]); c[3]+=0.226034f*(a[8]*b[15]+a[15]*b[8]); c[8]+=0.226034f*(a[3]*b[15]+a[15]*b[3]); c[1]+=0.226108f*(a[8]*b[9]+a[9]*b[8]); c[9]+=0.226108f*(a[1]*b[8]+a[8]*b[1]); c[4]+=-0.226136f*(a[1]*b[15]+a[15]*b[1]); c[6]+=0.247669f*(a[2]*b[12]+a[12]*b[2]); c[2]+=0.247669f*(a[6]*b[12]+a[12]*b[6]); c[14]+=-0.187900f*(a[8]*b[12]+a[12]*b[8]); c[10]+=-0.188019f*(a[4]*b[12]+a[12]*b[4]); c[15]+=-0.226136f*(a[1]*b[4]+a[4]*b[1]); c[3]+=0.226185f*(a[4]*b[9]+a[9]*b[4]); c[8]+=0.226108f*(a[1]*b[9]+a[9]*b[1]); c[1]+=-0.226136f*(a[4]*b[15]+a[15]*b[4]); c[9]+=0.226185f*(a[3]*b[4]+a[4]*b[3]); c[4]+=0.226185f*(a[3]*b[9]+a[9]*b[3]); c[5]+=0.233572f*(a[2]*b[11]+a[11]*b[2]); c[11]+=0.233572f*(a[2]*b[5]+a[5]*b[2]); c[7]+=0.233583f*(a[2]*b[13]+a[13]*b[2]); c[13]+=0.233583f*(a[2]*b[7]+a[7]*b[2]); c[12]+=0.247669f*(a[2]*b[6]+a[6]*b[2]); c[2]+=0.252308f*(a[2]*b[6]+a[6]*b[2]); c[6]+=0.252308f*a[2]*b[2]; c[8]+=0.281341f*(a[0]*b[8]+a[8]*b[0]); c[9]+=0.281264f*(a[0]*b[9]+a[9]*b[0]); c[15]+=0.281361f*(a[0]*b[15]+a[15]*b[0]); c[3]+=0.281660f*(a[0]*b[3]+a[3]*b[0]); c[14]+=0.281727f*(a[0]*b[14]+a[14]*b[0]); c[1]+=0.281767f*(a[0]*b[1]+a[1]*b[0]); c[10]+=0.281894f*(a[0]*b[10]+a[10]*b[0]); c[12]+=0.281884f*(a[0]*b[12]+a[12]*b[0]); c[4]+=0.281897f*(a[0]*b[4]+a[4]*b[0]); c[13]+=0.281956f*(a[0]*b[13]+a[13]*b[0]); c[6]+=0.281966f*(a[0]*b[6]+a[6]*b[0]); c[7]+=0.281987f*(a[0]*b[7]+a[7]*b[0]); c[5]+=0.282009f*(a[0]*b[5]+a[5]*b[0]); c[11]+=0.282026f*(a[0]*b[11]+a[11]*b[0]); c[2]+=0.282066f*(a[0]*b[2]+a[2]*b[0]); } } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/SH/SHCoeff4f_SSE.cpp
C++
gpl3
8,623
#pragma once #include "SHCoeff.hpp" #include <xmmintrin.h> namespace zzz{ class SHCoeff4f_SSE{ public: union{ float __declspec(align(16)) v[16]; struct {__m128 v0,v1,v2,v3;}; }; public: //inline functions inline const SHCoeff4f_SSE& operator=(const float *data) { v[0]=data[0]; v[1]=data[1]; v[2]=data[2]; v[3]=data[3]; v[4]=data[4]; v[5]=data[5]; v[6]=data[6]; v[7]=data[7]; v[8]=data[8]; v[9]=data[9]; v[10]=data[10]; v[11]=data[11]; v[12]=data[12]; v[13]=data[13]; v[14]=data[14]; v[15]=data[15]; return *this; } inline const SHCoeff4f_SSE& operator=(const SHCoeff4f &data) { v[0]=data.v[0]; v[1]=data.v[1]; v[2]=data.v[2]; v[3]=data.v[3]; v[4]=data.v[4]; v[5]=data.v[5]; v[6]=data.v[6]; v[7]=data.v[7]; v[8]=data.v[8]; v[9]=data.v[9]; v[10]=data.v[10]; v[11]=data.v[11]; v[12]=data.v[12]; v[13]=data.v[13]; v[14]=data.v[14]; v[15]=data.v[15]; return *this; } inline const SHCoeff4f_SSE& operator=(const SHCoeff4f_SSE& coef) { /*/// Assembly code _asm { mov eax, coef //move &coef to eax, coef is a pointer as to assembler mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //coef to register movaps xmm0, [eax]coef.v //all floats are moved to register before moved to target movaps xmm1, [eax]coef.v+16 //to increase pipeline parallelity movaps xmm2, [eax]coef.v+32 movaps xmm3, [eax]coef.v+48 //register to this movaps [edx]this.v, xmm0 movaps [edx]this.v+16, xmm1 movaps [edx]this.v+32, xmm2 movaps [edx]this.v+48, xmm3 } /*/// Equivalent SSE intrinsic code *((__m128 *)(v))=_mload_ps_(coef.v); *((__m128 *)(v+4))=_mload_ps_(coef.v+4); *((__m128 *)(v+8))=_mload_ps_(coef.v+8); *((__m128 *)(v+12))=_mload_ps_(coef.v+12); //*/ return *this; } inline void operator+=(const SHCoeff4f_SSE& coef) { /*/// Assembly code _asm { mov eax, coef //move &coef to eax, coef is a pointer as to assembler mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //coef to register movaps xmm0, [eax]coef.v movaps xmm1, [eax]coef.v+16 movaps xmm2, [eax]coef.v+32 movaps xmm3, [eax]coef.v+48 //this to register movaps xmm4, [edx]this.v movaps xmm5, [edx]this.v+16 movaps xmm6, [edx]this.v+32 movaps xmm7, [edx]this.v+48 //add addps xmm4, xmm0 addps xmm5, xmm1 addps xmm6, xmm2 addps xmm7, xmm3 //register to this movaps [edx]this.v, xmm4 movaps [edx]this.v+16, xmm5 movaps [edx]this.v+32, xmm6 movaps [edx]this.v+48, xmm7 } /*/// Equivalent SSE intrinsic code *((__m128 *)(v))=_madd_ps_(*((__m128 *)(v)),*((__m128 *)(coef.v))); *((__m128 *)(v+4))=_madd_ps_(*((__m128 *)(v+4)),*((__m128 *)(coef.v+4))); *((__m128 *)(v+8))=_madd_ps_(*((__m128 *)(v+8)),*((__m128 *)(coef.v+8))); *((__m128 *)(v+12))=_madd_ps_(*((__m128 *)(v+12)),*((__m128 *)(coef.v+12))); //*/ } inline void operator-=(const SHCoeff4f_SSE& coef) { /*/// Assembly code _asm { mov eax, coef //move &coef to eax, coef is a pointer as to assembler mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //coef to register movaps xmm0, [eax]coef.v movaps xmm1, [eax]coef.v+16 movaps xmm2, [eax]coef.v+32 movaps xmm3, [eax]coef.v+48 //this to register movaps xmm4, [edx]this.v movaps xmm5, [edx]this.v+16 movaps xmm6, [edx]this.v+32 movaps xmm7, [edx]this.v+48 //subtract subps xmm4, xmm0 subps xmm5, xmm1 subps xmm6, xmm2 subps xmm7, xmm3 //register to this movaps [edx]this.v, xmm4 movaps [edx]this.v+16, xmm5 movaps [edx]this.v+32, xmm6 movaps [edx]this.v+48, xmm7 } /*/// Equivalent SSE intrinsic code *((__m128 *)(v))=_msub_ps_(*((__m128 *)(v)),*((__m128 *)(coef.v))); *((__m128 *)(v+4))=_msub_ps_(*((__m128 *)(v+4)),*((__m128 *)(coef.v+4))); *((__m128 *)(v+8))=_msub_ps_(*((__m128 *)(v+8)),*((__m128 *)(coef.v+8))); *((__m128 *)(v+12))=_msub_ps_(*((__m128 *)(v+12)),*((__m128 *)(coef.v+12))); //*/ } inline const SHCoeff4f_SSE operator*(const float scale) const { /*/// Assembly code __m128 r[4]; //use SHCoeff4f_SSE here will cause an extra //constructor call _asm { mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //scale to register movss xmm0, scale //move scale to xmm0 shufps xmm0, xmm0, 0 //shuffle scale to all 4 floats in xmm0 //this to register movaps xmm1, [edx]this.v movaps xmm2, [edx]this.v+16 movaps xmm3, [edx]this.v+32 movaps xmm4, [edx]this.v+48 //multiply mulps xmm1, xmm0 mulps xmm2, xmm0 mulps xmm3, xmm0 mulps xmm4, xmm0 //register to this movaps r, xmm1 movaps r+16, xmm2 movaps r+32, xmm3 movaps r+48, xmm4 } return *((SHCoeff4f_SSE *)r); /*/// Equivalent SSE intrinsic code __m128 temp=_mload_ps1_(&scale); *((__m128 *)(v))=_mmul_ps_(*((__m128 *)(v)),temp); *((__m128 *)(v+4))=_mmul_ps_(*((__m128 *)(v+4)),temp); *((__m128 *)(v+8))=_mmul_ps_(*((__m128 *)(v+8)),temp); *((__m128 *)(v+12))=_mmul_ps_(*((__m128 *)(v+12)),temp); //*/ } inline void operator*=(const float scale) { /*/// Assembly code _asm { mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //scale to register movss xmm0, scale //move scale to xmm0 shufps xmm0, xmm0, 0 //shuffle scale to all 4 floats in xmm0 //this to register movaps xmm1, [edx]this.v movaps xmm2, [edx]this.v+16 movaps xmm3, [edx]this.v+32 movaps xmm4, [edx]this.v+48 //multiply mulps xmm1, xmm0 mulps xmm2, xmm0 mulps xmm3, xmm0 mulps xmm4, xmm0 //register to this movaps [edx]this.v, xmm1 movaps [edx]this.v+16, xmm2 movaps [edx]this.v+32, xmm3 movaps [edx]this.v+48, xmm4 } /*/// Equivalent SSE intrinsic code __m128 temp=_mload_ps1_(&scale); *((__m128 *)(v))=_mmul_ps_(*((__m128 *)(v)),temp); *((__m128 *)(v+4))=_mmul_ps_(*((__m128 *)(v+4)),temp); *((__m128 *)(v+8))=_mmul_ps_(*((__m128 *)(v+8)),temp); *((__m128 *)(v+12))=_mmul_ps_(*((__m128 *)(v+12)),temp); //*/ } inline void operator/=(const float scale) { /*/// Assembly code _asm { mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //scale to register movss xmm0, scale //move scale to xmm0 shufps xmm0, xmm0, 0 //shuffle scale to all 4 floats in xmm0 //this to register movaps xmm1, [edx]this.v movaps xmm2, [edx]this.v+16 movaps xmm3, [edx]this.v+32 movaps xmm4, [edx]this.v+48 //divide divps xmm1, xmm0 divps xmm2, xmm0 divps xmm3, xmm0 divps xmm4, xmm0 //register to this movaps [edx]this.v, xmm1 movaps [edx]this.v+16, xmm2 movaps [edx]this.v+32, xmm3 movaps [edx]this.v+48, xmm4 } /*/// Equivalent SSE intrinsic code __m128 temp=_mload_ps1_(&scale); *((__m128 *)(v))=_mdiv_ps_(*((__m128 *)(v)),temp); *((__m128 *)(v+4))=_mdiv_ps_(*((__m128 *)(v+4)),temp); *((__m128 *)(v+8))=_mdiv_ps_(*((__m128 *)(v+8)),temp); *((__m128 *)(v+12))=_mdiv_ps_(*((__m128 *)(v+12)),temp); //*/ } inline float Dot(const SHCoeff4f_SSE &coef) const { /*/// Assembly code __m128 tmp; //local variable to hold temporarily value _asm { mov eax, coef //move &coef to eax, coef is a pointer as to assembler mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //coef to register movaps xmm0, [eax]coef.v movaps xmm1, [eax]coef.v+16 movaps xmm2, [eax]coef.v+32 movaps xmm3, [eax]coef.v+48 //this to register movaps xmm4, [edx]this.v movaps xmm5, [edx]this.v+16 movaps xmm6, [edx]this.v+32 movaps xmm7, [edx]this.v+48 //multiply and add //mulps and addps are executed alternatively to increase parallelity mulps xmm4, xmm0 mulps xmm5, xmm1 addps xmm4, xmm5 mulps xmm6, xmm2 addps xmm4, xmm6 mulps xmm7, xmm3 addps xmm4, xmm7 //register to tmp movaps tmp, xmm4 fld tmp fadd tmp[4] fadd tmp[8] fadd tmp[12] } /*/// Equivalent SSE intrinsic code __m128 tmp0,tmp1; __m128 tmp2=coef.v0; tmp0=_mmul_ps_(*((__m128 *)(v)),tmp2); //*((__m128 *)(coef.v))); tmp1=_mmul_ps_(*((__m128 *)(v+4)),*((__m128 *)(coef.v+4))); tmp0=_madd_ps_(tmp0,tmp1); tmp1=_mmul_ps_(*((__m128 *)(v+8)),*((__m128 *)(coef.v+8))); tmp0=_madd_ps_(tmp0,tmp1); tmp1=_mmul_ps_(*((__m128 *)(v+12)),*((__m128 *)(coef.v+12))); tmp0=_madd_ps_(tmp0,tmp1); return tmp0.m128_f32[0]+tmp0.m128_f32[1]+tmp0.m128_f32[2]+tmp0.m128_f64[3]; //*/ } inline void Zero() { /*/// Assembly code _asm { mov edx, this //though "this" is always stored in ecx for thiscall functions //inline makes the call not guaranteed //set xmm0 to zero xorps xmm0,xmm0 //copy xmm0 to this movaps [edx]this.v, xmm0 movaps [edx]this.v+16, xmm0 movaps [edx]this.v+32, xmm0 movaps [edx]this.v+48, xmm0 } /*/// Equivalent SSE intrinsic code *((__m128 *)(v))=_msetzero_ps_(); *((__m128 *)(v+4))=_msetzero_ps_(); *((__m128 *)(v+8))=_msetzero_ps_(); *((__m128 *)(v+12))=_msetzero_ps_(); //*/ } inline void Dump() const { printf("%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n", v[0],v[1],v[2],v[3], v[4],v[5],v[6],v[7], v[8],v[9],v[10],v[11], v[12],v[13],v[14],v[15]); } inline float& operator [](int index) { return v[index]; } inline const float& operator[](int index) const { return v[index]; } inline void TripleProduct(const SHCoeff4f_SSE &coef) { TripleProduct4Appr(this,coef); } void TripleProduct4Appr(SHCoeff4f_SSE *ret,const SHCoeff4f_SSE &coef); public: //constructor and destructor SHCoeff4f_SSE(void); SHCoeff4f_SSE(const SHCoeff4f_SSE &coef); SHCoeff4f_SSE(float *data); ~SHCoeff4f_SSE(void); //new and delete inline void* operator new(size_t size) { return _aligned_malloc(size,16); } inline void* operator new(size_t size,void *p) { return p; } inline void* operator new[](size_t size) { return _aligned_malloc(size,16); } inline void* operator new[](size_t size,void *p) { return p; } inline void operator delete(void *p) { _aligned_free(p); } inline void operator delete(void *p, void *c) { return; } inline void operator delete[](void *p) { _aligned_free(p); } inline void operator delete[](void *p,void *c) { return; } inline bool operator ==(const SHCoeff4f_SSE& x) const { return v[0]==x[0] &&\ v[1]==x[1] &&\ v[2]==x[2] &&\ v[3]==x[3] &&\ v[4]==x[4] &&\ v[5]==x[5] &&\ v[6]==x[6] &&\ v[7]==x[7] &&\ v[8]==x[8] &&\ v[9]==x[9] &&\ v[10]==x[10] &&\ v[11]==x[11] &&\ v[12]==x[12] &&\ v[13]==x[13] &&\ v[14]==x[14] &&\ v[15]==x[15]; } inline operator SHCoeff4f() { SHCoeff4f ret; for (int i=0; i<16; i++) ret.v[i]=v[i]; return ret; } }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/SH/SHCoeff4f_SSE.hpp
C++
gpl3
12,482
#pragma once #include <Math/Matrix3x3.hpp> #include <Math/Vector3.hpp> namespace zzz{ template <std::size_t N,typename T=float> struct SHCoeff { T v[N*N]; const int order_; SHCoeff():order_(N) { } const SHCoeff& operator=(float *data) { for (int i=0; i<N*N; i++) v[i]=data[i]; return *this; } const SHCoeff& operator=(const SHCoeff<N,T>& coef) { for (int i=0; i<N*N; i++) v[i]=coef[i]; return *this; } //NO +-*/ SINCE +=,-=,*=,/= IS RECOMMEND TO USE void operator+=(const SHCoeff<N,T>& coef) { for (int i=0; i<N*N; i++) v[i]+=coef.v[i]; } void operator-=(const SHCoeff<N,T>& coef) { for (int i=0; i<N*N; i++) v[i]-=coef.v[i]; } void operator*=(const T scaler) { for (int i=0; i<N*N; i++) v[i]*=scaler; } void operator/=(const T scaler) { for (int i=0; i<N*N; i++) v[i]/=scaler; } const SHCoeff operator*(float scale) { SHCoeff<N,T> ret; for (int i=0; i<N*N; i++) ret.v[i]=v[i]*scale; return ret; } inline T& operator [](int index) { return v[index]; } inline const T& operator [](int index) const { return v[index]; } float Dot(const SHCoeff<N,T> &coef) { float ret=0; for (int i=0; i<N*N; i++) ret+=v[i]*coef.v[i]; return ret; } void Zero(T x=0) { for (int i=0; i<N*N; i++) v[i]=x; } void MultiMatRowMajor(const float *mat) { SHCoeff<N,T> tmp; for (int i=0; i<N*N; i++) for (int j=0; j<N*N; j++,mat++) tmp.v[i]+=*mat*v[j]; *this=tmp; } void MultiMatColMajor(const float *mat) { SHCoeff<N,T> tmp; for (int i=0; i<N*N; i++) for (int j=0; j<N*N; j++,mat++) tmp.v[j]+=*mat*v[i]; *this=tmp; } void MultiRotateMat(const float *mat) { SHCoeff<N,T> tmp; float *t=v; for (int i=0; i<N; i++) for (int j=0; j<=2*i; j++,mat+=N*N,t++) for (int k=i*i; k<(i+1)*(i+1); k++) *t+=mat[k]*v[k]; *this=tmp; } void MultiRotateMatAtRightSize(const float *mat) { SHCoeff<N,T> tmp; float *t=v; for (int i=0; i<N; i++) for (int j=0; j<=2*i; j++,mat++,t++) for (int k=i*i; k<(i+1)*(i+1); k++) *t+=mat[k]*v[k]; *this=tmp; } void TripleProduct(const SHCoeff<N,T> &coef) { printf("TripleProduct: Must be specialize to use!\n"); } void TripleProductMatrix(float *ret) { printf("TripleProductMatrix: Must be specialize to use!\n"); } friend ostream& operator<<(ostream &o,SHCoeff<N,T> &me) { me.SaveToFileA(o); return o; } friend istream& operator>>(istream &i,SHCoeff<N,T> &me) { me.LoadFromFileA(i); return i; } void SaveToFileA(ostream &fo) { for (int i=0; i<N*N; i++) fo<<v[i]<<' '; fo<<endl; } void LoadFromFileA(istream &fi) { for (int i=0; i<N*N; i++) fi>>v[i]; } void LoadFromFileA(FILE *fp) { printf("LoadFromFileA(FILE *fp) must be specialized to use!\n"); } void SaveToFileB(FILE *fp) { fwrite(v,sizeof(T),N*N,fp); } void LoadFromFileB(FILE *fp) { fread(v,sizeof(T),N*N,fp); } //ROTATION void RotationMatrix_Ivanic(const Matrix<3,3,T> &rot) { int order=N; T ret[N*N*N*N]; T R[10][10]; T M[10][10*2-1][10*2-1]; static T u[10][10*2-1][10*2-1],U[10][10*2-1][10*2-1],v[10][10*2-1][10*2-1],V[10][10*2-1][10*2-1],w[10][10*2-1][10*2-1],W[10][10*2-1][10*2-1]; T P[10][3][10*2-1][10*2-1]; memset(R,0,sizeof(R)); memset(M,0,sizeof(M)); memset(P,0,sizeof(P)); static bool firsttime=true; if (firsttime) { memset(u,0,sizeof(u)); memset(v,0,sizeof(v)); memset(w,0,sizeof(w)); firsttime=false; } memset(U,0,sizeof(U)); memset(V,0,sizeof(V)); memset(W,0,sizeof(W)); R[0][0]=rot.v[4]; R[0][1]=-rot.v[7]; R[0][2]=rot.v[1]; R[1][0]=-rot.v[5]; R[1][1]=rot.v[8]; R[1][2]=-rot.v[2]; R[2][0]=rot.v[3]; R[2][1]=-rot.v[6]; R[2][2]=rot.v[0]; M[0][0][0]=1.0f; M[1][0][0]=R[0][0]; M[1][0][1]=R[0][1]; M[1][0][2]=R[0][2]; M[1][1][0]=R[1][0]; M[1][1][1]=R[1][1]; M[1][1][2]=R[1][2]; M[1][2][0]=R[2][0]; M[1][2][1]=R[2][1]; M[1][2][2]=R[2][2]; static int last_largest_order=2; if (order>last_largest_order) { for (int i=last_largest_order; i<order; i++) for (int s=-i; s<=i; s++) for (int t=-i; t<=i; t++) { if (abs(t)<i) { float d=(s==0?1.0f:0.0f); u[i][s+i][t+i]=sqrt((i+s)*(i-s)/(float)(i+t)/(i-t)); v[i][s+i][t+i]=0.5f*sqrt((1+d)*(i+abs(s)-1)*(i+abs(s))/(float)(i+t)/(i-t))*(1.0f-2.0f*d); w[i][s+i][t+i]=-0.5f*sqrt((i-abs(s)-1)*(i-abs(s))/(float)(i+t)/(i-t))*(1.0f-d); } else { float d=(s==0?1.0f:0.0f); u[i][s+i][t+i]=sqrt((i+s)*(i-s)/(float)(2.0f*i)/(2.0f*i-1.0f)); v[i][s+i][t+i]=0.5f*sqrt((1+d)*(i+abs(s)-1)*(i+abs(s))/(float)(2.0f*i)/(2.0f*i-1.0f))*(1.0f-2.0f*d); w[i][s+i][t+i]=-0.5f*sqrt((i-abs(s)-1)*(i-abs(s))/(float)(2.0f*i)/(2.0f*i-1.0f))*(1.0f-d); } } last_largest_order=order; } for (int i=2; i<order; i++) { for (int s=-i+1; s<=i-1; s++) for (int t=-i; t<=i; t++) for (int r=-1; r<=1; r++) { if (abs(t)<i) P[i][r+1][s+i][t+i]=R[r+1][1]*M[i-1][s+i-1][t+i-1]; if (t==i) P[i][r+1][s+i][t+i]=R[r+1][2]*M[i-1][s+i-1][i*2-2]-R[r+1][0]*M[i-1][s+i-1][0]; if (t==-i) P[i][r+1][s+i][t+i]=R[r+1][2]*M[i-1][s+i-1][0]+R[r+1][0]*M[i-1][s+i-1][i*2-2]; } for (int t=-i; t<=i; t++) { for (int s=-i+1; s<=i-1; s++) U[i][s+i][t+i]=P[i][1][s+i][t+i]; for (int s=-i; s<=i; s++) { if (s==0) V[i][s+i][t+i]=P[i][2][1+i][t+i]+P[i][0][-1+i][t+i]; if (s>0) { float d=(s==1?1.0f:0.0f); V[i][s+i][t+i]=P[i][2][s-1+i][t+i]*sqrt(1.0f+d)-P[i][0][-s+1+i][t+i]*(1.0f-d); } if (s<0) { float d=(s==-1?1.0f:0.0f); V[i][s+i][t+i]=P[i][2][s+1+i][t+i]*(1.0f-d)+P[i][0][-s-1+i][t+i]*sqrt(1.0f+d); } } for (int s=-i+2; s<=i-2; s++) { if (s>0) W[i][s+i][t+i]=P[i][2][s+1+i][t+i]+P[i][0][-s-1+i][t+i]; if (s<0) W[i][s+i][t+i]=P[i][2][s-1+i][t+i]-P[i][0][-s+1+i][t+i]; } } for (int s=0; s<=i*2; s++) for (int t=0; t<=i*2; t++) M[i][s][t]=u[i][s][t]*U[i][s][t]+v[i][s][t]*V[i][s][t]+w[i][s][t]*W[i][s][t]; } memset(ret,0,sizeof(float)*order*order*order*order); for (int i=0; i<order; i++) for (int j=0; j<=i*2; j++) for (int k=0; k<=i*2; k++) ret[(i*i+j)*order*order+i*i+k]=M[i][j][k]; T newv[N*N]; memset(newv,0,sizeof(T)*N*N); for (int i=0; i<N*N; i++) for (int j=0; j<N*N; j++) newv[i]+=this->v[j]*ret[j*N*N+i]; memcpy(this->v,newv,sizeof(T)*N*N); } void Rotate_ZXZXZ(const float *rot) { printf("Rotate_ZXZXZ() must be specified to use!\n"); } void MultRotateMat(const float *mat) //time complexity 4/3*(order_)^3-(order_)/3 { SHCoeff<N,T> ret; float *t=ret.v; for (int i=0; i<order_; i++) for (int j=0; j<=2*i; j++,mat+=order_*order_,t++) for (int k=i*i; k<(i+1)*(i+1); k++) *t+=mat[k]*v[k]; *this=ret; } void MultRotateMatAtRightSide(const float *mat) { SHCoeff<N,T> ret; float *t=ret.v; for (int i=0; i<order_; i++) for (int j=0; j<=2*i; j++,mat++,t++) for (int k=i*i; k<(i+1)*(i+1); k++) *t+=mat[k*order_*order_]*v[k]; } }; template<> void SHCoeff<4,float>::TripleProduct(const SHCoeff<4,float> &coef) { SHCoeff<4,float> ret; float *c=ret.v; memset(c,0,sizeof(float)*16); const float *a=v,*b=coef.v; c[6]+=0.090109f*a[5]*b[5]; c[8]+=-0.058340f*(a[3]*b[13]+a[13]*b[3]); c[0]+=0.281264f*a[9]*b[9]; c[7]+=0.059470f*(a[12]*b[13]+a[13]*b[12]); c[5]+=0.059471f*(a[11]*b[12]+a[12]*b[11]); c[3]+=-0.058340f*(a[8]*b[13]+a[13]*b[8]); c[13]+=-0.058340f*(a[3]*b[8]+a[8]*b[3]); c[11]+=0.058369f*(a[1]*b[8]+a[8]*b[1]); c[1]+=0.058369f*(a[8]*b[11]+a[11]*b[8]); c[4]+=-0.058452f*(a[3]*b[11]+a[11]*b[3]); c[12]+=0.059470f*(a[7]*b[13]+a[13]*b[7]); c[6]+=0.090120f*a[7]*b[7]; c[8]+=0.058369f*(a[1]*b[11]+a[11]*b[1]); c[0]+=0.281341f*a[8]*b[8]; c[7]+=0.090120f*(a[6]*b[7]+a[7]*b[6]); c[5]+=0.090109f*(a[5]*b[6]+a[6]*b[5]); c[3]+=-0.058452f*(a[4]*b[11]+a[11]*b[4]); c[13]+=-0.058452f*(a[1]*b[4]+a[4]*b[1]); c[11]+=-0.058452f*(a[3]*b[4]+a[4]*b[3]); c[1]+=-0.058452f*(a[4]*b[13]+a[13]*b[4]); c[4]+=-0.058452f*(a[1]*b[13]+a[13]*b[1]); c[10]+=0.115150f*(a[5]*b[13]+a[13]*b[5]); c[6]+=0.126182f*a[11]*b[11]; c[8]+=-0.094025f*(a[9]*b[11]+a[11]*b[9]); c[0]+=0.281361f*a[15]*b[15]; c[7]+=0.115150f*(a[10]*b[11]+a[11]*b[10]); c[5]+=0.115150f*(a[10]*b[13]+a[13]*b[10]); c[3]+=-0.126223f*(a[3]*b[6]+a[6]*b[3]); c[13]+=0.059470f*(a[7]*b[12]+a[12]*b[7]); c[11]+=0.059471f*(a[5]*b[12]+a[12]*b[5]); c[1]+=-0.126236f*(a[1]*b[6]+a[6]*b[1]); c[4]+=-0.094033f*(a[9]*b[13]+a[13]*b[9]); c[14]+=0.115169f*(a[7]*b[13]+a[13]*b[7]); c[6]+=-0.126223f*a[3]*b[3]; c[8]+=-0.094056f*(a[13]*b[15]+a[15]*b[13]); c[0]+=0.281660f*a[3]*b[3]; c[7]+=0.115169f*(a[13]*b[14]+a[14]*b[13]); c[5]+=-0.115175f*(a[11]*b[14]+a[14]*b[11]); c[3]+=-0.142912f*(a[7]*b[12]+a[12]*b[7]); c[13]+=-0.094033f*(a[4]*b[9]+a[9]*b[4]); c[11]+=-0.094025f*(a[8]*b[9]+a[9]*b[8]); c[1]+=-0.143046f*(a[5]*b[12]+a[12]*b[5]); c[4]+=0.094033f*(a[11]*b[15]+a[15]*b[11]); c[2]+=0.184449f*(a[8]*b[14]+a[14]*b[8]); c[6]+=-0.126236f*a[1]*b[1]; c[8]+=-0.145674f*a[11]*b[11]; c[0]+=0.281727f*a[14]*b[14]; c[7]+=-0.142912f*(a[3]*b[12]+a[12]*b[3]); c[5]+=-0.143046f*(a[1]*b[12]+a[12]*b[1]); c[3]+=0.184557f*(a[5]*b[10]+a[10]*b[5]); c[13]+=-0.094056f*(a[8]*b[15]+a[15]*b[8]); c[11]+=0.094033f*(a[4]*b[15]+a[15]*b[4]); c[1]+=0.184557f*(a[7]*b[10]+a[10]*b[7]); c[4]+=0.145561f*(a[11]*b[13]+a[13]*b[11]); c[12]+=0.059471f*(a[5]*b[11]+a[11]*b[5]); c[6]+=0.126282f*a[13]*b[13]; c[8]+=0.145785f*a[13]*b[13]; c[0]+=0.281767f*a[1]*b[1]; c[7]+=0.148543f*(a[14]*b[15]+a[15]*b[14]); c[5]+=0.148600f*(a[9]*b[14]+a[14]*b[9]); c[9]+=-0.094025f*(a[8]*b[11]+a[11]*b[8]); c[15]+=0.094033f*(a[4]*b[11]+a[11]*b[4]); c[10]+=0.115150f*(a[7]*b[11]+a[11]*b[7]); c[11]+=0.115150f*(a[7]*b[10]+a[10]*b[7]); c[13]+=0.115150f*(a[5]*b[10]+a[10]*b[5]); c[14]+=-0.115175f*(a[5]*b[11]+a[11]*b[5]); c[6]+=0.168126f*a[12]*b[12]; c[8]+=-0.156112f*a[5]*b[5]; c[0]+=0.281884f*a[12]*b[12]; c[7]+=0.148683f*(a[9]*b[10]+a[10]*b[9]); c[5]+=-0.148673f*(a[10]*b[15]+a[15]*b[10]); c[4]+=0.155967f*(a[5]*b[7]+a[7]*b[5]); c[2]+=0.184558f*(a[4]*b[10]+a[10]*b[4]); c[1]+=-0.184781f*(a[5]*b[14]+a[14]*b[5]); c[3]+=0.184955f*(a[7]*b[14]+a[14]*b[7]); c[9]+=-0.094033f*(a[4]*b[13]+a[13]*b[4]); c[15]+=-0.094056f*(a[8]*b[13]+a[13]*b[8]); c[6]+=0.180199f*a[6]*b[6]; c[8]+=0.156254f*a[7]*b[7]; c[0]+=0.281894f*a[10]*b[10]; c[13]+=0.115169f*(a[7]*b[14]+a[14]*b[7]); c[11]+=-0.115175f*(a[5]*b[14]+a[14]*b[5]); c[12]+=-0.142912f*(a[3]*b[7]+a[7]*b[3]); c[14]+=0.148543f*(a[7]*b[15]+a[15]*b[7]); c[10]+=-0.148673f*(a[5]*b[15]+a[15]*b[5]); c[5]+=0.155967f*(a[4]*b[7]+a[7]*b[4]); c[7]+=0.155967f*(a[4]*b[5]+a[5]*b[4]); c[4]+=-0.180333f*(a[4]*b[6]+a[6]*b[4]); c[6]+=-0.180333f*a[4]*b[4]; c[8]+=-0.180343f*(a[6]*b[8]+a[8]*b[6]); c[0]+=0.281897f*a[4]*b[4]; c[3]+=0.202190f*(a[6]*b[13]+a[13]*b[6]); c[1]+=0.202243f*(a[6]*b[11]+a[11]*b[6]); c[2]+=0.218414f*(a[3]*b[7]+a[7]*b[3]); c[11]+=0.126182f*(a[6]*b[11]+a[11]*b[6]); c[13]+=0.126282f*(a[6]*b[13]+a[13]*b[6]); c[12]+=-0.143046f*(a[1]*b[5]+a[5]*b[1]); c[15]+=0.148543f*(a[7]*b[14]+a[14]*b[7]); c[14]+=0.148600f*(a[5]*b[9]+a[9]*b[5]); c[6]+=-0.180343f*a[8]*b[8]; c[8]+=0.184449f*(a[2]*b[14]+a[14]*b[2]); c[0]+=0.281956f*a[13]*b[13]; c[9]+=0.148600f*(a[5]*b[14]+a[14]*b[5]); c[10]+=0.148683f*(a[7]*b[9]+a[9]*b[7]); c[5]+=-0.156112f*(a[5]*b[8]+a[8]*b[5]); c[7]+=0.156254f*(a[7]*b[8]+a[8]*b[7]); c[4]+=0.184558f*(a[2]*b[10]+a[10]*b[2]); c[1]+=0.218374f*(a[3]*b[4]+a[4]*b[3]); c[3]+=0.218374f*(a[1]*b[4]+a[4]*b[1]); c[2]+=0.218461f*(a[1]*b[5]+a[5]*b[1]); c[6]+=0.202190f*(a[3]*b[13]+a[13]*b[3]); c[8]+=-0.187900f*(a[12]*b[14]+a[14]*b[12]); c[0]+=0.281966f*a[6]*b[6]; c[11]+=0.145561f*(a[4]*b[13]+a[13]*b[4]); c[13]+=0.145561f*(a[4]*b[11]+a[11]*b[4]); c[15]+=-0.148673f*(a[5]*b[10]+a[10]*b[5]); c[9]+=0.148683f*(a[7]*b[10]+a[10]*b[7]); c[12]+=0.168126f*(a[6]*b[12]+a[12]*b[6]); c[14]+=0.184449f*(a[2]*b[8]+a[8]*b[2]); c[5]+=0.184557f*(a[3]*b[10]+a[10]*b[3]); c[10]+=0.184557f*(a[3]*b[5]+a[5]*b[3]); c[6]+=0.202243f*(a[1]*b[11]+a[11]*b[1]); c[7]+=0.184558f*(a[1]*b[10]+a[10]*b[1]); c[4]+=-0.188019f*(a[10]*b[12]+a[12]*b[10]); c[3]+=0.218414f*(a[2]*b[7]+a[7]*b[2]); c[1]+=0.218461f*(a[2]*b[5]+a[5]*b[2]); c[8]+=-0.218732f*a[1]*b[1]; c[2]+=0.233572f*(a[5]*b[11]+a[11]*b[5]); c[0]+=0.281987f*a[7]*b[7]; c[11]+=-0.145674f*(a[8]*b[11]+a[11]*b[8]); c[13]+=0.145785f*(a[8]*b[13]+a[13]*b[8]); c[10]+=0.184558f*(a[1]*b[7]+a[7]*b[1]); c[6]+=-0.210482f*a[9]*b[9]; c[5]+=-0.184781f*(a[1]*b[14]+a[14]*b[1]); c[14]+=-0.184781f*(a[1]*b[5]+a[5]*b[1]); c[7]+=0.184955f*(a[3]*b[14]+a[14]*b[3]); c[12]+=-0.187900f*(a[8]*b[14]+a[14]*b[8]); c[9]+=-0.210482f*(a[6]*b[9]+a[9]*b[6]); c[15]+=-0.210522f*(a[6]*b[15]+a[15]*b[6]); c[4]+=0.218374f*(a[1]*b[3]+a[3]*b[1]); c[1]+=-0.218732f*(a[1]*b[8]+a[8]*b[1]); c[8]+=0.218821f*a[3]*b[3]; c[3]+=0.218821f*(a[3]*b[8]+a[8]*b[3]); c[6]+=-0.210522f*a[15]*b[15]; c[2]+=0.233583f*(a[7]*b[13]+a[13]*b[7]); c[0]+=0.282009f*a[5]*b[5]; c[10]+=0.184558f*(a[2]*b[4]+a[4]*b[2]); c[14]+=0.184955f*(a[3]*b[7]+a[7]*b[3]); c[12]+=-0.188019f*(a[4]*b[10]+a[10]*b[4]); c[13]+=0.202190f*(a[3]*b[6]+a[6]*b[3]); c[11]+=0.202243f*(a[1]*b[6]+a[6]*b[1]); c[7]+=0.218414f*(a[2]*b[3]+a[3]*b[2]); c[5]+=0.218461f*(a[1]*b[2]+a[2]*b[1]); c[15]+=0.226034f*(a[3]*b[8]+a[8]*b[3]); c[3]+=0.226034f*(a[8]*b[15]+a[15]*b[8]); c[8]+=0.226034f*(a[3]*b[15]+a[15]*b[3]); c[1]+=0.226108f*(a[8]*b[9]+a[9]*b[8]); c[9]+=0.226108f*(a[1]*b[8]+a[8]*b[1]); c[4]+=-0.226136f*(a[1]*b[15]+a[15]*b[1]); c[6]+=0.247669f*(a[2]*b[12]+a[12]*b[2]); c[2]+=0.247669f*(a[6]*b[12]+a[12]*b[6]); c[0]+=0.282026f*a[11]*b[11]; c[14]+=-0.187900f*(a[8]*b[12]+a[12]*b[8]); c[10]+=-0.188019f*(a[4]*b[12]+a[12]*b[4]); c[15]+=-0.226136f*(a[1]*b[4]+a[4]*b[1]); c[3]+=0.226185f*(a[4]*b[9]+a[9]*b[4]); c[8]+=0.226108f*(a[1]*b[9]+a[9]*b[1]); c[1]+=-0.226136f*(a[4]*b[15]+a[15]*b[4]); c[9]+=0.226185f*(a[3]*b[4]+a[4]*b[3]); c[4]+=0.226185f*(a[3]*b[9]+a[9]*b[3]); c[5]+=0.233572f*(a[2]*b[11]+a[11]*b[2]); c[11]+=0.233572f*(a[2]*b[5]+a[5]*b[2]); c[7]+=0.233583f*(a[2]*b[13]+a[13]*b[2]); c[13]+=0.233583f*(a[2]*b[7]+a[7]*b[2]); c[12]+=0.247669f*(a[2]*b[6]+a[6]*b[2]); c[2]+=0.252308f*(a[2]*b[6]+a[6]*b[2]); c[6]+=0.252308f*a[2]*b[2]; c[0]+=0.282056f*a[0]*b[0]; c[8]+=0.281341f*(a[0]*b[8]+a[8]*b[0]); c[9]+=0.281264f*(a[0]*b[9]+a[9]*b[0]); c[15]+=0.281361f*(a[0]*b[15]+a[15]*b[0]); c[3]+=0.281660f*(a[0]*b[3]+a[3]*b[0]); c[14]+=0.281727f*(a[0]*b[14]+a[14]*b[0]); c[1]+=0.281767f*(a[0]*b[1]+a[1]*b[0]); c[10]+=0.281894f*(a[0]*b[10]+a[10]*b[0]); c[12]+=0.281884f*(a[0]*b[12]+a[12]*b[0]); c[4]+=0.281897f*(a[0]*b[4]+a[4]*b[0]); c[13]+=0.281956f*(a[0]*b[13]+a[13]*b[0]); c[6]+=0.281966f*(a[0]*b[6]+a[6]*b[0]); c[7]+=0.281987f*(a[0]*b[7]+a[7]*b[0]); c[5]+=0.282009f*(a[0]*b[5]+a[5]*b[0]); c[11]+=0.282026f*(a[0]*b[11]+a[11]*b[0]); c[0]+=0.282066f*a[2]*b[2]; c[2]+=0.282066f*(a[0]*b[2]+a[2]*b[0]); *this=ret; } template<> void SHCoeff<4,float>::TripleProductMatrix(float *ret) { memset(ret,0,sizeof(float)*256); float *c=ret; float *a=v; c[101]+=0.090109f*a[5]; c[141]+=-0.058340f*a[3]; c[131]+=-0.058340f*a[13]; c[9]+=0.281264f*a[9]; c[125]+=0.059470f*a[12]; c[124]+=0.059470f*a[13]; c[92]+=0.059471f*a[11]; c[91]+=0.059471f*a[12]; c[61]+=-0.058340f*a[8]; c[56]+=-0.058340f*a[13]; c[216]+=-0.058340f*a[3]; c[211]+=-0.058340f*a[8]; c[184]+=0.058369f*a[1]; c[177]+=0.058369f*a[8]; c[27]+=0.058369f*a[8]; c[24]+=0.058369f*a[11]; c[75]+=-0.058452f*a[3]; c[67]+=-0.058452f*a[11]; c[205]+=0.059470f*a[7]; c[199]+=0.059470f*a[13]; c[103]+=0.090120f*a[7]; c[139]+=0.058369f*a[1]; c[129]+=0.058369f*a[11]; c[8]+=0.281341f*a[8]; c[119]+=0.090120f*a[6]; c[118]+=0.090120f*a[7]; c[86]+=0.090109f*a[5]; c[85]+=0.090109f*a[6]; c[59]+=-0.058452f*a[4]; c[52]+=-0.058452f*a[11]; c[212]+=-0.058452f*a[1]; c[209]+=-0.058452f*a[4]; c[180]+=-0.058452f*a[3]; c[179]+=-0.058452f*a[4]; c[29]+=-0.058452f*a[4]; c[20]+=-0.058452f*a[13]; c[77]+=-0.058452f*a[1]; c[65]+=-0.058452f*a[13]; c[173]+=0.115150f*a[5]; c[165]+=0.115150f*a[13]; c[107]+=0.126182f*a[11]; c[139]+=-0.094025f*a[9]; c[137]+=-0.094025f*a[11]; c[15]+=0.281361f*a[15]; c[123]+=0.115150f*a[10]; c[122]+=0.115150f*a[11]; c[93]+=0.115150f*a[10]; c[90]+=0.115150f*a[13]; c[54]+=-0.126223f*a[3]; c[51]+=-0.126223f*a[6]; c[220]+=0.059470f*a[7]; c[215]+=0.059470f*a[12]; c[188]+=0.059471f*a[5]; c[181]+=0.059471f*a[12]; c[22]+=-0.126236f*a[1]; c[17]+=-0.126236f*a[6]; c[77]+=-0.094033f*a[9]; c[73]+=-0.094033f*a[13]; c[237]+=0.115169f*a[7]; c[231]+=0.115169f*a[13]; c[99]+=-0.126223f*a[3]; c[143]+=-0.094056f*a[13]; c[141]+=-0.094056f*a[15]; c[3]+=0.281660f*a[3]; c[126]+=0.115169f*a[13]; c[125]+=0.115169f*a[14]; c[94]+=-0.115175f*a[11]; c[91]+=-0.115175f*a[14]; c[60]+=-0.142912f*a[7]; c[55]+=-0.142912f*a[12]; c[217]+=-0.094033f*a[4]; c[212]+=-0.094033f*a[9]; c[185]+=-0.094025f*a[8]; c[184]+=-0.094025f*a[9]; c[28]+=-0.143046f*a[5]; c[21]+=-0.143046f*a[12]; c[79]+=0.094033f*a[11]; c[75]+=0.094033f*a[15]; c[46]+=0.184449f*a[8]; c[40]+=0.184449f*a[14]; c[97]+=-0.126236f*a[1]; c[139]+=-0.145674f*a[11]; c[14]+=0.281727f*a[14]; c[124]+=-0.142912f*a[3]; c[115]+=-0.142912f*a[12]; c[92]+=-0.143046f*a[1]; c[81]+=-0.143046f*a[12]; c[58]+=0.184557f*a[5]; c[53]+=0.184557f*a[10]; c[223]+=-0.094056f*a[8]; c[216]+=-0.094056f*a[15]; c[191]+=0.094033f*a[4]; c[180]+=0.094033f*a[15]; c[26]+=0.184557f*a[7]; c[23]+=0.184557f*a[10]; c[77]+=0.145561f*a[11]; c[75]+=0.145561f*a[13]; c[203]+=0.059471f*a[5]; c[197]+=0.059471f*a[11]; c[109]+=0.126282f*a[13]; c[141]+=0.145785f*a[13]; c[1]+=0.281767f*a[1]; c[127]+=0.148543f*a[14]; c[126]+=0.148543f*a[15]; c[94]+=0.148600f*a[9]; c[89]+=0.148600f*a[14]; c[155]+=-0.094025f*a[8]; c[152]+=-0.094025f*a[11]; c[251]+=0.094033f*a[4]; c[244]+=0.094033f*a[11]; c[171]+=0.115150f*a[7]; c[167]+=0.115150f*a[11]; c[186]+=0.115150f*a[7]; c[183]+=0.115150f*a[10]; c[218]+=0.115150f*a[5]; c[213]+=0.115150f*a[10]; c[235]+=-0.115175f*a[5]; c[229]+=-0.115175f*a[11]; c[108]+=0.168126f*a[12]; c[133]+=-0.156112f*a[5]; c[12]+=0.281884f*a[12]; c[122]+=0.148683f*a[9]; c[121]+=0.148683f*a[10]; c[95]+=-0.148673f*a[10]; c[90]+=-0.148673f*a[15]; c[71]+=0.155967f*a[5]; c[69]+=0.155967f*a[7]; c[42]+=0.184558f*a[4]; c[36]+=0.184558f*a[10]; c[30]+=-0.184781f*a[5]; c[21]+=-0.184781f*a[14]; c[62]+=0.184955f*a[7]; c[55]+=0.184955f*a[14]; c[157]+=-0.094033f*a[4]; c[148]+=-0.094033f*a[13]; c[253]+=-0.094056f*a[8]; c[248]+=-0.094056f*a[13]; c[102]+=0.180199f*a[6]; c[135]+=0.156254f*a[7]; c[10]+=0.281894f*a[10]; c[222]+=0.115169f*a[7]; c[215]+=0.115169f*a[14]; c[190]+=-0.115175f*a[5]; c[181]+=-0.115175f*a[14]; c[199]+=-0.142912f*a[3]; c[195]+=-0.142912f*a[7]; c[239]+=0.148543f*a[7]; c[231]+=0.148543f*a[15]; c[175]+=-0.148673f*a[5]; c[165]+=-0.148673f*a[15]; c[87]+=0.155967f*a[4]; c[84]+=0.155967f*a[7]; c[117]+=0.155967f*a[4]; c[116]+=0.155967f*a[5]; c[70]+=-0.180333f*a[4]; c[68]+=-0.180333f*a[6]; c[100]+=-0.180333f*a[4]; c[136]+=-0.180343f*a[6]; c[134]+=-0.180343f*a[8]; c[4]+=0.281897f*a[4]; c[61]+=0.202190f*a[6]; c[54]+=0.202190f*a[13]; c[27]+=0.202243f*a[6]; c[22]+=0.202243f*a[11]; c[39]+=0.218414f*a[3]; c[35]+=0.218414f*a[7]; c[187]+=0.126182f*a[6]; c[182]+=0.126182f*a[11]; c[221]+=0.126282f*a[6]; c[214]+=0.126282f*a[13]; c[197]+=-0.143046f*a[1]; c[193]+=-0.143046f*a[5]; c[254]+=0.148543f*a[7]; c[247]+=0.148543f*a[14]; c[233]+=0.148600f*a[5]; c[229]+=0.148600f*a[9]; c[104]+=-0.180343f*a[8]; c[142]+=0.184449f*a[2]; c[130]+=0.184449f*a[14]; c[13]+=0.281956f*a[13]; c[158]+=0.148600f*a[5]; c[149]+=0.148600f*a[14]; c[169]+=0.148683f*a[7]; c[167]+=0.148683f*a[9]; c[88]+=-0.156112f*a[5]; c[85]+=-0.156112f*a[8]; c[120]+=0.156254f*a[7]; c[119]+=0.156254f*a[8]; c[74]+=0.184558f*a[2]; c[66]+=0.184558f*a[10]; c[20]+=0.218374f*a[3]; c[19]+=0.218374f*a[4]; c[52]+=0.218374f*a[1]; c[49]+=0.218374f*a[4]; c[37]+=0.218461f*a[1]; c[33]+=0.218461f*a[5]; c[109]+=0.202190f*a[3]; c[99]+=0.202190f*a[13]; c[142]+=-0.187900f*a[12]; c[140]+=-0.187900f*a[14]; c[6]+=0.281966f*a[6]; c[189]+=0.145561f*a[4]; c[180]+=0.145561f*a[13]; c[219]+=0.145561f*a[4]; c[212]+=0.145561f*a[11]; c[250]+=-0.148673f*a[5]; c[245]+=-0.148673f*a[10]; c[154]+=0.148683f*a[7]; c[151]+=0.148683f*a[10]; c[204]+=0.168126f*a[6]; c[198]+=0.168126f*a[12]; c[232]+=0.184449f*a[2]; c[226]+=0.184449f*a[8]; c[90]+=0.184557f*a[3]; c[83]+=0.184557f*a[10]; c[165]+=0.184557f*a[3]; c[163]+=0.184557f*a[5]; c[107]+=0.202243f*a[1]; c[97]+=0.202243f*a[11]; c[122]+=0.184558f*a[1]; c[113]+=0.184558f*a[10]; c[76]+=-0.188019f*a[10]; c[74]+=-0.188019f*a[12]; c[55]+=0.218414f*a[2]; c[50]+=0.218414f*a[7]; c[21]+=0.218461f*a[2]; c[18]+=0.218461f*a[5]; c[129]+=-0.218732f*a[1]; c[43]+=0.233572f*a[5]; c[37]+=0.233572f*a[11]; c[7]+=0.281987f*a[7]; c[187]+=-0.145674f*a[8]; c[184]+=-0.145674f*a[11]; c[221]+=0.145785f*a[8]; c[216]+=0.145785f*a[13]; c[167]+=0.184558f*a[1]; c[161]+=0.184558f*a[7]; c[105]+=-0.210482f*a[9]; c[94]+=-0.184781f*a[1]; c[81]+=-0.184781f*a[14]; c[229]+=-0.184781f*a[1]; c[225]+=-0.184781f*a[5]; c[126]+=0.184955f*a[3]; c[115]+=0.184955f*a[14]; c[206]+=-0.187900f*a[8]; c[200]+=-0.187900f*a[14]; c[153]+=-0.210482f*a[6]; c[150]+=-0.210482f*a[9]; c[255]+=-0.210522f*a[6]; c[246]+=-0.210522f*a[15]; c[67]+=0.218374f*a[1]; c[65]+=0.218374f*a[3]; c[24]+=-0.218732f*a[1]; c[17]+=-0.218732f*a[8]; c[131]+=0.218821f*a[3]; c[56]+=0.218821f*a[3]; c[51]+=0.218821f*a[8]; c[111]+=-0.210522f*a[15]; c[45]+=0.233583f*a[7]; c[39]+=0.233583f*a[13]; c[5]+=0.282009f*a[5]; c[164]+=0.184558f*a[2]; c[162]+=0.184558f*a[4]; c[231]+=0.184955f*a[3]; c[227]+=0.184955f*a[7]; c[202]+=-0.188019f*a[4]; c[196]+=-0.188019f*a[10]; c[214]+=0.202190f*a[3]; c[211]+=0.202190f*a[6]; c[182]+=0.202243f*a[1]; c[177]+=0.202243f*a[6]; c[115]+=0.218414f*a[2]; c[114]+=0.218414f*a[3]; c[82]+=0.218461f*a[1]; c[81]+=0.218461f*a[2]; c[248]+=0.226034f*a[3]; c[243]+=0.226034f*a[8]; c[63]+=0.226034f*a[8]; c[56]+=0.226034f*a[15]; c[143]+=0.226034f*a[3]; c[131]+=0.226034f*a[15]; c[25]+=0.226108f*a[8]; c[24]+=0.226108f*a[9]; c[152]+=0.226108f*a[1]; c[145]+=0.226108f*a[8]; c[79]+=-0.226136f*a[1]; c[65]+=-0.226136f*a[15]; c[108]+=0.247669f*a[2]; c[98]+=0.247669f*a[12]; c[44]+=0.247669f*a[6]; c[38]+=0.247669f*a[12]; c[11]+=0.282026f*a[11]; c[236]+=-0.187900f*a[8]; c[232]+=-0.187900f*a[12]; c[172]+=-0.188019f*a[4]; c[164]+=-0.188019f*a[12]; c[244]+=-0.226136f*a[1]; c[241]+=-0.226136f*a[4]; c[57]+=0.226185f*a[4]; c[52]+=0.226185f*a[9]; c[137]+=0.226108f*a[1]; c[129]+=0.226108f*a[9]; c[31]+=-0.226136f*a[4]; c[20]+=-0.226136f*a[15]; c[148]+=0.226185f*a[3]; c[147]+=0.226185f*a[4]; c[73]+=0.226185f*a[3]; c[67]+=0.226185f*a[9]; c[91]+=0.233572f*a[2]; c[82]+=0.233572f*a[11]; c[181]+=0.233572f*a[2]; c[178]+=0.233572f*a[5]; c[125]+=0.233583f*a[2]; c[114]+=0.233583f*a[13]; c[215]+=0.233583f*a[2]; c[210]+=0.233583f*a[7]; c[198]+=0.247669f*a[2]; c[194]+=0.247669f*a[6]; c[38]+=0.252308f*a[2]; c[34]+=0.252308f*a[6]; c[98]+=0.252308f*a[2]; c[0]+=0.282056f*a[0]; c[136]+=0.281341f*a[0]; c[128]+=0.281341f*a[8]; c[153]+=0.281264f*a[0]; c[144]+=0.281264f*a[9]; c[255]+=0.281361f*a[0]; c[240]+=0.281361f*a[15]; c[51]+=0.281660f*a[0]; c[48]+=0.281660f*a[3]; c[238]+=0.281727f*a[0]; c[224]+=0.281727f*a[14]; c[17]+=0.281767f*a[0]; c[16]+=0.281767f*a[1]; c[170]+=0.281894f*a[0]; c[160]+=0.281894f*a[10]; c[204]+=0.281884f*a[0]; c[192]+=0.281884f*a[12]; c[68]+=0.281897f*a[0]; c[64]+=0.281897f*a[4]; c[221]+=0.281956f*a[0]; c[208]+=0.281956f*a[13]; c[102]+=0.281966f*a[0]; c[96]+=0.281966f*a[6]; c[119]+=0.281987f*a[0]; c[112]+=0.281987f*a[7]; c[85]+=0.282009f*a[0]; c[80]+=0.282009f*a[5]; c[187]+=0.282026f*a[0]; c[176]+=0.282026f*a[11]; c[2]+=0.282066f*a[2]; c[34]+=0.282066f*a[0]; c[32]+=0.282066f*a[2]; } template<> void SHCoeff<4,float>::LoadFromFileA(FILE *fp) { for (int i=0; i<4*4; i++) fscanf(fp,"%f",v+i); } template<> void SHCoeff<4,Vector<3,float> >::LoadFromFileA(FILE *fp) { for (int i=0; i<4*4; i++) fscanf(fp,"%f %f %f",&(v[i][0]),&(v[i][1]),&(v[i][2])); } template<> void SHCoeff<4,float>::Rotate_ZXZXZ(const float *rot) { SHCoeff<4,float> tmp(*this); float cosine[4]; float sine[4]; #define CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ(tar,src,v_cos,v_sin)\ {\ cosine[1]=v_cos; \ sine[1]=v_sin; \ cosine[2]=2.0f*cosine[1]*cosine[1]-1.0f; \ sine[2]=2.0f*cosine[1]*sine[1]; \ cosine[3]=cosine[2]*cosine[1]+sine[2]*sine[1]; \ sine[3]=cosine[2]*sine[1]+sine[2]*cosine[1]; \ tar[0]=src[0]; \ tar[1]=cosine[1]*src[1]+sine[1]*src[3]; \ tar[2]=src[2]; \ tar[3]=cosine[1]*src[3]-sine[1]*src[1]; \ tar[4]=cosine[2]*src[4]+sine[2]*src[8]; \ tar[5]=cosine[1]*src[5]+sine[1]*src[7]; \ tar[6]=src[6]; \ tar[7]=cosine[1]*src[7]-sine[1]*src[5]; \ tar[8]=cosine[2]*src[8]-sine[2]*src[4]; \ tar[9]=cosine[3]*src[9]+sine[3]*src[15]; \ tar[10]=cosine[2]*src[10]+sine[2]*src[14]; \ tar[11]=cosine[1]*src[11]+sine[1]*src[13]; \ tar[12]=src[12]; \ tar[13]=cosine[1]*src[13]-sine[1]*src[11]; \ tar[14]=cosine[2]*src[14]-sine[2]*src[10]; \ tar[15]=cosine[3]*src[15]-sine[3]*src[9]; \ } //need for SSE2 /*_declspec(align(16))*/ float buf0[16]; /*_declspec(align(16))*/ float buf1[16]; if (1.0-rot[8]*rot[8]<1e-4 && rot[8]>0.0f) { CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ(buf0,tmp.v,rot[0],-rot[3]); memcpy(v,buf0,sizeof(float)*16); return; } float cosa,sina,cosb,sinb,cosc,sinc; cosb=rot[8]; sinb=sqrt(1-cosb*cosb); cosa=rot[2]/sinb; sina=rot[5]/sinb; cosc=-rot[6]/sinb; sinc=rot[7]/sinb; if (1.0-rot[8]*rot[8]<1e-4 && rot[8]<0.0f) { cosa=1.0f; sina=0.0f; cosc=-rot[0]; sinc=rot[3]; } CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ(buf0,tmp.v,cosc,sinc); buf1[0]=buf0[0]; buf1[1]=buf0[2]; buf1[2]=-buf0[1]; buf1[3]=buf0[3]; buf1[4]=buf0[7]; buf1[5]=-buf0[5]; buf1[6]=-0.5f*buf0[6]-0.86603f*buf0[8]; buf1[7]=-buf0[4]; buf1[8]=-0.86603f*buf0[6]+0.5f*buf0[8]; buf1[9]=-0.79057f*buf0[12]+0.61237f*buf0[14]; buf1[10]=-buf0[10]; buf1[11]=buf0[12]*-0.61237f+buf0[14]*-0.79057f; buf1[12]=buf0[9]*0.79057f+buf0[11]*0.61237f; buf1[13]=buf0[13]*-0.25f+buf0[15]*-0.96825f; buf1[14]=buf0[9]*-0.61237f+buf0[11]*0.79057f; buf1[15]=buf0[13]*-0.96825f+buf0[15]*0.25f; CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ(buf0,buf1,cosb,sinb); buf1[0]=buf0[0]; buf1[1]=-buf0[2]; buf1[2]=buf0[1]; buf1[3]=buf0[3]; buf1[4]=-buf0[7]; buf1[5]=-buf0[5]; buf1[6]=buf0[6]*-0.5f+buf0[8]*-0.86603f; buf1[7]=buf0[4]; buf1[8]=buf0[6]*-0.86603f+buf0[8]*0.5f; buf1[9]=buf0[12]*0.79057f+buf0[14]*-0.61237f; buf1[10]=-buf0[10]; buf1[11]=buf0[12]*0.61237f+buf0[14]*0.79057f; buf1[12]=buf0[9]*-0.79057f+buf0[11]*-0.61237f; buf1[13]=buf0[13]*-0.25f+buf0[15]*-0.96825f; buf1[14]=buf0[9]*0.61237f+buf0[11]*-0.79057f; buf1[15]=buf0[13]*-0.96825f+buf0[15]*0.25f; CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ(buf0,buf1,cosa,sina); memcpy(v,buf0,sizeof(float)*16); #undef CSHCOEF4F_ROTATE4_ZXZXZ_ROTATEZ } typedef SHCoeff<4,float> SHCoeff4f; typedef SHCoeff<4,Vector3f> SHCoeff4v3f; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/SH/SHCoeff.hpp
C++
gpl3
29,588
#include "GraphicsHelper.hpp" #include "GeometryHelper.hpp" #include "../Resource/Mesh/SimpleMesh.hpp" #include "../Resource/Shader/Shader.hpp" #include "OpenGLTools.hpp" #include "ColorDefine.hpp" namespace zzz{ void GraphicsHelper::DrawPlane(const Vector3d &point, const Vector3d &normal, double size) const { Vector3d one=normal.RandomPerpendicularUnitVec(), another=normal.Cross(one); one*=size/2;another*=size/2; glBegin(GL_QUADS); glVertex3dv((point-one-another).Data()); glVertex3dv((point-one+another).Data()); glVertex3dv((point+one+another).Data()); glVertex3dv((point+one-another).Data()); glEnd(); } void GraphicsHelper::DrawGrid(const zzz::Vector<3,double> &point, const zzz::Vector<3,double> &normal, double size, double interval) const { Vector3d one=normal.RandomPerpendicularUnitVec(), another=normal.Cross(one); int num=size/interval/2.0f; glBegin(GL_LINES); for (int i=-num; i<=num; i++) { glVertex3dv((point+one*interval*i+another*interval*num).Data()); glVertex3dv((point+one*interval*i-another*interval*num).Data()); glVertex3dv((point+another*interval*i+one*interval*num).Data()); glVertex3dv((point+another*interval*i-one*interval*num).Data()); } glEnd(); } const double X=0.525731112119133606; const double Z=0.850650808352039932; GLdouble vdata[12][3]={ {-X,0.0,Z},{X,0.0,Z},{-X,0.0,-Z},{X,0.0,-Z}, {0.0,Z,X},{0.0,Z,-X},{0.0,-Z,X},{0.0,-Z,-X}, {Z,X,0.0},{-Z,X,0.0},{Z,-X,0.0},{-Z,-X,0.0}, }; GLuint tindices[20][3]={ {1,4,0},{4,9,0},{4,5,9},{8,5,4,},{1,8,4}, {1,10,8},{10,3,8},{8,3,5},{3,2,5},{3,7,2}, {3,10,7},{10,6,7},{6,11,7},{6,0,11},{6,1,0}, {10,1,6},{11,0,9},{2,11,9},{5,2,9},{11,2,7}, }; void GraphicsHelper::DrawSphere(const double r, const int levels) const { SimpleMesh mesh; GeometryHelper::CreateSphere(mesh, levels); glPushMatrix(); glScaled(r,r,r); glBegin(GL_TRIANGLES); for(STLVector<Vector3i>::const_iterator vi = mesh.faces_.begin(); vi != mesh.faces_.end(); vi ++) { const Vector3i &f = *vi; glNormal3fv(mesh.vertices_[f[0]].Data()); glVertex3fv(mesh.vertices_[f[0]].Data()); glNormal3fv(mesh.vertices_[f[1]].Data()); glVertex3fv(mesh.vertices_[f[1]].Data()); glNormal3fv(mesh.vertices_[f[2]].Data()); glVertex3fv(mesh.vertices_[f[2]].Data()); } glEnd(); glPopMatrix(); } void GraphicsHelper::DrawAABB(const AABB<3,float> &aabb, const Colorf& color, float width) const { GLLineWidth::Set(width); Vector3f v[8]={\ aabb.Min(), Vector3f(aabb.Max()[0],aabb.Min()[1],aabb.Min()[2]),\ Vector3f(aabb.Max()[0],aabb.Min()[1],aabb.Max()[2]), Vector3f(aabb.Min()[0],aabb.Min()[1],aabb.Max()[2]),\ aabb.Max(), Vector3f(aabb.Min()[0],aabb.Max()[1],aabb.Max()[2]),\ Vector3f(aabb.Min()[0],aabb.Max()[1],aabb.Min()[2]), Vector3f(aabb.Max()[0],aabb.Max()[1],aabb.Min()[2])}; color.ApplyGL(); ZRM->Get<Shader*>("ColorShader")->Begin(); glBegin(GL_LINES); glVertex3fv(v[0].Data()); glVertex3fv(v[1].Data()); glVertex3fv(v[1].Data()); glVertex3fv(v[2].Data()); glVertex3fv(v[2].Data()); glVertex3fv(v[3].Data()); glVertex3fv(v[3].Data()); glVertex3fv(v[0].Data()); glVertex3fv(v[4].Data()); glVertex3fv(v[5].Data()); glVertex3fv(v[5].Data()); glVertex3fv(v[6].Data()); glVertex3fv(v[6].Data()); glVertex3fv(v[7].Data()); glVertex3fv(v[7].Data()); glVertex3fv(v[4].Data()); glVertex3fv(v[0].Data()); glVertex3fv(v[6].Data()); glVertex3fv(v[1].Data()); glVertex3fv(v[7].Data()); glVertex3fv(v[2].Data()); glVertex3fv(v[4].Data()); glVertex3fv(v[3].Data()); glVertex3fv(v[5].Data()); glEnd(); Shader::End(); GLLineWidth::Restore(); } void GraphicsHelper::DrawCoord(const Vector3d &point, double length/*=10*/, int linewidth/*=4*/) { GLLineWidth::Set(linewidth); ZRM->Get<Shader*>("ColorShader")->Begin(); glBegin(GL_LINES); ColorDefine::red.ApplyGL(); glVertex3dv(point.Data()); glVertex3d(point[0]+length, point[1], point[2]); ColorDefine::green.ApplyGL(); glVertex3dv(point.Data()); glVertex3d(point[0], point[1]+length, point[2]); ColorDefine::blue.ApplyGL(); glVertex3dv(point.Data()); glVertex3d(point[0], point[1], point[2]+length); glEnd(); Shader::End(); GLLineWidth::Restore(); } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/GraphicsHelper.cpp
C++
gpl3
4,458
#pragma once #include <Math/Vector3.hpp> #include <Math/Vector4.hpp> #include <Math/Vector.hpp> #include <Math/Matrix.hpp> namespace zzz{ template<typename T> class Rotation; template<typename T> class Quaternion : public Vector<4,T> { public: using Vector<4,T>::v; Quaternion():Vector<4,T>(0){} Quaternion(const VectorBase<3,T> &_axis, const T _angle):Vector<4,T>(_axis[0], _axis[1], _axis[2], 0) { XYZ().SafeNormalize(); XYZ() *= sin(_angle/2.0); W()=cos(_angle/2.0); } explicit Quaternion(const VectorBase<4,T> &_v):Vector<4,T>(_v){} Quaternion(const T x, const T y, const T z, const T w):Vector<4,T>(x,y,z,w){} explicit Quaternion(const MatrixBase<3,3,T> &rot) { float trace = rot(0,0) + rot(1,1) + rot(2,2); if(trace > 0) { float s = 0.5f / Sqrt<float>(trace+ 1.0f); v[3] = 0.25f / s; v[0] = (rot(2,1) - rot(1,2)) * s; v[1] = (rot(0,2) - rot(2,0)) * s; v[2] = (rot(1,0) - rot(0,1)) * s; } else if (rot(0,0) > rot(1,1) && rot(0,0) > rot(2,2)) { float s = 2.0f * Sqrt<float>(1.0f + rot(0,0) - rot(1,1) - rot(2,2)); v[3] = (rot(2,1) - rot(1,2)) / s; v[0] = 0.25f * s; v[1] = (rot(0,1) + rot(1,0)) / s; v[2] = (rot(0,2) + rot(2,0)) / s; } else if (rot(1,1) > rot(2,2)) { float s = 2.0f * Sqrt<float>(1.0f + rot(1,1) - rot(0,0) - rot(2,2)); v[3] = (rot(0,2) - rot(2,0)) / s; v[0] = (rot(0,1) + rot(1,0)) / s; v[1] = 0.25f * s; v[2] = (rot(1,2) + rot(2,1)) / s; } else { float s = 2.0f * Sqrt<float>(1.0f + rot(2,2) - rot(0,0) - rot(1,1)); v[3] = (rot(1,0) - rot(0,1)) / s; v[0] = (rot(0,2) + rot(2,0)) / s; v[1] = (rot(1,2) + rot(2,1)) / s; v[2] = 0.25f * s; } SafeNormalize(); } Quaternion(const Quaternion &other):Vector<4,T>(other.v){} using Vector<4,T>::operator=; using Vector<4,T>::operator[]; Vector<3,T> &XYZ() { return *(reinterpret_cast<Vector<3,T>*>(&v)); } const Vector<3,T> &XYZ() const { return *(reinterpret_cast<const Vector<3,T>*>(&v)); } T &W() { return v[3]; } const T &W() const { return v[3]; } inline Quaternion operator~() const { return Quaternion(-v[0], -v[1], -v[2], v[3]); } // (xyz + w) * u = Cross(xyz,u) + w * u - Dot(xyz,u) inline friend Quaternion<T> operator*(const Quaternion &q, const VectorBase<3,T> &u) { Vector<3,T> xyz(Cross(q.XYZ(), u) + q.W() * u); T w = -FastDot(q.XYZ(), u); return Quaternion(xyz[0], xyz[1], xyz[2], w); } // u * (xyz + w) = Cross(u, xyz) + u * w - Dot(xyz,u) inline friend Vector<3,T> operator*(const VectorBase<3,T> &u, const Quaternion &q) { Vector<3,T> xyz(Cross(u, q.XYZ()) + u * q.W()); T w = -FastDot(q.XYZ(), u); return Quaternion(xyz[0], xyz[1], xyz[2], w); } // (xyz1 + w1) * (xyz2 * w2) = Cross(xyz1, xyz2) + xyz1 * w2 + xyz2 * w1 + w1 * w2 - Dot(xyz1, xyz2) inline Quaternion operator*(const Quaternion &other) const { Vector<3,T> xyz(Cross(XYZ(), other.XYZ()) + XYZ()*other.W() + W()*other.XYZ()); T w = W()*other.W() - FastDot(XYZ(), other.XYZ()); return Quaternion(xyz[0], xyz[1], xyz[2], w); } void Identical() {v[0]=0; v[1]=0; v[2]=0; v[3]=1;} inline T Angle(){return 2*acos(W());} inline Vector<3,T> Axis(){return XYZ().Normalized();} inline VectorBase<3,T> RotateVector(const VectorBase<3,T> &u) const { Quaternion<T> q = (*this)*u*(~(*this)); return q.XYZ(); } inline VectorBase<3,T> RotateBackVector(const VectorBase<3,T> &u) const { Quaternion<T> q((~(*this))*u*(*this)); return q.XYZ(); } inline void SetAxisAngle(const VectorBase<3,T> &_axis, const T _angle) { XYZ()=_axis.Normalized()*sin(_angle/2.0); W()=cos(_angle/2.0); } // t is Distance(q, q1) / Distance(q1, q2) static Quaternion<T> Slerp(const Quaternion<T> &q1, const Quaternion<T> &q2, const T t) { // If q1 and q2 are colinear, there is no rotation between q1 and q2. T cos_val = FastDot(q1, q2); if (cos_val > 1.0 || cos_val < -1.0) return q2; T factor = 1.0; if (cos_val < 0.0) { factor = -1.0; cos_val = -cos_val; } T angle = acos(cos_val); if (angle < EPSILON) return q2; T sin_val = sin(angle); T inv_sin_val = 1.0 / sin_val; T coeff1 = sin((1.0-t)*angle)*inv_sin_val; T coeff2 = sin(t*angle)*inv_sin_val; Vector<4,T> v = static_cast<Vector<4,T> >(q1) * coeff1 + static_cast<Vector<4,T> >(q2) * (factor * coeff2); return Quaternion<T>(v); } void GetRoll(){return atan(2(v[0]*v[1]+v[2]*v[3])/(1-2*(v[1]*v[1]+v[2]*v[2]))); } void GetPitch(){return asin(2(v[0]*v[2]-v[3]*v[1])); } void GetYaw(){return atan(2(v[0]*v[3]+v[1]*v[2])/(1-2*(v[2]*v[2]+v[3]*v[3]))); } }; typedef Quaternion<zfloat32> Quaternionf32; typedef Quaternion<zfloat64> Quaternionf64; typedef Quaternion<float> Quaternionf; typedef Quaternion<double> Quaterniond; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/Quaternion.hpp
C++
gpl3
5,183
#pragma once namespace zzz{ template <typename T> class GraphicsElement3 { public: virtual T DistanceTo(const GraphicsElement3<T> &other) const=0; typedef enum {ELEMENT_POINT,ELEMENT_LINE,ELEMENT_PLANE,ELEMENT_BOX} ELEMENT_TYPE; GraphicsElement3(const ELEMENT_TYPE t):type(t){} const ELEMENT_TYPE type; }; template <typename T> class GraphicsElement2 { public: virtual T DistanceTo(const GraphicsElement2<T> &other) const=0; typedef enum {ELEMENT_POINT,ELEMENT_LINE,ELEMENT_BOX} ELEMENT_TYPE; GraphicsElement2(const ELEMENT_TYPE t):type(t){} const ELEMENT_TYPE type; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/GraphicsElement.hpp
C++
gpl3
611
#pragma once #include <zGraphicsConfig.hpp> #include "../Resource/Mesh/SimpleMesh.hpp" #include <Math/Vector3.hpp> #include <Math/Statistics.hpp> #include <Math/Matrix3x3.hpp> #include <Math/Array2.hpp> namespace zzz{ template<zuint PN> class Mesh; class GeometryHelper { public: template <typename T> static Vector<3,T> RotateVector3(const VectorBase<3,T> &v, const VectorBase<3,T> &normal, const T angle) { Vector<3,T> tmp=normal*v.Dot(normal); return (v-tmp)*cos(angle)+normal.Cross(v)*sin(angle)+tmp; } template <typename T, typename T1> static void Barycentric(const VectorBase<2,T> &p, const VectorBase<2,T> &t1, const VectorBase<2,T> &t2, const VectorBase<2,T> &t3, VectorBase<3,T1> &b) { VectorBase<2,T> v1=t1-t3; VectorBase<2,T> v2=t2-t3; T1 d=1.0/(v1[0]*v2[1]-v1[1]*v2[0]); VectorBase<2,T> x=p-t3; b[0]=(x[0]*v2[1]-x[1]*v2[0])*d; b[1]=(x[1]*v1[0]-x[0]*v1[1])*d; b[2]=1.0-b[0]-b[1]; } template <int N, typename T> static T TriangleArea(const VectorBase<N,T> &t1, const VectorBase<N,T> &t2, const VectorBase<N,T> &t3) { T a=t1.DistTo(t2); T b=t2.DistTo(t3); T c=t3.DistTo(t1); T v=(T)((a+b+c)/2.0); return Sqrt<T>(v*(v-a)*(v-b)*(v-c)); } template <typename T> static T TriangleArea(const VectorBase<2,T> &t1, const VectorBase<2,T> &t2, const VectorBase<2,T> &t3) { return 0.5 * Abs(Cross(t2 - t1, t3 - t1)); } template <typename T> static T TriangleArea(const VectorBase<3,T> &t1, const VectorBase<3,T> &t2, const VectorBase<3,T> &t3) { return 0.5 * Cross(t2 - t1, t3 - t1).Len(); } //return if p is on the left of l1->l2 template <typename T> static bool IsOnLeft(const VectorBase<2,T> &p, const VectorBase<2,T> &l1, const VectorBase<2,T> &l2) { T x = Cross(l2 - l1, p - l1); return x >= -TINY_EPSILON; } //return if p1 and p2 are on the same side of the line through l1 l2 template <typename T> static bool IsSameSide2D(const VectorBase<2,T> &p1, const VectorBase<2,T> &p2, const VectorBase<2,T> &l1, const VectorBase<2,T> &l2) { T x = ((p1[0]-l1[0]) * (l2[1]-l1[1]) - (l2[0]-l1[0]) * (p1[1]-l1[1])) * ((p2[0]-l1[0]) * (l2[1]-l1[1]) - (l2[0]-l1[0]) * (p2[1]-l1[1])); return x >= -TINY_EPSILON; } //return if p is inside triangle t1 t2 t3 template <typename T> static bool PointInTriangle2D(const Vector<2,T> &t1, const Vector<2,T> &t2, const Vector<2,T> &t3, const Vector<2,T> &p) { if (EPSILON < t1[0]-p[0] && EPSILON < t2[0]-p[0] && EPSILON < t3[0]-p[0]) return false; if (p[0]-t1[0] > EPSILON && p[0]-t2[0] > EPSILON && p[0]-t3[0] > EPSILON) return false; if (EPSILON < t1[1]-p[1] && EPSILON < t2[1]-p[1] && EPSILON < t3[1]-p[1]) return false; if (p[1]-t1[1] > EPSILON && p[1]-t2[1] > EPSILON && p[1]-t3[1] > EPSILON) return false; return IsSameSide2D(p,t1,t2,t3) && IsSameSide2D(p,t2,t1,t3) && IsSameSide2D(p,t3,t1,t2); } template <typename T> static bool IsSameSide3D(const VectorBase<3,T> &p1, const VectorBase<3,T> &p2, const VectorBase<3,T> &l1, const VectorBase<3,T> &l2) { Vector<3,T> a(l2-l1),b(p1-l1),c(p2-l1); return FastDot(a.Cross(b),a.Cross(c)) > 0; } //return if p is inside triangle t1 t2 t3 template <typename T> static bool PointInTriangle3D(const VectorBase<3,T> &t1, const VectorBase<3,T> &t2, const VectorBase<3,T> &t3, const VectorBase<3,T> &p) { return IsSameSide3D(p,t1,t2,t3) && IsSameSide3D(p,t2,t1,t3) && IsSameSide3D(p,t3,t1,t2); } //Ray intersect Triangle template<typename T, typename T1> static bool RayInTriangle(const VectorBase<3,T> &t0, const VectorBase<3,T> &t1, const VectorBase<3,T> &t2,\ const VectorBase<3,T> &orig, const VectorBase<3,T> &dir, \ T1 &dist, Vector<3,T1> &bary) { Vector<3,T> tvec, pvec, qvec; /* find vectors for two edges sharing vert0 */ Vector<3,T> edge1=t1-t0; Vector<3,T> edge2=t2-t0; /* begin calculating determinant - also used to calculate U parameter */ Cross(dir,edge2,pvec); /* if determinant is near zero, ray lies in plane of triangle */ T det = FastDot(edge1, pvec); #ifdef CULL_BACK_FACE if (det < EPSILON) return false; /* calculate distance from vert0 to ray origin */ tvec = orig - t0; /* calculate U parameter and test bounds */ bary[0] = Dot(tvec, pvec); if (bary[0] < 0.0 || bary[0] > det) return false; /* prepare to test V parameter */ Cross(tvec,edge1,qvec); /* calculate V parameter and test bounds */ bary[1] = Dot(dir, qvec); if (bary[1] < 0.0 || bary[0] + bary[1] > det) return false; /* calculate t, scale parameters, ray intersects triangle */ dist = Dot(edge2, qvec); T inv_det = 1.0 / det; dist *= inv_det; bary[0] *= inv_det; bary[1] *= inv_det; #else /* the non-culling branch */ if (det > -EPSILON && det < EPSILON) return false; T inv_det = 1.0 / det; /* calculate distance from vert0 to ray origin */ tvec=orig-t0; /* calculate U parameter and test bounds */ bary[0] = FastDot(tvec, pvec) * inv_det; if (bary[0] < -EPSILON || bary[0] > 1.0+EPSILON) return false; /* prepare to test V parameter */ Cross(tvec,edge1,qvec); /* calculate V parameter and test bounds */ bary[1] = FastDot(dir, qvec) * inv_det; if (bary[1] < -EPSILON || bary[0] + bary[1] > 1.0+EPSILON) return false; /* calculate t, ray intersects triangle */ dist = FastDot(edge2, qvec) * inv_det; #endif bary[2] = 1.0 - bary[0] - bary[1]; return true; } //decide if a polygon is a convex //just cross product each adjacent edges, convex will have the same sign //return 1:counter-closewise convex, -1:closewise convex, 0:not convex template <typename T> static int IsConvex(const vector<Vector<2,T> > &points) { T dir=Sign(Cross(points[1]-points[0],points.back()-points[0])); int psize=points.size(); for (int i=1; i<psize; i++) { T thisdir=Sign(Cross(points[(i+1)%psize]-points[i],points[(i+psize-1)%psize]-points[i])); if (thisdir!=dir) return 0; } return int(dir); } //decide vertices ordering for a polygon //it will detect if it is a convex first, if not a further algorithm for concave will be used //return 1:counter-closewise, -1:closewise template <typename T> static int PolygonOrdering(const vector<Vector<2,T> > &points) { int dir=IsConvex(points); if (dir!=0) return dir; return Sign(PolygonArea(points)); } //try every 3 adjecent point to see if they can form a triangle //input must be counter-clockwise template <typename T> static void PolygonToTriangles(const vector<Vector<2,T> > &points, vector<Vector3i> &triangles) { T dir=PolygonOrdering(points); triangles.clear(); vector<int> polygon; for (zuint i=0; i<points.size(); i++) polygon.push_back(i); while(polygon.size()>3) { int psize=polygon.size(); int best=-1; double maxcostheta=-2; for (int cur=0;cur<psize;cur++) { int t0=polygon[cur],t1=polygon[(cur+1)%psize],t2=polygon[(cur-1+psize)%psize]; //cannot be on the same line //this is the 3rd element of cross product result T nor2 = Cross(points[t1]-points[t0],points[t2]-points[t0]); if (nor2*dir<EPSILON) //on same line continue; //no other points should be inside bool no_point_inside=true; for (vector<int>::iterator li=polygon.begin();li!=polygon.end();li++) { if (*li==t0 || *li==t1 || *li==t2) continue; if (PointInTriangle2D(points[t0],points[t1],points[t2],points[*li])) { no_point_inside=false; break; } } if (!no_point_inside)//some point in side continue; //find mincostheta of three angles to evaluate if the triangle is "good" or not //the largest angle of a triangle should be small <-> the mincostheta should be large Vector<2,T> e1(points[t2]-points[t0]); Vector<2,T> e2(points[t1]-points[t0]); Vector<2,T> e3(points[t2]-points[t1]); e1.Normalize();e2.Normalize();e3.Normalize(); T costheta0 = FastDot(e1,e2); T costheta1 = -FastDot(e2,e3); T costheta2 = FastDot(e1,e3); T costheta=Min(costheta0,costheta1); if (costheta>costheta2) costheta=costheta2; if (costheta>maxcostheta) {best=cur;maxcostheta=costheta;} } //form triangle triangles.push_back(Vector3i(polygon[best],polygon[(best+1)%psize],polygon[(best-1+psize)%psize])); polygon.erase(polygon.begin()+best); } triangles.push_back(Vector3i(polygon[0],polygon[1],polygon[2])); } //project vertex to a 2D plane which is defined by PCA of these points template <int N, typename T> static Matrix<N,N,T> ProjectTo2D(const vector<Vector<N,T> > &t, vector<Vector<2,T> > &res) { //project to a plane Matrix<N,N,T> evector; Vector<N,T> evalue; PCA<N,T>(t,evector,evalue); res.clear(); res.reserve(t.size()); for (zuint i=0; i<t.size(); i++) { Vector<N,T> tmp=evector*t[i]; res.push_back(Vector<2,T>(tmp[0],tmp[1])); } return evector; } //polygon area //positive: polygon vertices are in counter-clockwise ordering //negative: polygon vertices are in clockwise ordering template <typename T> static T PolygonArea(const vector<Vector<2,T> > &t) { //sum the areas T area=0; for (zuint i=0; i<t.size(); i++) area+=Cross(t[i],t[(i+1)%t.size()]); area/=2; return area; } static const int PARALLEL = 0; static const int COINCIDENT = 1; static const int NOT_INTERSECTING = 2; static const int INTERSECTING = 3; template<typename T> static int LineSegmentIntersect(const Vector<2, T> &s0, const Vector<2, T> &e0, const Vector<2, T> &s1, const Vector<2, T> &e1, Vector<2, T> &intersection) { float denom = ((e1[1] - s1[1])*(e0[0] - s0[0])) - ((e1[0] - s1[0])*(e0[1] - s0[1])); float nume_a = ((e1[0] - s1[0])*(s0[1] - s1[1])) - ((e1[1] - s1[1])*(s0[0] - s1[0])); float nume_b = ((e0[0] - s0[0])*(s0[1] - s1[1])) - ((e0[1] - s0[1])*(s0[0] - s1[0])); if(Abs(denom) < EPS) { if(Abs(nume_a) < EPS && Abs(nume_b) < EPS) { return COINCIDENT; } return PARALLEL; } float ua = nume_a / denom; float ub = nume_b / denom; if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) { // Get the intersection point. intersection[0] = s0[0] + ua*(e0[0] - s0[0]); intersection[1] = s0[1] + ua*(e0[1] - s0[1]); return INTERSECTING; } return NOT_INTERSECTING; } static void CreateSphere(SimpleMesh &mesh, int levels=5); /// Calculate angle between 2 vectors. /// angle is from v1 to v2, counter closewise. /// Return a value from [0, 2PI). template<typename T> static double AngleFrom2Vectors(Vector<3,T> v1, Vector<3,T> v2) { v1.Normalize(); v2.Normalize(); double cosalpha = FastDot(v1,v2); Vector<3,T> cross = Cross(v1,v2); double sinalpha = cross.Len(); if (Within<double>(1.0-EPSILON5, sinalpha, 1.0+EPSILON5)) return 0; if (Within<double>(-1.0-EPSILON5, sinalpha, -1.0+EPSILON5)) return C_PI; Vector<3,T> aver = (v1+v2).Normalized(); Vector<3,T> crossaver = Cross(v1,aver); if (FastDot(cross, crossaver) > 0) // less then PI return SafeACos(cosalpha); else return C_2PI - SafeACos(cosalpha); } /// Calculate angle from sin and cos value of it. /// Return a value from [0, 2PI). /// sin and cos value will be clamp to [-1,1] static double AngleFromSinCos(double sinalpha, double cosalpha); /// Generate texture coordinate to a near-plane mesh static Matrix3x3f GenTexCoordFlat(Mesh<3> &mesh, zuint group, double pixel_per_one, zuint &u_size, zuint &v_size); /// Rasterize position to image according to texture coordinate static bool RasterizePosToImage(const Mesh<3> &mesh, zuint group, Array<2,Vector3f> &pos_img, Array2uc &pos_taken); }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/GeometryHelper.hpp
C++
gpl3
11,916
#pragma once #include <zGraphicsConfig.hpp> #include "Graphics.hpp" #include "Color.hpp" #include <Math/Vector2.hpp> #include "../Context/Context.hpp" #include <Utility/Thread.hpp> namespace zzz{ ZGRAPHICS_FUNC bool InitGLEW(); ZGRAPHICS_FUNC void CheckGLVersion(); ZGRAPHICS_FUNC bool CheckGLSL(); ZGRAPHICS_FUNC bool CheckSupport(const string &ext); ZGRAPHICS_FUNC int CheckGLError(char *file, int line); #ifndef ENABLE_CHECKGL #define CHECK_GL_ERROR() ; #else #define CHECK_GL_ERROR() zzz::CheckGLError(__FILE__, __LINE__); #endif // OpenGL convenience inline void glTranslatefv(const GLfloat *v) {glTranslatef(v[0],v[1],v[2]);} inline void glTranslatedv(const GLdouble *v) {glTranslated(v[0],v[1],v[2]);} inline bool GLExists(){return Context::current_context_!=NULL;} // Automatically call Restore when destroyed. template<typename T> class AutoRestore : public T { public: #define CONSTRUCTOR(type) AutoRestore(const type& x) {T::Set(x);} CONSTRUCTOR(int); CONSTRUCTOR(GLfloat); CONSTRUCTOR(GLuint); CONSTRUCTOR(Colorf); AutoRestore(GLenum face, GLenum mode) { T::Set(face, mode); } ~AutoRestore() { T::Restore(); } using T::Set; using T::Get; using T::Restore; }; // OpenGL status setters // How useful they are! class GLLineWidth { public: static float Set(GLfloat x) { old=Get(); glLineWidth(x); return old; } static void Restore() {Set(old);} static float Get() { GLfloat size; glGetFloatv(GL_LINE_WIDTH,&size); return size; } static GLfloat old; }; class GLPointSize { public: static float Set(GLfloat x) { old=Get(); glPointSize(x); return old; } static void Restore() {Set(old);} static float Get() { GLfloat size; glGetFloatv(GL_POINT_SIZE,&size); return size; } static GLfloat old; }; class GLPolygonMode { public: static Vector<2,GLint> Set(GLenum face, GLenum mode) { old=Get(); glPolygonMode(face,mode); return old; } static Vector<2,GLint> SetFill() { return Set(GL_FRONT_AND_BACK,GL_FILL); } static Vector<2,GLint> SetLine() { return Set(GL_FRONT_AND_BACK,GL_LINE); } static Vector<2,GLint> SetPoint() { return Set(GL_FRONT_AND_BACK,GL_POINT); } static void Restore() { glPolygonMode(GL_FRONT, old[0]); glPolygonMode(GL_BACK, old[1]); } static Vector<2,GLint> Get() { Vector<2,GLint> v; glGetIntegerv(GL_POLYGON_MODE,v.Data()); return v; } static Vector<2,GLint> old; }; class GLClearColor { public: // Parameter must not be reference, otherwise Restore will cause problem. // x will be the reference of old, but old will be changed first. static Color<GLfloat> Set(const Color<GLfloat> x) { old=Get(); glClearColor(x.r(),x.g(),x.b(),x.a()); return old; } static void Restore() {Set(old);} static Color<GLfloat> Get() { Color<GLfloat> c; glGetFloatv(GL_COLOR_CLEAR_VALUE,c.Data()); return c; } static Color<GLfloat> old; }; class GLClearDepth { public: static GLfloat Set(GLfloat x) { old=Get(); glClearDepth(x); return old; } static void Restore() {Set(old);} static GLfloat Get() { GLfloat c; glGetFloatv(GL_DEPTH_CLEAR_VALUE,&c); return c; } static GLfloat old; }; class GLBindTexture1D { public: static GLint Set(GLuint x) { old=Get(); glBindTexture(GL_TEXTURE_1D, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_TEXTURE_BINDING_1D,&c); return c; } static GLint old; }; class GLBindTexture2D { public: static GLint Set(GLuint x) { old=Get(); glBindTexture(GL_TEXTURE_2D, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_TEXTURE_BINDING_2D,&c); return c; } static GLint old; }; class GLBindTexture3D { public: static GLint Set(GLuint x) { old=Get(); glBindTexture(GL_TEXTURE_3D, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_TEXTURE_BINDING_3D,&c); return c; } static GLint old; }; class GLBindTextureCube { public: static GLint Set(GLuint x) { old=Get(); glBindTexture(GL_TEXTURE_CUBE_MAP, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP,&c); return c; } static GLint old; }; class GLBindRenderBuffer { public: static GLint Set(GLuint x) { old=Get(); glBindRenderbuffer(GL_RENDERBUFFER, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_RENDERBUFFER_BINDING,&c); return c; } static GLint old; }; class GLBindFrameBuffer { public: static GLint Set(GLuint x) { old=Get(); glBindFramebuffer(GL_FRAMEBUFFER, x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_FRAMEBUFFER_BINDING,&c); return c; } static GLint old; }; class GLDrawBuffer { public: static GLint Set(GLenum x) { old=Get(); glDrawBuffer(x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_DRAW_BUFFER,&c); return c; } static GLint old; }; class GLReadBuffer { public: static GLint Set(GLenum x) { old=Get(); glReadBuffer(x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_READ_BUFFER,&c); return c; } static GLint old; }; class GLActiveTexture { public: static GLint Set(GLenum x) { old=Get(); glActiveTexture(x); return old; } static void Restore() {Set(old);} static GLint Get() { GLint c; glGetIntegerv(GL_ACTIVE_TEXTURE,&c); return c; } static GLint old; }; class GLViewport { public: static Vector<4,GLint> Set(GLint x, GLint y, GLint w, GLint h) { old=Get(); glViewport(x,y,w,h); return old; } // Parameter must not be reference, otherwise Restore will cause problem. // x will be the reference of old, but old will be changed first. static Vector<4,GLint> Set(const Vector<4,GLint> v) { return Set(v[0],v[1],v[2],v[3]); } static void Restore(){Set(old);} static Vector<4,GLint> Get() { Vector<4,GLint> c; glGetIntegerv(GL_VIEWPORT,c.Data()); return c; } static Vector<4,GLint> old; }; class GLColorMask { public: static Vector<4,GLboolean> Set(GLboolean r, GLboolean g, GLboolean b, GLboolean a) { old=Get(); glColorMask(r,g,b,a); return old; } // Parameter must not be reference, otherwise Restore will cause problem. // x will be the reference of old, but old will be changed first. static Vector<4,GLboolean> Set(const Vector<4,GLboolean> v) { return Set(v[0],v[1],v[2],v[3]); } static void Restore(){Set(old);} static Vector<4,GLboolean> Get() { Vector<4,GLboolean> c; glGetBooleanv(GL_COLOR_WRITEMASK,c.Data()); return c; } static Vector<4,GLboolean> old; }; // Don't use it, until you fully understand how it process class GLRasterPos { public: static Vector<4,double> Set(double x, double y, double z=0, double w=1) { old=Get(); glRasterPos4d(x, y, z, w); Vector<4,double> test=Get(); // this is not the same as the one set return old; } // Parameter must not be reference, otherwise Restore will cause problem. // x will be the reference of old, but old will be changed first. static Vector<4,double> Set(const Vector<4,double> v) { return Set(v[0],v[1],v[2],v[3]); } static void Restore() { Set(old); } static Vector<4,double> Get() { Vector<4,double> c; glGetDoublev(GL_CURRENT_RASTER_POSITION,c.Data()); return c; } static Vector<4,double> old; }; class OpenGLProjector { public: OpenGLProjector(); void Refresh(); Vector3d UnProject(double winx, double winy, double winz=0.1); Vector3d Project(double objx, double objy, double objz); GLint viewport_[4]; GLdouble modelview_[16]; GLdouble projection_[16]; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/OpenGLTools.hpp
C++
gpl3
8,473
#pragma once #include <zGraphicsConfig.hpp> #include "Quaternion.hpp" #include "Rotation.hpp" #include "Translation.hpp" #include "Transformation.hpp" namespace zzz{ class ZGRAPHICS_CLASS ArcBall{ public: double win_w; /// the windows double win_h; /// the windows double old_x; /// stores the x coordinate where was pressed double old_y; /// stores the y coordinate where was pressed Quaternion<double> anchor_rot; /// Anchors the current roration Quaternion<double> rot; /// Stores the current rotation Quaternion<double> comb; ///in order to combine rotations, for instance, world rotation + object rotation //Quaternion<double> anchorLookAt; /// Anchors the camera's current rotation //Quaternion<double> currentLookAt; /// to compute the camera's rotation increment bool inv_rotate; /// flag to check if rotation is inverse or normal bool combine; /// flag to allow a rotation combination bool mode2d; GLTransformation<double> trans; public: ArcBall(); void SetWindowSize(double w, double h); void SetOldPos(double x, double y); void Rotate(double x, double y); void Reset(); Vector<3,double> GetAxis(); double GetAngle(); const GLTransformation<double> &GetGLTransform() const; const double* GetGLRotateMatrix() const; void SetInverse(bool val); void CombineRotation(const Quaternion<double> &q); void StopCombineRotation(); const Quaternion<double> GetQuaternion() const; void SetMode2D(bool val); bool GetMode2D(); void ApplyGL() const; private: /// anchors the current rotation void Bind(); void Normalize(double &x, double &y); void ProjectOntoSurface(Vector<3,double> &v); }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/ArcBall.hpp
C++
gpl3
1,720
#include "Camera.hpp" namespace zzz{ void Camera::SetPerspective(const int cw, const int ch, const double near, const double far, const double angle) { if (near != -1) zNear_=near; if (far != -1) zFar_=far; if (angle != -1) fovy_=angle; if (ch==0) return; width_=cw; height_=ch; aspect_=(double)cw/(double)ch; glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (!orthoMode_) gluPerspective(fovy_,aspect_,zNear_,zFar_); else { double r=orthoScale_; double t=r/aspect_; GLTransformationd trans; trans.Identical(); trans(0,0)=1.0/r; trans(1,1)=1.0/t; trans(2,2)=-2.0/100000; //(zFar_-zNear_); trans(2,3)=0; //-(zFar_+zNear_)/(zFar_-zNear_); trans.ApplyGL(); } glMatrixMode(GL_MODELVIEW); } void Camera::OffsetPosition(const double &x, const double &y, const double &z) { Position_[0]+=x; Position_[1]+=y; Position_[2]+=z; } void Camera::SetPosition(const double &x, const double &y, const double &z) { Position_[0]=x; Position_[1]=y; Position_[2]=z; } void Camera::OffsetPosition(const Vector<3,double> &offset) { Position_+=offset; } void Camera::Update() { Quaterniond q; // Make the Quaternions that will represent our rotations qPitch_.SetAxisAngle(Vector<3,double>(1,0,0),PitchDegrees_); qHeading_.SetAxisAngle(Vector<3,double>(0,1,0),YawDegrees_); // Combine the pitch and heading rotations and store the results in q q = qPitch_ * qHeading_; Transform_=GLTransformationd(Rotationd(q)); //original forward is 0,0,-1 DirectionVector_=q.RotateBackVector(Vector3d(0,0,-1)); } void Camera::SetPosition(const Vector<3,double> &pos) { Position_=pos; } // positive: forwards, negative: backwards void Camera::MoveForwards(double dist) { // Increment our position by the vector Position_ += DirectionVector_*dist; } // positive: leftwards, negative: rightwards void Camera::MoveLeftwards(double dist) { Quaternion<double> toHead(DirectionVector_.Cross(Vector3d(0,1,0)),PI/2); Vector3d newhead=toHead.RotateVector(DirectionVector_); Quaternion<double> toSide(newhead,PI/2); Vector3d LeftDir=toSide.RotateVector(DirectionVector_); // Increment our position by the vector Position_ += LeftDir*dist; } void Camera::MoveUpwards(double dist) { Quaternion<double> toHead(DirectionVector_.Cross(Vector3d(0,1,0)),PI/2); Vector3d newhead=toHead.RotateVector(DirectionVector_); // Increment our position by the vector Position_ += newhead*dist; } void Camera::ChangeYaw(double degrees) { if(Abs(degrees) < Abs(MaxYawRate_)) { // Our Heading is less than the max heading rate that we // defined so lets increment it but first we must check // to see if we are inverted so that our heading will not // become inverted. if(PitchDegrees_ > 90*C_D2R && PitchDegrees_ < 270*C_D2R || (PitchDegrees_ < -90*C_D2R && PitchDegrees_ > -270*C_D2R)) YawDegrees_ -= degrees; else YawDegrees_ += degrees; } else { // Our heading is greater than the max heading rate that // we defined so we can only increment our heading by the // maximum allowed value. if(degrees < 0) { // Check to see if we are upside down. if((PitchDegrees_ > 90*C_D2R && PitchDegrees_ < 270*C_D2R) || (PitchDegrees_ < -90*C_D2R && PitchDegrees_ > -270*C_D2R)) { // Ok we would normally decrement here but since we are upside // down then we need to increment our heading YawDegrees_ += MaxYawRate_; } else { // We are not upside down so decrement as usual YawDegrees_ -= MaxYawRate_; } } else { // Check to see if we are upside down. if(PitchDegrees_ > 90*C_D2R && PitchDegrees_ < 270*C_D2R || (PitchDegrees_ < -90*C_D2R && PitchDegrees_ > -270*C_D2R)) { // Ok we would normally increment here but since we are upside // down then we need to decrement our heading. YawDegrees_ -= MaxYawRate_; } else { // We are not upside down so increment as usual. YawDegrees_ += MaxYawRate_; } } } // We don't want our heading to run away from us either. Although it // really doesn't matter I prefer to have my heading degrees // within the range of -360.0f to 360.0f if(YawDegrees_ > 360*C_D2R) { YawDegrees_ -= 360*C_D2R; } else if(YawDegrees_ < -360*C_D2R) { YawDegrees_ += 360*C_D2R; } Update(); } void Camera::ChangePitch(double degrees) { if(Abs(degrees) < Abs(MaxPitchRate_)) { // Our pitch is less than the max pitch rate that we // defined so lets increment it. PitchDegrees_ += degrees; } else { // Our pitch is greater than the max pitch rate that // we defined so we can only increment our pitch by the // maximum allowed value. if(degrees < 0) { // We are pitching down so decrement PitchDegrees_ -= MaxPitchRate_; } else { // We are pitching up so increment PitchDegrees_ += MaxPitchRate_; } } // We don't want our pitch to run away from us. Although it // really doesn't matter I prefer to have my pitch degrees // within the range of -360.0f to 360.0f if(PitchDegrees_ > 360*C_D2R) { PitchDegrees_ -= 360*C_D2R; } else if(PitchDegrees_ < -360*C_D2R) { PitchDegrees_ += 360*C_D2R; } Update(); } void Camera::ApplyGL(void) const { // Let OpenGL set our new prespective on the world! Transform_.ApplyGL(); // Translate to our new position. glTranslated(-Position_[0],-Position_[1],-Position_[2]); } void Camera::Reset() { // Initalize all our member varibles. MaxPitchRate_ = 5; MaxYawRate_ = 5; YawDegrees_ = 0; PitchDegrees_ = 0; Position_.Set(0,0,0); Update(); } Camera::Camera() :zNear_(0.01), zFar_(1000), fovy_(60), orthoScale_(1.0), orthoMode_(false) { Reset(); } zzz::GLTransformationd Camera::GetGLTransformation() { GLTransformationd trans(Translationd(-Position_[0], -Position_[1], -Position_[2])); trans = trans * Transform_; return trans; } void Camera::LookAt(const Vector3d &from, const Vector3d &to, const Vector3d &up) { Vector3d f = to - from; f.Normalize(); Vector3d s = Cross(f, up.Normalized()); Vector3d u = Cross(s, f); Rotationd rot(Matrix3x3d(s,u,-f)); Transform_.Set(rot, Translationd(0,0,0)); // hopefully correct, roll must be zero double roll; rot.ToEulerAngles(PitchDegrees_, YawDegrees_, roll); PitchDegrees_*=C_R2D; YawDegrees_*=C_R2D; } void Camera::SetOrthoMode(bool mode) { orthoMode_=mode; SetPerspective(width_, height_); } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/Camera.cpp
C++
gpl3
6,786
#include "GeometryHelper.hpp" #include <Resource\Mesh\Mesh.hpp> namespace zzz{ void SphereSubDivide(SimpleMesh &mesh) { unsigned int origSize = mesh.faces_.size(); for (unsigned int i = 0 ; i < origSize ; ++i) { Vector3i &t = mesh.faces_[i]; const Vector3f &a = mesh.vertices_[t[0]], &b = mesh.vertices_[t[1]], &c = mesh.vertices_[t[2]]; Vector3f v1(a+b); Vector3f v2(a+c); Vector3f v3(b+c); v1.Normalize(); v2.Normalize(); v3.Normalize(); int ia=t[0], ib=t[1], ic=t[2], iv1, iv2, iv3; vector<Vector3f>::iterator vi1=find(mesh.vertices_.begin(),mesh.vertices_.end(),v1); if (vi1==mesh.vertices_.end()) { mesh.vertices_.push_back(v1); iv1=mesh.vertices_.size()-1; } else iv1=vi1-mesh.vertices_.begin(); vector<Vector3f>::iterator vi2=find(mesh.vertices_.begin(),mesh.vertices_.end(),v2); if (vi2==mesh.vertices_.end()) { mesh.vertices_.push_back(v2); iv2=mesh.vertices_.size()-1; } else iv2=vi2-mesh.vertices_.begin(); vector<Vector3f>::iterator vi3=find(mesh.vertices_.begin(),mesh.vertices_.end(),v3); if (vi3==mesh.vertices_.end()) { mesh.vertices_.push_back(v3); iv3=mesh.vertices_.size()-1; } else iv3=vi3-mesh.vertices_.begin(); t[0] = iv1; t[1] = iv3; t[2] = iv2; // overwrite the original mesh.faces_.push_back(Vector3i(ia, iv1, iv2)); mesh.faces_.push_back(Vector3i(ic, iv2, iv3)); mesh.faces_.push_back(Vector3i(ib, iv3, iv1)); } } void GeometryHelper::CreateSphere(SimpleMesh &mesh, int levels) { mesh.vertices_.clear(); mesh.faces_.clear(); // build an icosahedron float t = (1 + sqrt(5.0))/2.0; float s = sqrt(1 + t*t); // create the 12 vertices mesh.vertices_.push_back(Vector3f(t, 1, 0)/s); mesh.vertices_.push_back(Vector3f(-t, 1, 0)/s); mesh.vertices_.push_back(Vector3f(t, -1, 0)/s); mesh.vertices_.push_back(Vector3f(-t, -1, 0)/s); mesh.vertices_.push_back(Vector3f(1, 0, t)/s); mesh.vertices_.push_back(Vector3f(1, 0, -t)/s); mesh.vertices_.push_back(Vector3f(-1, 0, t)/s); mesh.vertices_.push_back(Vector3f(-1, 0, -t)/s); mesh.vertices_.push_back(Vector3f(0, t, 1)/s); mesh.vertices_.push_back(Vector3f(0, -t, 1)/s); mesh.vertices_.push_back(Vector3f(0, t, -1)/s); mesh.vertices_.push_back(Vector3f(0, -t, -1)/s); // create the 20 triangles_ mesh.faces_.push_back(Vector3i(0, 8, 4)); mesh.faces_.push_back(Vector3i(1, 10, 7)); mesh.faces_.push_back(Vector3i(2, 9, 11)); mesh.faces_.push_back(Vector3i(7, 3, 1)); mesh.faces_.push_back(Vector3i(0, 5, 10)); mesh.faces_.push_back(Vector3i(3, 9, 6)); mesh.faces_.push_back(Vector3i(3, 11, 9)); mesh.faces_.push_back(Vector3i(8, 6, 4)); mesh.faces_.push_back(Vector3i(2, 4, 9)); mesh.faces_.push_back(Vector3i(3, 7, 11)); mesh.faces_.push_back(Vector3i(4, 2, 0)); mesh.faces_.push_back(Vector3i(9, 4, 6)); mesh.faces_.push_back(Vector3i(2, 11, 5)); mesh.faces_.push_back(Vector3i(0, 10, 8)); mesh.faces_.push_back(Vector3i(5, 0, 2)); mesh.faces_.push_back(Vector3i(10, 5, 7)); mesh.faces_.push_back(Vector3i(1, 6, 8)); mesh.faces_.push_back(Vector3i(1, 8, 10)); mesh.faces_.push_back(Vector3i(6, 1, 3)); mesh.faces_.push_back(Vector3i(11, 7, 5)); for (int ctr = 0; ctr < levels; ctr++) SphereSubDivide(mesh); } double GeometryHelper::AngleFromSinCos(double sinalpha, double cosalpha) { sinalpha=Clamp<double>(-1,sinalpha,1); cosalpha=Clamp<double>(-1,cosalpha,1); if (sinalpha > 0) // phase 1, 2 return acos(cosalpha); return C_2PI - acos(cosalpha); } Matrix3x3f GeometryHelper::GenTexCoordFlat(Mesh<3> &mesh, zuint group, double pixel_per_one, zuint &u_size, zuint &v_size) { ZCHECK(group<mesh.groups_.size()); TriMesh::MeshGroup *g=mesh.groups_[group]; vector<int> used_points(mesh.pos_.size(), -1); for (zuint i=0; i<g->facep_.size(); i++) { used_points[g->facep_[i][0]]=1; used_points[g->facep_[i][1]]=1; used_points[g->facep_[i][2]]=1; } vector<Vector3f> selected; for (zuint i=0; i<used_points.size(); i++) { if (used_points[i]==1) selected.push_back(mesh.pos_[i]); } // project to 2d plane Matrix3x3f evector; Vector3f evalue; PCA<3,float>(selected, evector, evalue); for (zuint i=0; i<selected.size(); i++) selected[i]=evector * selected[i]; // calculate projected size AABB<3,float> aabb; aabb+=selected; if (aabb.Diff(2)/aabb.Diff(0)>0.01 || aabb.Diff(2)/aabb.Diff(1)>0.01) ZLOGV<<"The mesh is not very flat, "<<ZVAR(aabb.Diff())<<endl; // decide tex size u_size = aabb.Diff(0)*pixel_per_one; v_size = aabb.Diff(1)*pixel_per_one; float u_scale = float(u_size-1)/u_size; float v_scale = float(v_size-1)/v_size; float u_offset = 0.5f / u_size; float v_offset = 0.5f / v_size; for (zuint i=0, j=0; i<used_points.size(); i++) { if (used_points[i]==1) { used_points[i]=mesh.tex_.size(); const Vector3f &tex=selected[j++]; mesh.tex_.push_back(Vector3f( (tex[0]-aabb.Min(0)) / aabb.Diff(0) * u_scale + u_offset, (tex[1]-aabb.Min(1)) / aabb.Diff(1) * v_scale + v_offset, 0)); } } g->facet_.clear(); for (zuint i=0; i<g->facep_.size(); i++) { g->facet_.push_back(Vector3i(used_points[g->facep_[i][0]], used_points[g->facep_[i][1]], used_points[g->facep_[i][2]])); } mesh.SetFlag(MESH_TEX); g->SetFlag(MESH_TEX); return evector; } bool GeometryHelper::RasterizePosToImage(const Mesh<3> &mesh, zuint group, Array<2,Vector3f> &pos_img, Array2uc &pos_taken) { pos_taken.SetSize(pos_img.Size()); pos_taken.Zero(); TriMesh::MeshGroup *g = mesh.groups_[group]; int u_size = pos_img.Size(1); int v_size = pos_img.Size(0); ZCHECK(mesh.HasFlag(MESH_POS)); ZCHECK(mesh.HasFlag(MESH_TEX)); ZCHECK(g->HasFlag(MESH_POS)); ZCHECK(g->HasFlag(MESH_TEX)); for (zuint tri = 0; tri < g->facep_.size(); tri++) { const Vector2f tex_coord0(mesh.tex_[g->facet_[tri][0]]); const Vector2f tex_coord1(mesh.tex_[g->facet_[tri][1]]); const Vector2f tex_coord2(mesh.tex_[g->facet_[tri][2]]); const Vector3f &pos_coord0(mesh.pos_[g->facep_[tri][0]]); const Vector3f &pos_coord1(mesh.pos_[g->facep_[tri][1]]); const Vector3f &pos_coord2(mesh.pos_[g->facep_[tri][2]]); AABB<2, float> aabb; aabb += tex_coord0; aabb += tex_coord1; aabb += tex_coord2; int u_min = Clamp<int>(0, floor(aabb.Min(0) * (u_size-1)), u_size-1); int u_max = Clamp<int>(0, ceil(aabb.Max(0) * (u_size-1)), u_size-1); int v_min = Clamp<int>(0, floor(aabb.Min(1) * (v_size-1)), v_size-1); int v_max = Clamp<int>(0, ceil(aabb.Max(1) * (v_size-1)), v_size-1); for (int v = v_min; v <= v_max; v++) for (int u = u_min; u <= u_max; u++) { // Generate point Vector2f uv_coord(float(u-0.5f/u_size)/u_size, float(v-0.5f/v_size)/v_size); if (!PointInTriangle2D(tex_coord0, tex_coord1, tex_coord2, uv_coord)) continue; Vector3f bary_coord; Barycentric<float, float>(uv_coord, tex_coord0, tex_coord1, tex_coord2, bary_coord); pos_img(v, u) = pos_coord0 * bary_coord[0] + pos_coord1 * bary_coord[1] + pos_coord2 * bary_coord[2]; pos_taken(v, u) = 1; } } return true; } } // namespace zzz
zzz-engine
zzzEngine/zGraphics/zGraphics/Graphics/GeometryHelper.cpp
C++
gpl3
7,613
#pragma once #include <zGraphicsConfig.hpp> #include <common.hpp> #include "../Graphics/Graphics.hpp" #include "../Resource/Texture/Texture.hpp" namespace zzz { class ZGRAPHICS_CLASS FBO { public: FBO(); virtual ~FBO(); GLuint GetID(); void Bind(); void Unbind(); void AttachTexture(Texture &tex, GLenum attachment = GL_COLOR_ATTACHMENT0_EXT, int mipLevel = 0, int zSlice = 0); virtual void AttachTexture(GLenum texTarget, GLuint texId, GLenum attachment = GL_COLOR_ATTACHMENT0_EXT, int mipLevel = 0, int zSlice = 0); virtual void AttachTextures(int numTextures, GLenum texTarget[], GLuint texId[], GLenum attachment[] = NULL, int mipLevel[] = NULL, int zSlice[] = NULL); virtual void AttachRenderBuffer(GLuint buffId, GLenum attachment = GL_COLOR_ATTACHMENT0_EXT); virtual void AttachRenderBuffers(int numBuffers, GLuint buffId[], GLenum attachment[] = NULL); void Unattach(GLenum attachment); void UnattachAll(); bool CheckStatus(); bool IsValid(); /// Is attached type GL_RENDERBUFFER or GL_TEXTURE? GLenum GetAttachedType(GLenum attachment); /// What is the Id of Renderbuffer/texture currently /// attached to "attachement?" GLuint GetAttachedId(GLenum attachment); /// Which mipmap level is currently attached to "attachement?" GLint GetAttachedMipLevel(GLenum attachment); /// Which cube face is currently attached to "attachment?" GLint GetAttachedCubeFace(GLenum attachment); /// Which z-slice is currently attached to "attachment?" GLint GetAttachedZSlice(GLenum attachment); static int GetMaxColorAttachments(); static void Disable(); private: GLuint fbo_; }; }; // namespace zzz
zzz-engine
zzzEngine/zGraphics/zGraphics/FBO/FBO.hpp
C++
gpl3
2,188
#include "RenderBuffer.hpp" namespace zzz{ Renderbuffer::Renderbuffer(GLenum internalFormat) :buf_(0), width_(0), height_(0), internal_format_(internalFormat) { } Renderbuffer::Renderbuffer(GLenum internalFormat, int width, int height) :buf_(0) { Create(internalFormat, width, height); } Renderbuffer::~Renderbuffer() { if (IsValid()) glDeleteRenderbuffers(1, &buf_); } void Renderbuffer::Create(int width, int height) { Create(internal_format_, width, height); } void Renderbuffer::Create(GLenum internal_format, int width, int height) { if (width==width_ && height==height_ && internal_format_==internal_format) return; static const int maxSize = Renderbuffer::GetMaxSize(); if (width > maxSize || height > maxSize) { ZLOGV << "Cannot create RenderBuffer, too large size: " << width << "x" << height << ", max size is "<<maxSize<<endl; return; } // Guarded bind Bind(); // Allocate memory for renderBuffer glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internal_format, width, height); width_=width; height_=height; internal_format_=internal_format; Unbind(); } GLint Renderbuffer::GetMaxSize() { GLint maxAttach = 0; glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &maxAttach); return maxAttach; } } // namespace zzz
zzz-engine
zzzEngine/zGraphics/zGraphics/FBO/RenderBuffer.cpp
C++
gpl3
1,330
#pragma once #include <zGraphicsConfig.hpp> #include "FBO.hpp" #include <Image\Image.hpp> #include <Graphics\OpenGLTools.hpp> namespace zzz{ class ZGRAPHICS_CLASS Renderbuffer { public: Renderbuffer(GLenum internalFormat); Renderbuffer(GLenum internalFormat, int width, int height); ~Renderbuffer(); inline void Bind() { GLBindRenderBuffer::Set(GetID()); } inline void Unbind() { GLBindRenderBuffer::Restore(); } inline GLuint GetID() { if (!IsValid()) { glGenRenderbuffersEXT(1, &buf_); CHECK_GL_ERROR(); ZCHECK_NOT_ZERO(buf_); } return buf_; } void Create(int width, int height); void Create(GLenum internalFormat, int width, int height); bool IsValid() { bool valid=(glIsRenderbuffer(buf_)==GL_TRUE); CHECK_GL_ERROR() return valid; } template<typename T> bool ImageToRenderBuffer(const Image<T> &img); template<typename T> bool RenderBufferToImage(Image<T> &img); private: GLuint buf_; int width_,height_; int internal_format_; inline static GLint GetMaxSize(); }; // It is not correct, I don't which buffer should be set to readbuffer/drawbuffer template<typename T> bool Renderbuffer::ImageToRenderBuffer(const Image<T> &img) { GLvoid *data=(GLvoid *)img.Data(); Set(internalFormat, img.Cols(), img.Rows()); Bind(); GLDrawBuffer::Set(GL_RENDERBUFFER); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMatrixMode(GL_PROJECTION); glPushMatrix(); GLRasterPos::Set(0,0,0,1); glDrawPixels(width_, height_, img.Format_, img.Type_, data); GLRasterPos::Restore(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); GLDrawBuffer::Restore(); CHECK_GL_ERROR(); return true; } template<typename T> bool Renderbuffer::RenderBufferToImage(Image<T> &img) { if (!IsValid()) return false; Bind(); GLReadBuffer::Set(GL_RENDERBUFFER); img.SetSize(height_,width_); GLvoid *data=(GLvoid *)img.Data(); glReadPixels(0, 0, width_, height_, img.Format_, img.Type_, data); GLReadBuffer::Restore(); Unbind(); CHECK_GL_ERROR() return true; } }
zzz-engine
zzzEngine/zGraphics/zGraphics/FBO/RenderBuffer.hpp
C++
gpl3
2,177
#include "FBO.hpp" #include <Graphics\OpenGLTools.hpp> namespace zzz { FBO::FBO() :fbo_(0) { } FBO::~FBO() { glDeleteFramebuffers(1, &fbo_); } void FBO::Bind() { GLBindFrameBuffer::Set(GetID()); } void FBO::Unbind() { GLBindFrameBuffer::Restore(); } void FBO::Disable() { GLBindFrameBuffer::Set(0); } void FBO::AttachTexture(GLenum texTarget, GLuint texId, GLenum attachment, int mipLevel, int zSlice) { Bind(); CHECK_GL_ERROR(); switch(texTarget) { case GL_TEXTURE_1D: glFramebufferTexture1D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_1D, texId, mipLevel); CHECK_GL_ERROR(); break; case GL_TEXTURE_3D: glFramebufferTexture3D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_3D, texId, mipLevel, zSlice); CHECK_GL_ERROR(); break; case GL_TEXTURE_2D: glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, texId, mipLevel); CHECK_GL_ERROR(); break; default: // For GL_TEXTURE_CUBE_MAP_X glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, texTarget, texId, mipLevel); CHECK_GL_ERROR(); } Unbind(); CHECK_GL_ERROR(); } void FBO::AttachTexture(Texture &tex, GLenum attachment /*= GL_COLOR_ATTACHMENT0_EXT*/, int mipLevel /*= 0*/, int zSlice /*= 0 */) { AttachTexture(tex.tex_target_, tex.GetID(), attachment, mipLevel, zSlice); } void FBO::AttachTextures(int numTextures, GLenum texTarget[], GLuint texId[], GLenum attachment[], int mipLevel[], int zSlice[]) { for(int i = 0; i < numTextures; ++i) { AttachTexture(texTarget[i], texId[i], attachment ? attachment[i] : (GL_COLOR_ATTACHMENT0+ i), mipLevel ? mipLevel[i] : 0, zSlice ? zSlice[i] : 0); } } void FBO::AttachRenderBuffer(GLuint buffId, GLenum attachment) { Bind(); glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffId); Unbind(); } void FBO::AttachRenderBuffers(int numBuffers, GLuint buffId[], GLenum attachment[]) { for(int i = 0; i < numBuffers; ++i) { AttachRenderBuffer(buffId[i], attachment ? attachment[i] : (GL_COLOR_ATTACHMENT0+ i)); } } void FBO::Unattach(GLenum attachment) { Bind(); GLenum type = GetAttachedType(attachment); switch(type) { case GL_NONE: break; case GL_RENDERBUFFER_EXT: AttachRenderBuffer(0, attachment); break; case GL_TEXTURE: AttachTexture(GL_TEXTURE_2D, 0, attachment); break; default: cerr << "FramebufferObject::unbind_attachment ERROR: Unknown attached resource type\n"; } Unbind(); } void FBO::UnattachAll() { int numAttachments = GetMaxColorAttachments(); for(int i = 0; i < numAttachments; ++i) { Unattach(GL_COLOR_ATTACHMENT0_EXT + i); } } GLint FBO::GetMaxColorAttachments() { GLint maxAttach = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxAttach); return maxAttach; } bool FBO::CheckStatus() { Bind(); bool isOK = false; GLenum status; status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // Everything's OK isOK = true; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"; isOK = false; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; isOK = false; break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT\n"; isOK = false; break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT\n"; isOK = false; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n"; isOK = false; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n"; isOK = false; break; case GL_FRAMEBUFFER_UNSUPPORTED: ZLOGE << "CheckStatus() ERROR: GL_FRAMEBUFFER_UNSUPPORTED\n"; isOK = false; break; default: ZLOGE << "CheckStatus() ERROR: Unknown ERROR\n"; isOK = false; } Unbind(); return isOK; } /// Accessors GLenum FBO::GetAttachedType(GLenum attachment) { // Returns GL_RENDERBUFFER or GL_TEXTURE Bind(); GLint type = 0; glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER_EXT, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT, &type); Unbind(); return GLenum(type); } GLuint FBO::GetAttachedId(GLenum attachment) { Bind(); GLint id = 0; glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT, &id); Unbind(); return GLuint(id); } GLint FBO::GetAttachedMipLevel(GLenum attachment) { Bind(); GLint level = 0; glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT, &level); Unbind(); return level; } GLint FBO::GetAttachedCubeFace(GLenum attachment) { Bind(); GLint level = 0; glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT, &level); Unbind(); return level; } GLint FBO::GetAttachedZSlice(GLenum attachment) { Bind(); GLint slice = 0; glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT, &slice); Unbind(); return slice; } GLuint FBO::GetID() { if (!IsValid()) { glGenFramebuffers(1, &fbo_); CHECK_GL_ERROR(); ZCHECK_NOT_ZERO(fbo_); } return fbo_; } bool FBO::IsValid() { bool valid=(glIsFramebuffer(fbo_)==GL_TRUE); CHECK_GL_ERROR() return valid; } }; // namespace zzz
zzz-engine
zzzEngine/zGraphics/zGraphics/FBO/FBO.cpp
C++
gpl3
5,991
#pragma once #include <zGraphicsConfig.hpp> #include "Context.hpp" #ifdef ZZZ_CONTEXT_MFC #include <common.hpp> #include "../Renderer/Renderer.hpp" #include <Windows.h> namespace zzz{ class ZGRAPHICS_CLASS SingleViewContext : public Context { public: virtual ~SingleViewContext(); public: bool Initialize(HWND hWnd); void Redraw() { ::InvalidateRect(hWnd_,NULL,TRUE); } void SwapBuffer() { SwapBuffers(hDC_); } void MakeCurrent() { wglMakeCurrent(hDC_,hRC_); Context::MakeCurrent(); } void HideCursor() { ::ShowCursor(FALSE); } void ShowCursor() { ::ShowCursor(TRUE); } public: virtual void OnMouseMove(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnMouseMove(nFlags,x,y)) return; return renderer_->OnMouseMove(nFlags,x,y); } virtual void OnLButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnLButtonDown(nFlags,x,y)) return; return renderer_->OnLButtonDown(nFlags,x,y); } virtual void OnLButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnLButtonUp(nFlags,x,y)) return; return renderer_->OnLButtonUp(nFlags,x,y); } virtual void OnRButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnRButtonDown(nFlags,x,y)) return; return renderer_->OnRButtonDown(nFlags,x,y); } virtual void OnRButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnLButtonUp(nFlags,x,y)) return; return renderer_->OnRButtonUp(nFlags,x,y); } virtual void OnMButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnMButtonDown(nFlags,x,y)) return; return renderer_->OnMButtonDown(nFlags,x,y); } virtual void OnMButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && gui_->OnMButtonDown(nFlags,x,y)) return; return renderer_->OnMButtonUp(nFlags,x,y); } virtual void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y) { if (!own_mouse_ && gui_ && gui_->OnMouseWheel(nFlags,zDelta,x,y)) return; return renderer_->OnMouseWheel(nFlags,zDelta,x,y); } virtual void OnSize(unsigned int nType, int cx, int cy) { renderer_->OnSize(nType,cx,cy); if (gui_) gui_->OnSize(nType,cx,cy); width_=cx;height_=cy; } virtual void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { MFC2ZZZ(nChar,nFlags); if (!own_keyboard_ && gui_ && gui_->OnChar(nChar,nRepCnt,nFlags)) return; return renderer_->OnChar(nChar,nRepCnt,nFlags); } virtual void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { MFC2ZZZ(nChar,nFlags); if (!own_keyboard_ && gui_ && gui_->OnKeyDown(nChar,nRepCnt,nFlags)) return; return renderer_->OnKeyDown(nChar,nRepCnt,nFlags); } virtual void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { MFC2ZZZ(nChar,nFlags); if (!own_keyboard_ && gui_ && gui_->OnKeyUp(nChar,nRepCnt,nFlags)) return; return renderer_->OnKeyUp(nChar,nRepCnt,nFlags); } protected: HDC hDC_; HGLRC hRC_; bool GLinited_,GLEWinited_; GLint DefaultDrawBuffer_; HWND hWnd_; private: bool InitGL(); int InitMultisample(); bool SetupPixelFormat(int pf=0); }; //1 Define a renderer class //2 put renderer_.RenderScene() in OnDraw() //3 Put the following macro in the correct file #define PUT_IN_VIEW_H public:\ zzz::SingleViewContext zzzContext_; \ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); \ afx_msg void OnMouseMove(UINT nFlags, CPoint point); \ afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); \ afx_msg void OnMButtonDown(UINT nFlags, CPoint point); \ afx_msg void OnMButtonUp(UINT nFlags, CPoint point); \ afx_msg void OnLButtonDown(UINT nFlags, CPoint point); \ afx_msg void OnLButtonUp(UINT nFlags, CPoint point); \ afx_msg void OnRButtonDown(UINT nFlags, CPoint point); \ afx_msg void OnRButtonUp(UINT nFlags, CPoint point); \ afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); \ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); \ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); \ afx_msg void OnSize(UINT nType, int cx, int cy); \ afx_msg BOOL OnEraseBkgnd(CDC* pDC); \ afx_msg void OnPaint(); #define PUT_IN_VIEW_CPP_MESSAGE_MAP ON_WM_CREATE()\ ON_WM_MOUSEMOVE()\ ON_WM_MOUSEWHEEL()\ ON_WM_MBUTTONDOWN()\ ON_WM_MBUTTONUP()\ ON_WM_LBUTTONDOWN()\ ON_WM_LBUTTONUP()\ ON_WM_RBUTTONDOWN()\ ON_WM_RBUTTONUP()\ ON_WM_CHAR()\ ON_WM_KEYDOWN()\ ON_WM_KEYUP()\ ON_WM_SIZE()\ ON_WM_ERASEBKGND()\ ON_WM_PAINT() #define PUT_IN_VIEW_CPP(viewclass,varrenderer) \ int viewclass::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1) return -1;zzzContext_.SetRenderer(&varrenderer);zzzContext_.Initialize(GetSafeHwnd());return 0;}\ void viewclass::OnMouseMove(UINT nFlags, CPoint point){zzzContext_.OnMouseMove(nFlags,point.x,point.y);CView::OnMouseMove(nFlags, point);}\ BOOL viewclass::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt){zzzContext_.OnMouseWheel(nFlags,zDelta/120,pt.x,pt.y);return CView::OnMouseWheel(nFlags, zDelta, pt);}\ void viewclass::OnMButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnMButtonDown(nFlags,point.x,point.y);CView::OnMButtonDown(nFlags, point);}\ void viewclass::OnMButtonUp(UINT nFlags, CPoint point){zzzContext_.OnMButtonUp(nFlags,point.x,point.y);CView::OnMButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnLButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnLButtonDown(nFlags,point.x,point.y);CView::OnLButtonDown(nFlags, point);}\ void viewclass::OnLButtonUp(UINT nFlags, CPoint point){zzzContext_.OnLButtonUp(nFlags,point.x,point.y);CView::OnLButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnRButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnRButtonDown(nFlags,point.x,point.y);CView::OnRButtonDown(nFlags, point);}\ void viewclass::OnRButtonUp(UINT nFlags, CPoint point){zzzContext_.OnRButtonUp(nFlags,point.x,point.y);CView::OnRButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnChar(nChar,nRepCnt,nFlags);CView::OnChar(nChar, nRepCnt, nFlags);}\ void viewclass::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnKeyDown(nChar,nRepCnt,nFlags);CView::OnKeyDown(nChar, nRepCnt, nFlags);}\ void viewclass::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnKeyUp(nChar,nRepCnt,nFlags);CView::OnKeyUp(nChar, nRepCnt, nFlags);}\ void viewclass::OnSize(UINT nType, int cx, int cy){CView::OnSize(nType, cx, cy);zzzContext_.OnSize(nType,cx,cy);}\ BOOL viewclass::OnEraseBkgnd(CDC* pDC){return TRUE;}\ void viewclass::OnPaint(){CPaintDC dc(this);zzzContext_.RenderScene();OnDraw(&dc);} #define PUT_IN_VIEW_CPP_GUI(viewclass,varrenderer,vargui) \ int viewclass::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1) return -1;zzzContext_.SetRenderer(&varrenderer);zzzContext_.SetGraphicsGUI(&vargui);zzzContext_.Initialize(GetSafeHwnd());return 0;}\ void viewclass::OnMouseMove(UINT nFlags, CPoint point){zzzContext_.OnMouseMove(nFlags,point.x,point.y);CView::OnMouseMove(nFlags, point);}\ BOOL viewclass::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt){zzzContext_.OnMouseWheel(nFlags,zDelta/120,pt.x,pt.y);return CView::OnMouseWheel(nFlags, zDelta, pt);}\ void viewclass::OnMButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnMButtonDown(nFlags,point.x,point.y);CView::OnMButtonDown(nFlags, point);}\ void viewclass::OnMButtonUp(UINT nFlags, CPoint point){zzzContext_.OnMButtonUp(nFlags,point.x,point.y);CView::OnMButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnLButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnLButtonDown(nFlags,point.x,point.y);CView::OnLButtonDown(nFlags, point);}\ void viewclass::OnLButtonUp(UINT nFlags, CPoint point){zzzContext_.OnLButtonUp(nFlags,point.x,point.y);CView::OnLButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnRButtonDown(UINT nFlags, CPoint point){SetFocus();SetCapture();zzzContext_.OnRButtonDown(nFlags,point.x,point.y);CView::OnRButtonDown(nFlags, point);}\ void viewclass::OnRButtonUp(UINT nFlags, CPoint point){zzzContext_.OnRButtonUp(nFlags,point.x,point.y);CView::OnRButtonUp(nFlags, point);ReleaseCapture();}\ void viewclass::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnChar(nChar,nRepCnt,nFlags);CView::OnChar(nChar, nRepCnt, nFlags);}\ void viewclass::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnKeyDown(nChar,nRepCnt,nFlags);CView::OnKeyDown(nChar, nRepCnt, nFlags);}\ void viewclass::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags){zzzContext_.OnKeyUp(nChar,nRepCnt,nFlags);CView::OnKeyUp(nChar, nRepCnt, nFlags);}\ void viewclass::OnSize(UINT nType, int cx, int cy){CView::OnSize(nType, cx, cy);zzzContext_.OnSize(nType,cx,cy);}\ BOOL viewclass::OnEraseBkgnd(CDC* pDC){return TRUE;}\ void viewclass::OnPaint(){CPaintDC dc(this);zzzContext_.RenderScene();OnDraw(&dc);} } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/SingleViewContext.hpp
C++
gpl3
9,762
#pragma once #include <Utility/Tools.hpp> namespace zzz { //for OnMouse... #define ZZZFLAG_LMOUSE (0x00000001) #define ZZZFLAG_RMOUSE (0x00000002) #define ZZZFLAG_MMOUSE (0x00000004) #define ZZZFLAG_X1MOUSE (0x00000008) #define ZZZFLAG_X2MOUSE (0x00000010) #define ZZZFLAG_SHIFT (0x00010000) #define ZZZFLAG_CTRL (0x00020000) #define ZZZFLAG_ALT (0x00040000) #define ZZZFLAG_META (0x00080000) #define ZZZFLAG_LSHIFT (0x00100000) #define ZZZFLAG_LCTRL (0x00200000) #define ZZZFLAG_LALT (0x00400000) #define ZZZFLAG_LMETA (0x00800000) #define ZZZFLAG_RSHIFT (0x01000000) #define ZZZFLAG_RCTRL (0x02000000) #define ZZZFLAG_RALT (0x04000000) #define ZZZFLAG_RMETA (0x08000000) inline void CompleteZZZFlags(unsigned int &flag) { if (CheckBit(flag, ZZZFLAG_LSHIFT) | CheckBit(flag, ZZZFLAG_RSHIFT)) SetBit(flag,ZZZFLAG_SHIFT); if (CheckBit(flag, ZZZFLAG_LCTRL) | CheckBit(flag, ZZZFLAG_RCTRL)) SetBit(flag,ZZZFLAG_CTRL); if (CheckBit(flag, ZZZFLAG_LALT) | CheckBit(flag, ZZZFLAG_RALT)) SetBit(flag,ZZZFLAG_ALT); if (CheckBit(flag, ZZZFLAG_LMETA) | CheckBit(flag, ZZZFLAG_RMETA)) SetBit(flag,ZZZFLAG_META); } //OnKeyDown,OnChar #define ZZZKEY_NOKEY (0) #define ZZZKEY_1 ('1') #define ZZZKEY_2 ('2') #define ZZZKEY_3 ('3') #define ZZZKEY_4 ('4') #define ZZZKEY_5 ('5') #define ZZZKEY_6 ('6') #define ZZZKEY_7 ('7') #define ZZZKEY_8 ('8') #define ZZZKEY_9 ('9') #define ZZZKEY_0 ('0') #define ZZZKEY_A ('A') #define ZZZKEY_B ('B') #define ZZZKEY_C ('C') #define ZZZKEY_D ('D') #define ZZZKEY_E ('E') #define ZZZKEY_F ('F') #define ZZZKEY_G ('G') #define ZZZKEY_H ('H') #define ZZZKEY_I ('I') #define ZZZKEY_J ('J') #define ZZZKEY_K ('K') #define ZZZKEY_L ('L') #define ZZZKEY_M ('M') #define ZZZKEY_N ('N') #define ZZZKEY_O ('O') #define ZZZKEY_P ('P') #define ZZZKEY_Q ('Q') #define ZZZKEY_R ('R') #define ZZZKEY_S ('S') #define ZZZKEY_T ('T') #define ZZZKEY_U ('U') #define ZZZKEY_V ('V') #define ZZZKEY_W ('W') #define ZZZKEY_X ('X') #define ZZZKEY_Y ('Y') #define ZZZKEY_Z ('Z') #define ZZZKEY_a ('a') #define ZZZKEY_b ('b') #define ZZZKEY_c ('c') #define ZZZKEY_d ('d') #define ZZZKEY_e ('e') #define ZZZKEY_f ('f') #define ZZZKEY_g ('g') #define ZZZKEY_h ('h') #define ZZZKEY_i ('i') #define ZZZKEY_j ('j') #define ZZZKEY_k ('k') #define ZZZKEY_l ('l') #define ZZZKEY_m ('m') #define ZZZKEY_n ('n') #define ZZZKEY_o ('o') #define ZZZKEY_p ('p') #define ZZZKEY_q ('q') #define ZZZKEY_r ('r') #define ZZZKEY_s ('s') #define ZZZKEY_t ('t') #define ZZZKEY_u ('u') #define ZZZKEY_v ('v') #define ZZZKEY_w ('w') #define ZZZKEY_x ('x') #define ZZZKEY_y ('y') #define ZZZKEY_z ('z') #define ZZZKEY_MINUS ('-') #define ZZZKEY_UL ('_') //underline #define ZZZKEY_EQUAL ('=') #define ZZZKEY_PLUS ('+') #define ZZZKEY_LSB ('[') //left square bracket #define ZZZKEY_RSB (']') //right square bracket #define ZZZKEY_LB ('{') //left brace #define ZZZKEY_RB ('}') //right brace #define ZZZKEY_SCOLON ('; ') //Semi Colon #define ZZZKEY_COLON (':') //Colon #define ZZZKEY_SQM ('\'') //Single Quotation mark #define ZZZKEY_DQM ('\"') //Double Quotation mark #define ZZZKEY_COMMA (',') #define ZZZKEY_LT ('<') //Less Than #define ZZZKEY_DOT ('.') #define ZZZKEY_GT ('>') //Grater Than #define ZZZKEY_SLASH ('/') #define ZZZKEY_QM ('?') //Question Mark #define ZZZKEY_BSLASH ('\\') #define ZZZKEY_VB ('|') //Vertical Bar #define ZZZKEY_SPACE (' ') #define ZZZKEY_BQ ('`') //Back Quotation #define ZZZKEY_TILDE ('~') #define ZZZKEY_EM ('!') //Exclamation Mark #define ZZZKEY_AT ('@') #define ZZZKEY_NS ('#') //Number Sign #define ZZZKEY_DOLLAR ('$') #define ZZZKEY_PERCENT ('%') #define ZZZKEY_CARET ('^') #define ZZZKEY_AMPERSAND ('&') #define ZZZKEY_ASTERISK ('*') #define ZZZKEY_LP ('(') //Left Parenthesis #define ZZZKEY_RP (')') //Right Parenthesis #define ZZZKEY_ESC (27) #define ZZZKEY_ESCAPE (27) #define ZZZKEY_TAB (9) #define ZZZKEY_BACK (8) #define ZZZKEY_ENTER (13) #define ZZZKEY_RETURN (13) #define ZZZKEY_BASE_FUNC (256) #define ZZZKEY_CAPSLOCK (259) #define ZZZKEY_SCROLLLOCK (260) #define ZZZKEY_PAUSE (261) #define ZZZKEY_PRINT (262) #define ZZZKEY_F_KEY (290) #define ZZZKEY_F1 (291) #define ZZZKEY_F2 (292) #define ZZZKEY_F3 (293) #define ZZZKEY_F4 (294) #define ZZZKEY_F5 (295) #define ZZZKEY_F6 (296) #define ZZZKEY_F7 (297) #define ZZZKEY_F8 (298) #define ZZZKEY_F9 (299) #define ZZZKEY_F10 (300) #define ZZZKEY_F11 (301) #define ZZZKEY_F12 (302) #define ZZZKEY_F13 (303) #define ZZZKEY_F14 (304) #define ZZZKEY_F15 (305) #define ZZZKEY_FUNC (310) #define ZZZKEY_INSERT (311) #define ZZZKEY_DELETE (312) #define ZZZKEY_HOME (313) #define ZZZKEY_END (314) #define ZZZKEY_PAGEUP (315) #define ZZZKEY_PAGEDOWN (316) #define ZZZKEY_DIR (320) #define ZZZKEY_UP (321) #define ZZZKEY_DOWN (322) #define ZZZKEY_LEFT (323) #define ZZZKEY_RIGHT (324) #define ZZZKEY_NUM_KEY (330) #define ZZZKEY_NUM_LOCK (331) #define ZZZKEY_NUM_PLUS (332) #define ZZZKEY_NUM_MINUS (333) #define ZZZKEY_NUM_TIMES (334) #define ZZZKEY_NUM_DIVIDE (335) #define ZZZKEY_NUM_1 (336) #define ZZZKEY_NUM_2 (337) #define ZZZKEY_NUM_3 (338) #define ZZZKEY_NUM_4 (339) #define ZZZKEY_NUM_5 (340) #define ZZZKEY_NUM_6 (341) #define ZZZKEY_NUM_7 (342) #define ZZZKEY_NUM_8 (343) #define ZZZKEY_NUM_9 (344) #define ZZZKEY_NUM_0 (345) #define ZZZKEY_NUM_DOT (346) #define ZZZKEY_NUM_ENTER (347) #define ZZZKEY_CTRL (400) #define ZZZKEY_ALT (410) #define ZZZKEY_SHIFT (420) #define ZZZKEY_META (500) //WIN for Windows and CMD for Mac #define ZZZKEY_MENU (510) #define ZZZKEY_LCTRL (401) #define ZZZKEY_RCTRL (402) #define ZZZKEY_LALT (411) #define ZZZKEY_RALT (412) #define ZZZKEY_LSHIFT (421) #define ZZZKEY_RSHIFT (422) #define ZZZKEY_LMETA (501) #define ZZZKEY_RMETA (502) }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/KeyDefine.hpp
C++
gpl3
5,921
#pragma once #include <zGraphicsConfig.hpp> #include "KeyDefine.hpp" #include "../GraphicsGUI/GraphicsGUI.hpp" #include "../Resource/ResourceManager.hpp" #include <Utility/Thread.hpp> namespace zzz{ class Renderer; class ZGRAPHICS_CLASS Context { public: Context(); virtual ~Context(); public: // Connect renderer and context. // Call this function as soon as possible. // Better to be called inside context initialization. // Do not make user to call explicitly, they will forget... // Do not in constructor for users' convenience void SetRenderer(Renderer *renderer); // Generally speaking, this method need not to be overrided. // In every paint function which is called after dirty by GUI system. // Should only call this RenderScene() function. // swapbuffer by GUI system should be disabled. virtual void RenderScene(); // This make window dirty, so paint will be insert into message queue. virtual void Redraw()=0; // To swap opengl buffer. virtual void SwapBuffer()=0; // Need override, make current, for multi context. // ALWAYS NEED TO CALL THISl virtual void MakeCurrent(); // To hide/show cursor, for camera operation. virtual void HideCursor(){} virtual void ShowCursor(){} // For GraphicsGUI. // If renderer owns the mouse, gui will not receive. void OwnMouse(bool own){own_mouse_=own;} void OwnKeyboard(bool own){own_keyboard_=own;} // Interface to send message to Renderer void OnMouseMove(unsigned int nFlags,int x,int y); void OnLButtonDown(unsigned int nFlags,int x,int y); void OnLButtonUp(unsigned int nFlags,int x,int y); void OnRButtonDown(unsigned int nFlags,int x,int y); void OnRButtonUp(unsigned int nFlags,int x,int y); void OnMButtonDown(unsigned int nFlags,int x,int y); void OnMButtonUp(unsigned int nFlags,int x,int y); void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y); void OnSize(unsigned int nType, int cx, int cy); void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); void OnIdle(); // Wwap renderer, since resources are connected to the context, it is not very useful. void SwapRenderer(Context *other); // Get renderer Renderer* GetRenderer(){return renderer_;} // Get resource manager ResourceManager* GetRM(){return &RM_;} protected: bool own_mouse_; bool own_keyboard_; bool show_gui_; GraphicsGUI<Renderer> *gui_; Renderer *renderer_; ResourceManager RM_; //ATTENTION: fill the window size when resize int width_, height_; public: static Context *current_context_; #ifdef ZZZ_OPENGL_MX static Mutex OpenGLMutex; #endif // ZZZ_OPENGL_MX }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/Context.hpp
C++
gpl3
2,893
#define ZGRAPHICS_SOURCE #include "Qt4Context.hpp" #ifdef ZZZ_CONTEXT_QT4 #include <QtGui/QApplication> #include "../Resource/Shader/ShaderSpecify.hpp" #include "../Graphics/OpenGLTools.hpp" namespace zzz{ ////////////////////////////////////////////////////////////////////////// //QTWidget zQt4GLWidget::zQt4GLWidget(Renderer *renderer) { setFormat(QGLFormat(QGL::DoubleBuffer | QGL::DepthBuffer)); SetRenderer(renderer); setMouseTracking(true); setFocusPolicy(Qt::StrongFocus); setAutoBufferSwap(false); //glInit(); } void zQt4GLWidget::initializeGL() { #ifdef ZZZ_OPENGL_MX OpenGLMutex.Lock(); #endif // ZZZ_OPENGL_MX MakeCurrent(); InitGLEW(); renderer_->InitState(); renderer_->InitData(); #ifdef ZZZ_OPENGL_MX OpenGLMutex.Unlock(); #endif // ZZZ_OPENGL_MX //init GraphicsGUI if (gui_) gui_->Init(renderer_); } void zQt4GLWidget::resizeGL(int width, int height) { Context::OnSize(0, width, height); } void zQt4GLWidget::paintGL() { RenderScene(); } void zQt4GLWidget::mousePressEvent(QMouseEvent *event) { switch(event->button()) { case Qt::LeftButton: return Context::OnLButtonDown(GetInputFlag(),event->x(),event->y()); case Qt::RightButton: return Context::OnRButtonDown(GetInputFlag(),event->x(),event->y()); case Qt::MidButton: return Context::OnMButtonDown(GetInputFlag(),event->x(),event->y()); } } void zQt4GLWidget::mouseReleaseEvent(QMouseEvent *event) { switch(event->button()) { case Qt::LeftButton: return Context::OnLButtonUp(GetInputFlag(),event->x(),event->y()); case Qt::RightButton: return Context::OnRButtonUp(GetInputFlag(),event->x(),event->y()); case Qt::MidButton: return Context::OnMButtonUp(GetInputFlag(),event->x(),event->y()); } } void zQt4GLWidget::mouseMoveEvent(QMouseEvent *event) { return Context::OnMouseMove(GetInputFlag(),event->x(),event->y()); } #ifndef QT_NO_WHEELEVENT void zQt4GLWidget::wheelEvent(QWheelEvent *event) { return Context::OnMouseWheel(GetInputFlag(),event->delta()/120,event->x(),event->y()); } #endif void zQt4GLWidget::keyPressEvent(QKeyEvent *event) { unsigned int repeat=event->count(); unsigned int c=0; if (!event->text().isEmpty()) c=event->text()[repeat-1].toAscii(); Context::OnKeyDown(QT4Key2ZZZKey(event->key()),repeat,GetInputFlag()); if (c!=0) { Context::OnChar(c,repeat,GetInputFlag()); } } void zQt4GLWidget::keyReleaseEvent(QKeyEvent *event) { unsigned int repeat=event->count(); return Context::OnKeyUp(QT4Key2ZZZKey(event->key()),repeat,GetInputFlag()); } unsigned int zQt4GLWidget::GetInputFlag() { unsigned int flag=0; Qt::KeyboardModifiers keystatus=QApplication::keyboardModifiers(); if (CheckBit(keystatus,Qt::ShiftModifier)) SetBit(flag,ZZZFLAG_SHIFT); if (CheckBit(keystatus,Qt::ControlModifier)) SetBit(flag,ZZZFLAG_CTRL); if (CheckBit(keystatus,Qt::AltModifier)) SetBit(flag,ZZZFLAG_ALT); if (CheckBit(keystatus,Qt::MetaModifier)) SetBit(flag,ZZZFLAG_META); Qt::MouseButtons mousestatus=QApplication::mouseButtons(); if (CheckBit(mousestatus,Qt::LeftButton)) SetBit(flag,ZZZFLAG_LMOUSE); if (CheckBit(mousestatus,Qt::RightButton)) SetBit(flag,ZZZFLAG_RMOUSE); if (CheckBit(mousestatus,Qt::MidButton)) SetBit(flag,ZZZFLAG_MMOUSE); if (CheckBit(mousestatus,Qt::XButton1)) SetBit(flag,ZZZFLAG_X1MOUSE); if (CheckBit(mousestatus,Qt::XButton2)) SetBit(flag,ZZZFLAG_X2MOUSE); CompleteZZZFlags(flag); return flag; } unsigned int zQt4GLWidget::QT4Key2ZZZKey(int key) { switch(key) { case Qt::Key_Escape: return ZZZKEY_ESCAPE; case Qt::Key_Tab: return ZZZKEY_TAB; case Qt::Key_Backspace: return ZZZKEY_BACK; case Qt::Key_Return: return ZZZKEY_RETURN; case Qt::Key_Enter: return ZZZKEY_ENTER; case Qt::Key_Insert: return ZZZKEY_INSERT; case Qt::Key_Delete: return ZZZKEY_DELETE; case Qt::Key_Pause: return ZZZKEY_PAUSE; case Qt::Key_Print: return ZZZKEY_PRINT; case Qt::Key_Home: return ZZZKEY_HOME; case Qt::Key_End: return ZZZKEY_END; case Qt::Key_Left: return ZZZKEY_LEFT; case Qt::Key_Up: return ZZZKEY_UP; case Qt::Key_Right: return ZZZKEY_RIGHT; case Qt::Key_Down: return ZZZKEY_DOWN; case Qt::Key_PageUp: return ZZZKEY_PAGEUP; case Qt::Key_PageDown: return ZZZKEY_PAGEDOWN; case Qt::Key_Shift: return ZZZKEY_SHIFT; case Qt::Key_Control: return ZZZKEY_CTRL; case Qt::Key_Meta: return ZZZKEY_META; case Qt::Key_Alt: return ZZZKEY_ALT; case Qt::Key_CapsLock: return ZZZKEY_CAPSLOCK; case Qt::Key_NumLock: return ZZZKEY_NUM_LOCK; case Qt::Key_ScrollLock: return ZZZKEY_ESCAPE; case Qt::Key_F1: return ZZZKEY_F1; case Qt::Key_F2: return ZZZKEY_F2; case Qt::Key_F3: return ZZZKEY_F3; case Qt::Key_F4: return ZZZKEY_F4; case Qt::Key_F5: return ZZZKEY_F5; case Qt::Key_F6: return ZZZKEY_F6; case Qt::Key_F7: return ZZZKEY_F7; case Qt::Key_F8: return ZZZKEY_F8; case Qt::Key_F9: return ZZZKEY_F9; case Qt::Key_F10: return ZZZKEY_F10; case Qt::Key_F11: return ZZZKEY_F11; case Qt::Key_F12: return ZZZKEY_F12; case Qt::Key_F13: return ZZZKEY_F13; case Qt::Key_F14: return ZZZKEY_F14; case Qt::Key_F15: return ZZZKEY_F15; case Qt::Key_Menu: return ZZZKEY_MENU; case Qt::Key_Space: return ZZZKEY_SPACE; case Qt::Key_QuoteDbl: return ZZZKEY_DQM; case Qt::Key_NumberSign: return ZZZKEY_MINUS; case Qt::Key_Dollar: return ZZZKEY_DOLLAR; case Qt::Key_Percent: return ZZZKEY_PERCENT; case Qt::Key_Ampersand: return ZZZKEY_AMPERSAND; case Qt::Key_Apostrophe: return ZZZKEY_SQM; case Qt::Key_ParenLeft: return ZZZKEY_LP; case Qt::Key_ParenRight: return ZZZKEY_RP; case Qt::Key_Asterisk: return ZZZKEY_ASTERISK; case Qt::Key_Plus: return ZZZKEY_PLUS; case Qt::Key_Comma: return ZZZKEY_COMMA; case Qt::Key_Minus: return ZZZKEY_MINUS; case Qt::Key_Period: return ZZZKEY_DOT; case Qt::Key_Slash: return ZZZKEY_SLASH; case Qt::Key_0: return ZZZKEY_0; case Qt::Key_1: return ZZZKEY_1; case Qt::Key_2: return ZZZKEY_2; case Qt::Key_3: return ZZZKEY_3; case Qt::Key_4: return ZZZKEY_4; case Qt::Key_5: return ZZZKEY_5; case Qt::Key_6: return ZZZKEY_6; case Qt::Key_7: return ZZZKEY_7; case Qt::Key_8: return ZZZKEY_8; case Qt::Key_9: return ZZZKEY_9; case Qt::Key_Colon: return ZZZKEY_COLON; case Qt::Key_Semicolon: return ZZZKEY_SCOLON; case Qt::Key_Less: return ZZZKEY_LT; case Qt::Key_Equal: return ZZZKEY_EQUAL; case Qt::Key_Greater: return ZZZKEY_GT; case Qt::Key_Question: return ZZZKEY_QM; case Qt::Key_At: return ZZZKEY_AT; case Qt::Key_A: return ZZZKEY_a; case Qt::Key_B: return ZZZKEY_b; case Qt::Key_C: return ZZZKEY_c; case Qt::Key_D: return ZZZKEY_d; case Qt::Key_E: return ZZZKEY_e; case Qt::Key_F: return ZZZKEY_f; case Qt::Key_G: return ZZZKEY_g; case Qt::Key_H: return ZZZKEY_h; case Qt::Key_I: return ZZZKEY_i; case Qt::Key_J: return ZZZKEY_j; case Qt::Key_K: return ZZZKEY_k; case Qt::Key_L: return ZZZKEY_l; case Qt::Key_M: return ZZZKEY_m; case Qt::Key_N: return ZZZKEY_n; case Qt::Key_O: return ZZZKEY_o; case Qt::Key_P: return ZZZKEY_p; case Qt::Key_Q: return ZZZKEY_q; case Qt::Key_R: return ZZZKEY_r; case Qt::Key_S: return ZZZKEY_s; case Qt::Key_T: return ZZZKEY_t; case Qt::Key_U: return ZZZKEY_u; case Qt::Key_V: return ZZZKEY_v; case Qt::Key_W: return ZZZKEY_w; case Qt::Key_X: return ZZZKEY_x; case Qt::Key_Y: return ZZZKEY_y; case Qt::Key_Z: return ZZZKEY_z; case Qt::Key_BracketLeft: return ZZZKEY_LSB; case Qt::Key_Backslash: return ZZZKEY_BSLASH; case Qt::Key_BracketRight: return ZZZKEY_RSB; case Qt::Key_Underscore: return ZZZKEY_UL; case Qt::Key_QuoteLeft: return ZZZKEY_BQ; case Qt::Key_BraceLeft: return ZZZKEY_LB; case Qt::Key_Bar: return ZZZKEY_VB; case Qt::Key_BraceRight: return ZZZKEY_RB; } return ZZZKEY_NOKEY; } } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/Qt4Context.cpp
C++
gpl3
8,010
#pragma once #include <zGraphicsConfig.hpp> #include "../zGraphicsConfig.hpp" #include "Context.hpp" #ifdef ZZZ_CONTEXT_QT4 #include "../Renderer/Renderer.hpp" #pragma warning(disable:4311) //reinterpret_cast #pragma warning(disable:4312) //reinterpret_cast #include <QtOpenGL/QGLWidget> #include <QtGui/QMouseEvent> #include <QtGui/QWheelEvent> #include <QtGui/QKeyEvent> namespace zzz{ class ZGRAPHICS_CLASS zQt4GLWidget : public QGLWidget, public Context { public: zQt4GLWidget(Renderer *renderer); protected: void initializeGL(); void resizeGL(int width, int height); void paintGL(); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); #ifndef QT_NO_WHEELEVENT void wheelEvent(QWheelEvent *); #endif void keyPressEvent(QKeyEvent *); void keyReleaseEvent(QKeyEvent *); //Context interface public: void Redraw() { this->update(); } void SwapBuffer() { this->swapBuffers(); } void HideCursor() { this->setCursor(QCursor(Qt::BlankCursor)); } void ShowCursor() { this->setCursor(QCursor(Qt::ArrowCursor)); } void MakeCurrent() { this->makeCurrent(); Context::MakeCurrent(); } static unsigned int QT4Key2ZZZKey(int key); unsigned int GetInputFlag(); }; } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/Qt4Context.hpp
C++
gpl3
1,371
#pragma once #include "../../common.hpp" #include "../../Graphics/Box2.hpp" #include "../../Renderer/Renderer.hpp" namespace zzz{ struct MultiContextDescriptorBase { float m_ratio; //width / height Box2<int> m_box; }; struct MultiContextDescriptor : public MultiContextDescriptorBase { Renderer *m_renderer; }; struct MultiContextHSplitor : public MultiContextDescriptor { public: vector<MultiContextDescriptor*> m_desc; void AddDescriptor(MultiContextDescriptor *desc) { m_desc.push_back(desc); } void Clear() { m_desc.clear(); } }; struct MultiContextVSplitor : public MultiContextDescriptor { vector<MultiContextDescriptor*> m_desc; void AddDescriptor(MultiContextDescriptor *desc) { m_desc.push_back(desc); } void Clear() { m_desc.clear(); } }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/MultiContext/MultiContextDescriptor.hpp
C++
gpl3
824
#define ZGRAPHICS_SOURCE #include "SFMLContext.hpp" #ifdef ZZZ_CONTEXT_SFML #include "../Renderer/Renderer.hpp" #include "../Graphics/OpenGLTools.hpp" namespace zzz{ SFMLContext::SFMLContext(void) :App_(NULL) { } SFMLContext::~SFMLContext(void) { if (App_) delete App_; } void SFMLContext::Initialize(Renderer* renderer, const string &title, int sizex, int sizey) { SetRenderer(renderer); char windowtitle[1024]="zzzEngine in SFML"; if (title) strcpy(windowtitle,title); App_=new sf::RenderWindow(sf::VideoMode(sizex, sizey), windowtitle); #ifdef ZZZ_OPENGL_MX OpenGLMutex.Lock(); #endif // ZZZ_OPENGL_MX InitGLEW(); MakeCurrent(); renderer_->InitState(); renderer_->InitData(); #ifdef ZZZ_OPENGL_MX OpenGLMutex.Unlock(); #endif // ZZZ_OPENGL_MX renderer_->OnSize(0, sizex, sizey); width_=sizex; height_=sizey; // Start game loop while (App_->IsOpened()) { // Process events sf::Event Event; while (App_->GetEvent(Event)) { switch(Event.Type) { case sf::Event::Closed: App_->Close(); break; case sf::Event::KeyPressed: Context::OnKeyDown(SFMLKey2ZZZKey(Event.Key.Code),0 ,(Event.Key.Alt?ZZZFLAG_ALT:0) | (Event.Key.Control?ZZZFLAG_CTRL:0) | (Event.Key.Shift?ZZZFLAG_SHIFT:0)); break; case sf::Event::KeyReleased: Context::OnKeyUp(SFMLKey2ZZZKey(Event.Key.Code),0 ,(Event.Key.Alt?ZZZFLAG_ALT:0) | (Event.Key.Control?ZZZFLAG_CTRL:0) | (Event.Key.Shift?ZZZFLAG_SHIFT:0)); break; case sf::Event::Resized: Context::OnSize(0, Event.Size.Width, Event.Size.Height); width_=Event.Size.Width; height_=Event.Size.Height; break; case sf::Event::TextEntered: Context::OnChar(Event.Text.Unicode, 0, 0); break; case sf::Event::MouseMoved: Context::OnMouseMove(GetInputFlag(),Event.MouseMove.X,Event.MouseMove.Y); break; case sf::Event::MouseButtonPressed: if (Event.MouseButton.Button==sf::Mouse::Left) Context::OnLButtonDown(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); else if (Event.MouseButton.Button==sf::Mouse::Right) Context::OnRButtonDown(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); else if (Event.MouseButton.Button==sf::Mouse::Middle) Context::OnMButtonDown(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); break; case sf::Event::MouseButtonReleased: if (Event.MouseButton.Button==sf::Mouse::Left) Context::OnLButtonUp(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); else if (Event.MouseButton.Button==sf::Mouse::Right) Context::OnRButtonUp(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); else if (Event.MouseButton.Button==sf::Mouse::Middle) Context::OnMButtonUp(GetInputFlag(),Event.MouseButton.X,Event.MouseButton.Y); break; case sf::Event::MouseWheelMoved: renderer_->OnMouseWheel(GetInputFlag(),Event.MouseWheel.Delta,App_->GetInput().GetMouseX(),App_->GetInput().GetMouseX()); break; //not support by zzzEngine yet case sf::Event::MouseEntered: case sf::Event::MouseLeft: case sf::Event::LostFocus: case sf::Event::GainedFocus: case sf::Event::JoyButtonPressed: case sf::Event::JoyButtonReleased: case sf::Event::JoyMoved: break; } } if (needRedraw_) { RenderScene(); needRedraw_=false; } } // Don't forget to destroy our texture // glDeleteTextures(1, &Texture);} } void SFMLContext::Redraw() { needRedraw_=true; } void SFMLContext::SwapBuffer() { App_->Display(); } void SFMLContext::MakeCurrent() { App_->SetActive(); Context::MakeCurrent(); } unsigned int SFMLContext::SFMLKey2ZZZKey(sf::Key::Code &code) { switch(code) { case sf::Key::A: return ZZZKEY_a; case sf::Key::B: return ZZZKEY_b; case sf::Key::C: return ZZZKEY_c; case sf::Key::D: return ZZZKEY_d; case sf::Key::E: return ZZZKEY_e; case sf::Key::F: return ZZZKEY_f; case sf::Key::G: return ZZZKEY_g; case sf::Key::H: return ZZZKEY_h; case sf::Key::I: return ZZZKEY_i; case sf::Key::J: return ZZZKEY_j; case sf::Key::K: return ZZZKEY_k; case sf::Key::L: return ZZZKEY_l; case sf::Key::M: return ZZZKEY_m; case sf::Key::N: return ZZZKEY_n; case sf::Key::O: return ZZZKEY_o; case sf::Key::P: return ZZZKEY_p; case sf::Key::Q: return ZZZKEY_q; case sf::Key::R: return ZZZKEY_r; case sf::Key::S: return ZZZKEY_s; case sf::Key::T: return ZZZKEY_t; case sf::Key::U: return ZZZKEY_u; case sf::Key::V: return ZZZKEY_v; case sf::Key::W: return ZZZKEY_w; case sf::Key::X: return ZZZKEY_x; case sf::Key::Y: return ZZZKEY_y; case sf::Key::Z: return ZZZKEY_z; case sf::Key::Num0: return ZZZKEY_NUM_0; case sf::Key::Num1: return ZZZKEY_NUM_1; case sf::Key::Num2: return ZZZKEY_NUM_2; case sf::Key::Num3: return ZZZKEY_NUM_3; case sf::Key::Num4: return ZZZKEY_NUM_4; case sf::Key::Num5: return ZZZKEY_NUM_5; case sf::Key::Num6: return ZZZKEY_NUM_6; case sf::Key::Num7: return ZZZKEY_NUM_7; case sf::Key::Num8: return ZZZKEY_NUM_8; case sf::Key::Num9: return ZZZKEY_NUM_9; case sf::Key::Escape: return ZZZKEY_ESC; case sf::Key::LControl: return ZZZKEY_LCTRL; case sf::Key::LShift: return ZZZKEY_LSHIFT; case sf::Key::LAlt: return ZZZKEY_LALT; case sf::Key::LSystem: return ZZZKEY_LMETA; case sf::Key::RControl: return ZZZKEY_RCTRL; case sf::Key::RShift: return ZZZKEY_RSHIFT; case sf::Key::RAlt: return ZZZKEY_RALT; case sf::Key::RSystem: return ZZZKEY_RMETA; case sf::Key::Menu: return ZZZKEY_MENU; case sf::Key::LBracket: return ZZZKEY_LSB; case sf::Key::RBracket: return ZZZKEY_RSB; case sf::Key::SemiColon: return ZZZKEY_SCOLON; case sf::Key::Comma: return ZZZKEY_COMMA; case sf::Key::Period: return ZZZKEY_DOT; case sf::Key::Quote: return ZZZKEY_SQM; case sf::Key::Slash: return ZZZKEY_SLASH; case sf::Key::BackSlash: return ZZZKEY_BSLASH; case sf::Key::Tilde: return ZZZKEY_TILDE; case sf::Key::Equal: return ZZZKEY_EQUAL; case sf::Key::Dash: return ZZZKEY_MINUS; case sf::Key::Space: return ZZZKEY_SPACE; case sf::Key::Return: return ZZZKEY_ENTER; case sf::Key::Back: return ZZZKEY_BACK; case sf::Key::Tab: return ZZZKEY_TAB; case sf::Key::PageUp: return ZZZKEY_PAGEUP; case sf::Key::PageDown: return ZZZKEY_PAGEDOWN; case sf::Key::End: return ZZZKEY_END; case sf::Key::Home: return ZZZKEY_HOME; case sf::Key::Insert: return ZZZKEY_INSERT; case sf::Key::Delete: return ZZZKEY_DELETE; case sf::Key::Add: return ZZZKEY_NUM_PLUS; case sf::Key::Subtract: return ZZZKEY_NUM_MINUS; case sf::Key::Multiply: return ZZZKEY_NUM_TIMES; case sf::Key::Divide: return ZZZKEY_NUM_DIVIDE; case sf::Key::Left: return ZZZKEY_LEFT; case sf::Key::Right: return ZZZKEY_RIGHT; case sf::Key::Up: return ZZZKEY_UP; case sf::Key::Down: return ZZZKEY_DOWN; case sf::Key::Numpad0: return ZZZKEY_NUM_0; case sf::Key::Numpad1: return ZZZKEY_NUM_1; case sf::Key::Numpad2: return ZZZKEY_NUM_2; case sf::Key::Numpad3: return ZZZKEY_NUM_3; case sf::Key::Numpad4: return ZZZKEY_NUM_4; case sf::Key::Numpad5: return ZZZKEY_NUM_5; case sf::Key::Numpad6: return ZZZKEY_NUM_6; case sf::Key::Numpad7: return ZZZKEY_NUM_7; case sf::Key::Numpad8: return ZZZKEY_NUM_8; case sf::Key::Numpad9: return ZZZKEY_NUM_9; case sf::Key::F1: return ZZZKEY_F1; case sf::Key::F2: return ZZZKEY_F2; case sf::Key::F3: return ZZZKEY_F3; case sf::Key::F4: return ZZZKEY_F4; case sf::Key::F5: return ZZZKEY_F5; case sf::Key::F6: return ZZZKEY_F6; case sf::Key::F7: return ZZZKEY_F7; case sf::Key::F8: return ZZZKEY_F8; case sf::Key::F9: return ZZZKEY_F9; case sf::Key::F10: return ZZZKEY_F10; case sf::Key::F11: return ZZZKEY_F11; case sf::Key::F12: return ZZZKEY_F12; case sf::Key::F13: return ZZZKEY_F13; case sf::Key::F14: return ZZZKEY_F14; case sf::Key::F15: return ZZZKEY_F15; case sf::Key::Pause: return ZZZKEY_PAUSE; } return ZZZKEY_NOKEY; } unsigned int SFMLContext::GetInputFlag() { unsigned int flag=0; if (App_->GetInput().IsKeyDown(sf::Key::LControl)) SetBit(flag,ZZZFLAG_LCTRL); if (App_->GetInput().IsKeyDown(sf::Key::RControl)) SetBit(flag,ZZZFLAG_RCTRL); if (App_->GetInput().IsKeyDown(sf::Key::LAlt)) SetBit(flag,ZZZFLAG_LALT); if (App_->GetInput().IsKeyDown(sf::Key::RAlt)) SetBit(flag,ZZZFLAG_RALT); if (App_->GetInput().IsKeyDown(sf::Key::LShift)) SetBit(flag,ZZZFLAG_LSHIFT); if (App_->GetInput().IsKeyDown(sf::Key::RShift)) SetBit(flag,ZZZFLAG_RSHIFT); CompleteZZZFlags(flag); if (App_->GetInput().IsMouseButtonDown(sf::Mouse::Left)) SetBit(flag,ZZZFLAG_LMOUSE); if (App_->GetInput().IsMouseButtonDown(sf::Mouse::Right)) SetBit(flag,ZZZFLAG_RMOUSE); if (App_->GetInput().IsMouseButtonDown(sf::Mouse::Middle)) SetBit(flag,ZZZFLAG_MMOUSE); if (App_->GetInput().IsMouseButtonDown(sf::Mouse::XButton1)) SetBit(flag,ZZZFLAG_X1MOUSE); if (App_->GetInput().IsMouseButtonDown(sf::Mouse::XButton1)) SetBit(flag,ZZZFLAG_X2MOUSE); return flag; } } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/SFMLContext.cpp
C++
gpl3
9,649
#pragma once #include <zGraphicsConfig.hpp> #include "../zGraphicsConfig.hpp" #include "Context.hpp" #include "../Graphics/Graphics.hpp" #include "../GraphicsGUI/GraphicsGUI.hpp" #include "../Renderer/Renderer.hpp" //GLUT #define FREEGLUT_STATIC #define FREEGLUT_LIB_PRAGMAS 0 #include <GL/freeglut.h> //GLUI #ifdef ZZZ_CONTEXT_GLUI #define GLUI_NO_LIB_PRAGMA #include <GL/glui.h> #endif namespace zzz{ class ZGRAPHICS_CLASS GLUTContext : public Context { public: virtual ~GLUTContext(); public: typedef enum{NOGLUI,GLUISUBWINDOW,GLUIWINDOW} GluiMode; bool Initialize(Renderer* renderer, GluiMode mode=NOGLUI, const char *title=0, int sizex=600, int sizey=600); void Redraw() { MakeCurrent(); glutPostRedisplay(); } void SwapBuffer() { MakeCurrent(); glutSwapBuffers(); } void MakeCurrent() { glutSetWindow(window_id); Context::MakeCurrent(); } void HideCursor() { glutSetCursor(GLUT_CURSOR_NONE); } void ShowCursor() { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); } void StartMainLoop() { MakeCurrent(); glutMainLoop(); } int GetWindowID() { return window_id; } #ifdef ZZZ_CONTEXT_GLUI GLUI *GetGlui() { return glui; } #endif public: static void reshape(int nw, int nh) { s_context->MakeCurrent(); #ifdef ZZZ_CONTEXT_GLUI if (gluimode==GLUISUBWINDOW) { int tx,ty,tw,th; GLUI_Master.get_viewport_area(&tx,&ty,&tw,&th); nw=tw; nh=th; } #endif s_context->OnSize(0,nw,nh); } static void display(void) { s_context->RenderScene(); } static void mouse(int button, int state, int x, int y) { switch(button) { case GLUT_LEFT_BUTTON: if (state==GLUT_UP) { left_=false; return s_context->OnLButtonUp(GetInputFlag(),x,y); } else if (state==GLUT_DOWN) { left_=true; return s_context->OnLButtonDown(GetInputFlag(),x,y); } break; case GLUT_RIGHT_BUTTON: if (state==GLUT_UP) { right_=false; return s_context->OnRButtonUp(GetInputFlag(),x,y); } else if (state==GLUT_DOWN) { right_=true; return s_context->OnRButtonDown(GetInputFlag(),x,y); } break; case GLUT_MIDDLE_BUTTON: if (state==GLUT_UP) { middle_=false; return s_context->OnMButtonUp(GetInputFlag(),x,y); } else if (state==GLUT_DOWN) { middle_=true; return s_context->OnMButtonDown(GetInputFlag(),x,y); } break; } } static void mousewheel(int button, int dir, int x, int y) { if (dir > 0) { return s_context->OnMouseWheel(GetInputFlag(),1,x,y); } else { return s_context->OnMouseWheel(GetInputFlag(),-1,x,y); } } static void motion(int x, int y) { return s_context->OnMouseMove(GetInputFlag(),x,y); } static void passivemotion(int x, int y) { return s_context->OnMouseMove(GetInputFlag(),x,y); } static void key(unsigned char key, int x, int y) { s_context->OnKeyDown(key,0,GetInputFlag()); return s_context->OnChar(key,0,GetInputFlag()); } static void keyup(unsigned char key, int x, int y) { s_context->OnKeyUp(key,0,GetInputFlag()); } static void special(int key, int x, int y) { return s_context->OnKeyDown(GLUTKey2ZZZKey(key),0,GetInputFlag()); } static void idle() { return s_context->OnIdle(); } protected: static unsigned int GLUTKey2ZZZKey(int key); static unsigned int GetInputFlag(); static GLUTContext *s_context; static int window_id; static bool left_, right_, middle_; #ifdef ZZZ_CONTEXT_GLUI static GLUI *glui; #endif static GluiMode gluimode; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/GLUTContext.hpp
C++
gpl3
3,777
#define ZGRAPHICS_SOURCE #include "GLUTContext.hpp" #include "../Graphics/OpenGLTools.hpp" #include "../Resource/Shader/ShaderSpecify.hpp" namespace zzz{ GLUTContext * GLUTContext::s_context; int GLUTContext::window_id; #ifdef ZZZ_CONTEXT_GLUI GLUI *GLUTContext::glui; #endif GLUTContext::GluiMode GLUTContext::gluimode; bool GLUTContext::left_; bool GLUTContext::right_; bool GLUTContext::middle_; bool GLUTContext::Initialize(Renderer* renderer, GluiMode mode/*=NOGLUI*/, const char *title/* =0 */, int sizex/* =600 */, int sizey/* =600 */) { s_context=this; SetRenderer(renderer); left_=false; right_=false; middle_=false; int argc=1; char *argv[]={NULL}; #ifdef ZZZ_OPENGL_MX OpenGLMutex.Lock(); #endif // ZZZ_OPENGL_MX glutInit(&argc,argv); glutInitWindowSize(sizex,sizey); glutInitWindowPosition(0,0); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); if (title) window_id=glutCreateWindow(title); else window_id=glutCreateWindow("zzz Engine in GLUT"); MakeCurrent(); InitGLEW(); renderer_->InitState(); renderer_->InitData(); #ifdef ZZZ_OPENGL_MX OpenGLMutex.Unlock(); #endif // ZZZ_OPENGL_MX glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(key); glutKeyboardUpFunc(keyup); glutSpecialFunc(special); glutMouseFunc(mouse); glutMouseWheelFunc(mousewheel); glutMotionFunc(motion); glutPassiveMotionFunc(passivemotion); // glutIdleFunc(idle); // init GLUI #ifdef ZZZ_CONTEXT_GLUI gluimode = mode; switch(mode) { case NOGLUI: glui=NULL; break; case GLUISUBWINDOW: GLUI_Master.set_glutKeyboardFunc(key); GLUI_Master.set_glutSpecialFunc(special); GLUI_Master.set_glutMouseFunc(mouse); GLUI_Master.set_glutReshapeFunc(reshape); GLUI_Master.set_glutIdleFunc(idle); glui=GLUI_Master.create_glui_subwindow(window_id,GLUI_SUBWINDOW_RIGHT); break; case GLUIWINDOW: GLUI_Master.set_glutIdleFunc(idle); if (title) glui=GLUI_Master.create_glui(title); else glui=GLUI_Master.create_glui("zzz Engine GLUI Window",0,sizex+10,0); glui->set_main_gfx_window(window_id); break; } #endif //init GraphicsGUI if (gui_) gui_->Init(renderer_); return true; } GLUTContext::~GLUTContext() { } unsigned int GLUTContext::GLUTKey2ZZZKey(int key) { switch(key) { case GLUT_KEY_F1: return ZZZKEY_F1; case GLUT_KEY_F2: return ZZZKEY_F2; case GLUT_KEY_F3: return ZZZKEY_F3; case GLUT_KEY_F4: return ZZZKEY_F4; case GLUT_KEY_F5: return ZZZKEY_F5; case GLUT_KEY_F6: return ZZZKEY_F6; case GLUT_KEY_F7: return ZZZKEY_F7; case GLUT_KEY_F8: return ZZZKEY_F8; case GLUT_KEY_F9: return ZZZKEY_F9; case GLUT_KEY_F10: return ZZZKEY_F10; case GLUT_KEY_F11: return ZZZKEY_F11; case GLUT_KEY_F12: return ZZZKEY_F12; case GLUT_KEY_LEFT: return ZZZKEY_LEFT; case GLUT_KEY_UP: return ZZZKEY_UP; case GLUT_KEY_RIGHT: return ZZZKEY_RIGHT; case GLUT_KEY_DOWN: return ZZZKEY_DOWN; case GLUT_KEY_PAGE_UP: return ZZZKEY_PAGEUP; case GLUT_KEY_PAGE_DOWN: return ZZZKEY_PAGEDOWN; case GLUT_KEY_HOME: return ZZZKEY_HOME; case GLUT_KEY_END: return ZZZKEY_END; case GLUT_KEY_INSERT: return ZZZKEY_INSERT; } return 0; } unsigned int GLUTContext::GetInputFlag() { int modifers=glutGetModifiers(); unsigned int flag=0; if (CheckBit(modifers,GLUT_ACTIVE_SHIFT)) SetBit(flag,ZZZFLAG_SHIFT); if (CheckBit(modifers,GLUT_ACTIVE_ALT)) SetBit(flag,ZZZFLAG_CTRL); if (CheckBit(modifers,GLUT_ACTIVE_CTRL)) SetBit(flag,ZZZFLAG_ALT); if (left_) SetBit(flag, ZZZFLAG_LMOUSE); if (right_) SetBit(flag, ZZZFLAG_RMOUSE); if (middle_) SetBit(flag, ZZZFLAG_MMOUSE); return flag; } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/GLUTContext.cpp
C++
gpl3
3,767
#pragma once #include <zGraphicsConfig.hpp> #include "Context.hpp" #ifdef ZZZ_CONTEXT_SFML #include <SFML/Graphics.hpp> #ifdef ZZZ_DEBUG #pragma comment(lib,"sfml-window-s-d.lib") #pragma comment(lib,"sfml-graphics-s-d.lib") #pragma comment(lib,"sfml-system-s-d.lib") #else #pragma comment(lib,"sfml-window-s.lib") #pragma comment(lib,"sfml-graphics-s.lib") #pragma comment(lib,"sfml-system-s.lib") #endif #pragma comment(lib,"libpng.lib") #pragma comment(lib,"libjpeg.lib") namespace zzz{ class ZGRAPHICS_CLASS SFMLContext : public Context { public: SFMLContext(void); ~SFMLContext(void); void Initialize(Renderer* renderer, const string &title=0, int sizex=600, int sizey=600); void Redraw(); void SwapBuffer(); void MakeCurrent(); private: sf::RenderWindow *App_; bool needRedraw_; static unsigned int SFMLKey2ZZZKey(sf::Key::Code&); unsigned int GetInputFlag(); }; } #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/SFMLContext.hpp
C++
gpl3
943
#define ZGRAPHICS_SOURCE #include "../Graphics/OpenGLTools.hpp" #include "../Graphics/Graphics.hpp" #include "../Renderer/Renderer.hpp" #include "Context.hpp" namespace zzz{ Context *Context::current_context_=NULL; #ifdef ZZZ_OPENGL_MX Mutex Context::OpenGLMutex; #endif // ZZZ_OPENGL_MX Context::Context() :own_mouse_(false),own_keyboard_(false), gui_(NULL),renderer_(NULL),show_gui_(true) {} Context::~Context() { RM_.Clear(); if (current_context_==this) current_context_=NULL; } void Context::SetRenderer(Renderer *renderer) { renderer_=renderer; renderer->SetContext(this); if (renderer_->gui_) gui_=renderer_->gui_; } void Context::RenderScene() { // Always lock the RenderScene, so context won't be switched in the middle of rendering. // There is only one graphics card anyway, so it won't affect the performance much. // Just don't write too much non-rendering stuff inside RenderScene. #ifdef ZZZ_OPENGL_MX OpenGLMutex.Lock(); #endif // ZZZ_OPENGL_MX MakeCurrent(); renderer_->RenderScene(); if (gui_ && show_gui_) gui_->Draw(); SwapBuffer(); #ifdef ZZZ_OPENGL_MX OpenGLMutex.Unlock(); #endif // ZZZ_OPENGL_MX } void Context::SwapRenderer(Context *other) { if (other==this) return; Renderer *r=renderer_; renderer_=other->renderer_; other->renderer_=r; renderer_->SetContext(this); r->SetContext(other); MakeCurrent(); renderer_->OnSize(0,width_,height_); other->MakeCurrent(); r->OnSize(0,other->width_,other->height_); } void Context::MakeCurrent() { current_context_=this; } void Context::OnMouseMove(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnMouseMove(nFlags, x, y)) return; renderer_->OnMouseMove(nFlags, x, y); } void Context::OnLButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnLButtonDown(nFlags, x, y)) return; renderer_->OnLButtonDown(nFlags, x, y); } void Context::OnLButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnLButtonUp(nFlags, x, y)) return; renderer_->OnLButtonUp(nFlags, x, y); OwnMouse(false); } void Context::OnRButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnRButtonDown(nFlags, x, y)) return; renderer_->OnRButtonDown(nFlags, x, y); } void Context::OnRButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnRButtonUp(nFlags, x, y)) return; renderer_->OnRButtonUp(nFlags, x, y); OwnMouse(false); } void Context::OnMButtonDown(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnMButtonDown(nFlags, x, y)) return; renderer_->OnMButtonDown(nFlags, x, y); } void Context::OnMButtonUp(unsigned int nFlags,int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnMButtonUp(nFlags, x, y)) return; renderer_->OnMButtonUp(nFlags, x, y); OwnMouse(false); } void Context::OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y) { if (!own_mouse_ && gui_ && show_gui_ && gui_->OnMouseWheel(nFlags, zDelta, x, y)) return; renderer_->OnMouseWheel(nFlags, zDelta, x, y); } void Context::OnSize(unsigned int nType, int cx, int cy) { if (gui_) gui_->OnSize(0, cx, cy); width_=cx;height_=cy; renderer_->OnSize(nType, cx, cy); } void Context::OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (!own_keyboard_ && gui_ && show_gui_ && gui_->OnChar(nChar, nRepCnt, nFlags)) return; renderer_->OnChar(nChar, nRepCnt, nFlags); } void Context::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (nChar==ZZZKEY_CAPSLOCK){ show_gui_=!show_gui_; Redraw(); return; } if (!own_keyboard_ && gui_ && show_gui_ && gui_->OnKeyDown(nChar, nRepCnt, nFlags)) return; renderer_->OnKeyDown(nChar, nRepCnt, nFlags); } void Context::OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (!own_keyboard_ && gui_ && show_gui_ && gui_->OnKeyUp(nChar, nRepCnt, nFlags)) return; renderer_->OnKeyUp(nChar, nRepCnt, nFlags); } void Context::OnIdle() { renderer_->OnIdle(); } }
zzz-engine
zzzEngine/zGraphics/zGraphics/Context/Context.cpp
C++
gpl3
4,352
#pragma once #include <zGraphicsConfig.hpp> #include "RT_Ray.hpp" #include "../Graphics/AABB.hpp" namespace zzz { // interior node of a k-d tree struct ZGRAPHICS_CLASS RT_KdNode { enum SAxis{AXIS_X = 0, AXIS_Y, AXIS_Z}; SAxis splitFlag; // decide split axis float split; //decide split plane position int left, right, parent ; //l/r child or parent index in the RT_KdNode List // if left/ right is a negative interger,then its child is a leaf(use abs to index) unsigned int nElems; }; // leaf of a k-d tree struct ZGRAPHICS_CLASS RT_KdLeaf { zuint nElems; vector<int> elems; int prim; //bounding box for the leaf's triangle int parent; //parent index in Node List }; // axis aligned accelebrated data struct class ZGRAPHICS_CLASS RT_KdTree { public: RT_KdTree(); void Clear(); //description : user interface , see member func buildTree bool Build(const vector<Vector3f> &points, const vector<Vector3i> &faces); //description : test intersect for a given ray, return the hit point's properties (pos,normal,texcoord) bool Intersect(RT_Ray &ray, int &f, Vector3f &bary); //description : only test if a given ray intersects the scene ,return true is hits any mesh bool DoesIntersect(RT_Ray &ray) ; //vector<RT_Triangle> mTriangleList; vector<Vector3i> faces_; vector<Vector3f> points_; private: // build a kdTree based on current vertexes and indexes recursively // building strategy : minimize the cost(node) = Cost on traversal + (1 - be)(PB * NB * ti + PA * NA * ti) // where be is a bonus for one-side empty choice , PB,PA is the probabilities of left and right ,NB, NA is the number of tris of left and right. int BuildTree(const AABB3f &nodeBounds, vector<int> &mTris, int numTris ,int depth); int CreateLeaf(const AABB3f& leafBounds, const vector<int> &mTris, int numTris); bool NodeIntersect(int index, const AABB3f &nodeBounds, RT_Ray &ray, int &f, Vector3f &bary); bool NodeIntersectP(int index, const AABB3f &nodeBounds, RT_Ray &ray); bool LeafIntersect(int index, RT_Ray &ray, int &f, Vector3f &bary); bool LeafIntersectP(int index, RT_Ray &ray); AABB3f GetTriangleAABB(int t) const; int TriangleIntersectPlaneAxis(int t, float pos, int axis) const; bool TriangleIntersect(int t, const RT_Ray &ray, Vector3f &bary, float &hitDist) const; bool TriangleDoesIntersect(int t, const RT_Ray &ray) const; // keep scene's mesh content in vector<AABB3f> mPrimList; // keep interior nodes vector<RT_KdNode> mNodes; vector<RT_KdLeaf> mLeafs; AABB3f mBounds; int root; //root node index; float mbe ; // bonus param of be ,in the range of [0, 1] float mCostTt; // cost on traverse the interior node and decide ray partition method, i set it as 1.0f float mCostTi; // cost on intersect with a elem ,say a triangle, i set is a 80.0f; // when the interior node's depth exceed the max depth, or it contains no more than minElems elems, it should become a RT_KdLeaf int maxDepth; int minElems; int mCurNodeIndex; int mCurLeafIndex; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/RayTracer/RT_KdTree.hpp
C++
gpl3
3,102
#define ZGRAPHICS_SOURCE #include "RT_Ray.hpp" namespace zzz { const float RT_Ray::MAX_RAY_RANGE=4096.0f; const float RT_Ray::RAY_EPSILON=0.00003f; }
zzz-engine
zzzEngine/zGraphics/zGraphics/RayTracer/RT_Ray.cpp
C++
gpl3
156
#pragma once #include <zGraphicsConfig.hpp> #include <Math/Vector3.hpp> #include "../Graphics/AABB.hpp" namespace zzz { class ZGRAPHICS_CLASS RT_Ray { public: static const float MAX_RAY_RANGE; static const float RAY_EPSILON; RT_Ray() :mint_(RAY_EPSILON), maxt_(MAX_RAY_RANGE) { } RT_Ray(const Vector3f &ori, const Vector3f &dir, float min = RAY_EPSILON, float max = MAX_RAY_RANGE) :ori_(ori), dir_(dir), mint_(min), maxt_(max) { } bool IntersectP(const AABB3f &aabb, float &hitt0, float &hitt1) const { float t0 = mint_, t1 = maxt_; for (int i = 0; i<3; ++i) { //update interval for ith bounding box slab float invRayDir = 1.f / dir_[i]; float tNear = (aabb.Min(i) - ori_[i]) * invRayDir; float tFar = (aabb.Max(i) - ori_[i]) * invRayDir; //update parametric interval from slab intersection ts if (tNear > tFar) Swap(tNear, tFar); t0 = tNear > t0 ? tNear : t0; t1 = tFar < t1 ? tFar : t1; if (t0 > t1) return false; } hitt0 = t0; hitt1 = t1; return true; } public: Vector3f ori_; Vector3f dir_; float mint_, maxt_; }; }
zzz-engine
zzzEngine/zGraphics/zGraphics/RayTracer/RT_Ray.hpp
C++
gpl3
1,176
#include <zGraphicsConfig.hpp> #ifdef ZZZ_DYNAMIC #include <zCoreAutoLink.hpp> #include <zImageAutoLink.hpp> #include <zGraphicsAutoLink3rdParty.hpp> #endif
zzz-engine
zzzEngine/zGraphics/zGraphics/zGraphicsAutoLink.cpp
C++
gpl3
163
SET(THISLIB zVision) FILE(GLOB_RECURSE LibSrc *.cpp) #MESSAGE(STATUS "files ${LibSrc}") IF( "${DEBUG_MODE}" EQUAL "1") SET(THISLIB ${THISLIB}D) ENDIF() IF( "${BIT_MODE}" EQUAL "64" ) SET(THISLIB ${THISLIB}_X64) ENDIF() ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
zzz-engine
zzzEngine/zVision/CMakeLists.txt
CMake
gpl3
272
#pragma once #include <Math/Matrix3x3.hpp> #include <Math/Random.hpp> #include <Math/Vector.hpp> namespace zzz{ template<typename T, zuint N> Vector<N+1,T> ToHomogeneous(const Vector<N,T> &v) { Vector<N+1,T> res; for (zuint i=0; i<N; i++) res[i]=v[i]; res[N]=1; return res; } template<typename T, zuint N> Vector<N-1,T> FromHomogeneous(const Vector<N,T> &v) { Vector<N-1,T> res; for (zuint i=0; i<N-1; i++) res[i]=v[i]/v[N-1]; return res; } //randomly pick N different integers template<zuint N> class RANSACPicker { public: typedef Vector<N,int> PickType; /// Constructor RANSACPicker(const int min, const int max) : randi_(min,max) { ZCHECK_GE(max - min + 1, N) << "Cannot pick enough number from the given range!"; } Vector<N,int> Pick() { Vector<N,int> res; set<int> taken; for (zuint i = 0; i < N; i++) { int x = randi_.Rand(); while(taken.find(x) != taken.end()) x = randi_.Rand(); taken.insert(x); res[i] = x; } return res; } void SeedFromTime(){randi_.SeedFromTime();} private: RandomInteger<int> randi_; }; template<typename T> Matrix<3,3,T> SkewSymmetricMatrix(const Vector<3,T> &a) { Matrix<3,3,T> res; res(0,0)=0; res(0,1)=-a[2]; res(0,2)=a[1]; res(1,0)=a[2]; res(1,1)=0; res(1,2)=-a[0]; res(2,0)=-a[1];res(2,1)=a[0]; res(2,2)=0; return res; } }
zzz-engine
zzzEngine/zVision/zVision/VisionTools.hpp
C++
gpl3
1,432
#pragma once #include <EnvDetect.hpp> #include <LibraryConfig.hpp> #ifdef ZZZ_OS_WIN32 #include "zVisionConfig.hpp.win32" #endif
zzz-engine
zzzEngine/zVision/zVision/zVisionConfig.hpp
C++
gpl3
137
#pragma once #include <common.hpp> #include <Math/Vector3.hpp> #include <Math/Matrix3x3.hpp> #include "../VisionTools.hpp" namespace zzz{ class Homography { public: static const int MIN_POINT_NUMBER = 4; Homography(){Hab_.Identical(); Hba_.Identical();} bool Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb); bool Create(const vector<Vector3d> &pa, const vector<Vector3d> &pb); Vector3d ToA(const Vector3d &pb) { Vector3d ret=Hba_*pb; ret/=ret[2]; return ret; } Vector2d ToA(const Vector2d &pb) { return FromHomogeneous(ToA(ToHomogeneous(pb))); } Vector3d ToB(const Vector3d &pa) { Vector3d ret=Hab_*pa; ret/=ret[2]; return ret; } Vector2d ToB(const Vector2d &pb) { return FromHomogeneous(ToB(ToHomogeneous(pb))); } Matrix3x3d GetHab(){return Hab_;} Matrix3x3d GetHba(){return Hba_;} private: Matrix3x3d Hab_; Matrix3x3d Hba_; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/Homography.hpp
C++
gpl3
948
#include "Triangulator.hpp" #include "../VisionTools.hpp" #include <zMat.hpp> namespace zzz{ Vector3d Triangulator::LinearTriangulate(const vector<ProjectionMat<double> > &P, const vector<Vector2d> &pos2ds) { zuint n=P.size(); zMatrix<double> A(n*2,4),U,S,VT; for (zuint i=0; i<n; i++) { A(i*2, Colon()) = Trans(Dress(P[i].P().Row(2)*pos2ds[i][0]-P[i].P().Row(0))); A(i*2+1,Colon()) = Trans(Dress(P[i].P().Row(2)*pos2ds[i][1]-P[i].P().Row(1))); } bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed in linear triangulate."; Vector4d X(VT(3,0),VT(3,1),VT(3,2),VT(3,3)); return FromHomogeneous(X); } void Triangulator::LinearTriangulate(const ProjectionMatd P[2], const vector<Vector2d> pos2ds[2], vector<Vector3d> &pos3ds) { zuint n=pos2ds[0].size(); pos3ds.clear(); pos3ds.reserve(n); zMatrix<double> A(4,4),U,S,VT; Vector4d X; for (zuint i=0; i<n; i++) { A(0,Colon()) = Trans(Dress(P[0].P().Row(2)*pos2ds[0][i][0]-P[0].P().Row(0))); A(1,Colon()) = Trans(Dress(P[0].P().Row(2)*pos2ds[0][i][1]-P[0].P().Row(1))); A(2,Colon()) = Trans(Dress(P[1].P().Row(2)*pos2ds[1][i][0]-P[1].P().Row(0))); A(3,Colon()) = Trans(Dress(P[1].P().Row(2)*pos2ds[1][i][1]-P[1].P().Row(1))); bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed is linear triangulate"; Dress(X)=Trans(VT(3,Colon())); pos3ds.push_back(FromHomogeneous(X)); } } void Triangulator::LinearTriangulate(SceneData<double> &sd) { for (zuint p=0; p<sd.points_.size(); p++) { const vector<SceneData<double>::Point2D> &pos2ds=sd.points_[p].pos2ds; zuint n=pos2ds.size(); zMatrix<double> A(n*2,4),U,S,VT; for (zuint i=0; i<n; i++) { const ProjectionMatd &P=sd.cameras_[pos2ds[i].img_id].camera; A(i*2, Colon()) = Trans(Dress(P.P().Row(2)*pos2ds[i].pos2d[0]-P.P().Row(0))); A(i*2+1,Colon()) = Trans(Dress(P.P().Row(2)*pos2ds[i].pos2d[1]-P.P().Row(1))); } bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed in linear triangulate"; Vector4d X(VT(3,0),VT(3,1),VT(3,2),VT(3,3)); sd.points_[p].pos3d=FromHomogeneous(X); } } void Triangulator::NonLinearTriangulate(const ProjectionMatd P[2], const vector<Vector2d> pos2ds[2], vector<Vector3d> &pos3ds) { } }
zzz-engine
zzzEngine/zVision/zVision/SfM/Triangulator.cpp
C++
gpl3
2,332
#pragma once #include <common.hpp> #include <Math/Vector3.hpp> #include <Math/Matrix3x3.hpp> #include <Math/IterExitCond.hpp> #include "ProjectionMat.hpp" #include "SceneData.hpp" //implementation of 11.1.1 namespace zzz{ class FundamentalMat : public Matrix3x3d { public: FundamentalMat(const MatrixBase<3,3,double> &b):Matrix3x3d(b){} FundamentalMat(const FundamentalMat &b):Matrix3x3d(b){} FundamentalMat(){} bool Create8(const vector<Vector2d> &ls, const vector<Vector2d> &rs); int Create8RANSAC(const vector<Vector2d> &ls, const vector<Vector2d> &rs, const double outlier_threshold, IterExitCond<double> &cond); int Create8RANSAC(PairData<double> &data, const double outlier_threshold, IterExitCond<double> &cond); bool CalEpipoles(Vector3d &left, Vector3d &right); double Residue(const Vector2d &l, const Vector2d &r) const; }; class EssentialMat : public FundamentalMat { public: EssentialMat(const MatrixBase<3,3,double> &b):FundamentalMat(b){} EssentialMat(const EssentialMat &b):FundamentalMat(b){} EssentialMat(){} bool GetProjection(ProjectionMatd &P, const Vector2d &l, const Vector2d &r) const; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/FundamentalMat.hpp
C++
gpl3
1,178
#pragma once #include <Math/Statistics.hpp> #include <Math/Matrix3x3.hpp> //to normalize coordination in an image //based on "In Defense of Eight-Point Algorithm" //set ori to the center of image and scale to make (average distance of all points from the origin is equal to \sqrt{2}) //will make the eight-point algorithm much more robust //remember to restore to original coord after calculate fundamental matrix namespace zzz{ class CoordNormalizer { public: CoordNormalizer(const Vector2ui &size):ori_(size) { ori_/=2.0; double distall=0; for (zuint r=0; r<size[0]; r++) for (zuint c=0; c<size[1]; c++) { double rr(r),cc(c); rr-=ori_[0];cc-=ori_[1]; double dist=Sqrt(rr*rr+cc*cc); distall+=dist; } scale_=size[0]*size[1]*C_SQRT2/distall; CalT(); } CoordNormalizer(const Vector2d &ori, const double scale):ori_(ori),scale_(scale) { CalT(); } CoordNormalizer(const vector<Vector2d> &pts) { //init from a bunch of points //implementation as in phototourism zuint n=pts.size(); //1. centroid of these points ori_=Mean(pts); //2. average distance double dist=0; for (zuint i=0; i<n; i++) dist+=ori_.DistTo(pts[i]); dist/=n; dist/=C_SQRT2; scale_=1.0/dist; CalT(); } template<typename T> void Normalize(Vector<2,T> &ori) { ori[0]=(ori[0]-ori_[0])*scale_; ori[1]=(ori[1]-ori_[1])*scale_; } template<typename T> void Normalize(Vector<3,T> &ori) { ori[0]=(ori[0]-ori_[0])*scale_; ori[1]=(ori[1]-ori_[1])*scale_; } template<typename T> void Restore(Vector<2,T> &nor) { nor[0]=nor[0]/scale_+ori_[0]; nor[1]=nor[1]/scale_+ori_[1]; } template<typename T> void Restore(Vector<3,T> &nor) { nor[0]=nor[0]/scale_+ori_[0]; nor[1]=nor[1]/scale_+ori_[1]; } void Restore(Matrix3x3d &F) { F=T_.Transposed()*F*T_; } const Matrix3x3d& GetT(){return T_;} private: void CalT() { //so that nor=T*ori; T_(0,0)=scale_; T_(0,1)=0; T_(0,2) = -scale_*ori_[0]; T_(1,0)=0; T_(1,1)=scale_; T_(1,2) = -scale_*ori_[1]; T_(2,0)=0; T_(2,1)=0; T_(2,2) = 1; } Vector2d ori_; double scale_; Matrix3x3d T_; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/CoordNormalizer.hpp
C++
gpl3
2,340
#include "Affine.hpp" #include <zMat.hpp> #include <Utility/Log.hpp> #include "../VisionTools.hpp" namespace zzz{ bool Affine::Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb) { ZCHECK_EQ(pa.size(), pb.size()); zuint n=pa.size(); zMatrix<double> A(Zerosd(n*2,6)); zVector<double> B(n*2); zuint cur=0; for (zuint i=0; i<n; i++) { const Vector2d &a=pa[i],&b=pb[i]; A(cur,0)=a[0]; A(cur,1)=a[1]; A(cur,2)=1; B(cur)=b[0]; cur++; A(cur,3)=a[0]; A(cur,4)=a[1]; A(cur,5)=1; B(cur)=b[1]; cur++; } zMatrix<double> ATA(Trans(A)*A); if (!Invert(ATA)) return false; zVector<double> X(ATA*Trans(A)*B); Hab_(0,0)=X(0); Hab_(0,1)=X(1); Hab_(0,2)=X(2); Hab_(1,0)=X(3); Hab_(1,1)=X(4); Hab_(1,2)=X(5); if (Abs(Hab_.Determinant())<EPSILON) return false; Hba_=Hab_.Inverted(); return true; } }
zzz-engine
zzzEngine/zVision/zVision/SfM/Affine.cpp
C++
gpl3
937
#pragma once #include "FundamentalMat.hpp" #include <Math/Vector2.hpp> #include <Math/IterExitCond.hpp> //Calculate relative pose given intrinsic calibration, fundamental matrix and corresponding point pairs namespace zzz{ int FivePointAlgo(EssentialMat &E, const Matrix3x3d &K, const vector<Vector2d> &ls, const vector<Vector2d> &rs, const double outlier_shreshold, IterExitCond<double> &cond); }
zzz-engine
zzzEngine/zVision/zVision/SfM/FivePointAlgo.hpp
C++
gpl3
410
#pragma once #include <common.hpp> #include <Math/Vector3.hpp> #include <Math/Matrix3x3.hpp> #include "../VisionTools.hpp" namespace zzz{ class SmallRigid { public: static const int MIN_POINT_NUMBER = 2; SmallRigid(){Hab_.Identical(); Hba_.Identical();} bool Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb); Vector2d ToA(const Vector2d &pb) { return Vector2d(Hba_*ToHomogeneous(pb)); } Vector2d ToB(const Vector2d &pb) { return Vector2d(Hab_*ToHomogeneous(pb)); } Matrix3x3d GetHab(){return Hab_;} Matrix3x3d GetHba(){return Hba_;} private: Matrix3x3d Hab_; Matrix3x3d Hba_; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/SmallRigid.hpp
C++
gpl3
652
#include "Homography.hpp" #include <zMat.hpp> #include <Utility/Log.hpp> #include "../VisionTools.hpp" namespace zzz{ bool Homography::Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb) { ZCHECK_EQ(pa.size(), pb.size()); zuint n=pa.size(); zMatrix<double> A(Zeros<double>(n*2,9)),U,S,VT; zuint cur=0; for (zuint i = 0; i < n; ++i) { const Vector2d &a = pa[i], &b = pb[i]; A(cur, 0) = a[0]; A(cur, 1) = a[1]; A(cur, 2) = 1; A(cur, 6) = -a[0] * b[0]; A(cur, 7) = -a[1] * b[0]; A(cur, 8) = -b[0]; ++cur; A(cur, 3) = a[0]; A(cur, 4) = a[1]; A(cur, 5) = 1; A(cur, 6) = -a[0] * b[1]; A(cur, 7) = -a[1] * b[1]; A(cur, 8) = -b[1]; ++cur; } if (!SVD(A,U,S,VT)) { ZLOGE<<"SVD ERROR!\n"; return false; } Hab_(0, 0) = VT(8, 0); Hab_(0, 1) = VT(8, 1); Hab_(0, 2) = VT(8, 2); Hab_(1, 0) = VT(8, 3); Hab_(1, 1) = VT(8, 4); Hab_(1, 2) = VT(8, 5); Hab_(2, 0) = VT(8, 6); Hab_(2, 1) = VT(8, 7); Hab_(2, 2) = VT(8, 8); Hab_.Normalize(); Hba_ = Hab_; if (!Hba_.Invert()) return false; Hba_.Normalize(); return true; } bool Homography::Create(const vector<Vector3d> &pa, const vector<Vector3d> &pb) { ZCHECK_EQ(pa.size(), pb.size()); zuint n = pa.size(); vector<Vector2d> pa2,pb2; pa2.reserve(n); pb2.reserve(n); for (zuint i = 0; i < n; ++i) { pa2.push_back(FromHomogeneous(pa[i])); pb2.push_back(FromHomogeneous(pb[i])); } return Create(pa2, pb2); } }
zzz-engine
zzzEngine/zVision/zVision/SfM/Homography.cpp
C++
gpl3
1,484
#pragma once #include "ProjectionMat.hpp" #include <Math/Vector2.hpp> #include <Math/Vector3.hpp> #include <Math/Vector.hpp> #include "SceneData.hpp" namespace zzz{ class Triangulator { public: static Vector3d LinearTriangulate(const vector<ProjectionMat<double> > &P, const vector<Vector2d> &pos2ds); static void LinearTriangulate(const ProjectionMat<double> P[2], const vector<Vector2d> pos2ds[2], vector<Vector3d> &pos3ds); static void LinearTriangulate(SceneData<double> &sd); static void NonLinearTriangulate(const ProjectionMat<double> P[2], const vector<Vector2d> pos2ds[2], vector<Vector3d> &pos3ds); }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/Triangulator.hpp
C++
gpl3
644
#pragma once #include <common.hpp> #include <Math/Vector3.hpp> #include <Math/Matrix3x3.hpp> #include "../VisionTools.hpp" namespace zzz{ class Affine { public: static const int MIN_POINT_NUMBER = 3; Affine(){Hab_.Identical(); Hba_.Identical();} bool Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb); Vector2d ToA(const Vector2d &pb) { return Vector2d(Hba_*ToHomogeneous(pb)); } Vector2d ToB(const Vector2d &pb) { return Vector2d(Hab_*ToHomogeneous(pb)); } Matrix3x3d GetHab(){return Hab_;} Matrix3x3d GetHba(){return Hba_;} private: Matrix3x3d Hab_; Matrix3x3d Hba_; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/Affine.hpp
C++
gpl3
644
#pragma once #include "SceneData.hpp" #include <Utility/IOObject.hpp> namespace zzz { typedef SceneDataf64::Point2D SceneDataf32Point2D; SIMPLE_IOOBJECT(SceneDataf32Point2D); typedef SceneDataf64::Point SceneDataf32Point; template<> class IOObject<SceneDataf32Point> { public: typedef SceneDataf32Point DataType; static const int RF_POS3D = 1; static const int RF_POS2DS = 2; static const int RF_FERROR = 3; static const int RF_PERROR = 4; static const int RF_STATUS = 5; static void WriteFileR(RecordFile &rf, const DataType &src) { IOObj::WriteFileR(rf, RF_POS3D, src.pos3d); IOObj::WriteFileR(rf, RF_POS2DS, src.pos2ds); IOObj::WriteFileR(rf, RF_FERROR, src.ferror); IOObj::WriteFileR(rf, RF_PERROR, src.perror); IOObj::WriteFileR(rf, RF_STATUS, src.status); } static void ReadFileR(RecordFile &rf, DataType &dst) { IOObj::ReadFileR(rf, RF_POS3D, dst.pos3d); IOObj::ReadFileR(rf, RF_POS2DS, dst.pos2ds); IOObj::ReadFileR(rf, RF_FERROR, dst.ferror); IOObj::ReadFileR(rf, RF_PERROR, dst.perror); IOObj::ReadFileR(rf, RF_STATUS, dst.status); } }; typedef SceneDataf64::ImageInfo SceneDataf32ImageInfo; SIMPLE_IOOBJECT(SceneDataf32ImageInfo); typedef SceneDataf64::CameraInfo SceneDataf32CameraInfo; SIMPLE_IOOBJECT(SceneDataf32CameraInfo); typedef SceneDataf64::SIFTMatch SceneDataf32SIFTMatch; SIMPLE_IOOBJECT(SceneDataf32SIFTMatch::PtIdx); SIMPLE_IOOBJECT(SceneDataf32SIFTMatch::Matches); template<> class IOObject<SceneDataf32SIFTMatch> { public: typedef SceneDataf32SIFTMatch DataType; static const int RF_ID1 = 1; static const int RF_ID2 = 2; static const int RF_PTIDX = 3; static const int RF_MATCHES = 4; static void WriteFileR(RecordFile &rf, const DataType &src) { IOObj::WriteFileR(rf, RF_ID1, src.id1); IOObj::WriteFileR(rf, RF_ID2, src.id2); IOObj::WriteFileR(rf, RF_PTIDX, src.ptidx); IOObj::WriteFileR(rf, RF_MATCHES, src.matches); } static void ReadFileR(RecordFile &rf, DataType &dst) { IOObj::ReadFileR(rf, RF_ID1, dst.id1); IOObj::ReadFileR(rf, RF_ID2, dst.id2); IOObj::ReadFileR(rf, RF_PTIDX, dst.ptidx); IOObj::ReadFileR(rf, RF_MATCHES, dst.matches); } }; typedef SceneDataf64::SfMPair SceneDataf32SfMPair; SIMPLE_IOOBJECT(SceneDataf32SfMPair); template<> class IOObject<SceneDataf64> { public: typedef SceneDataf64 DataType; static const int RF_POINTS = 1; static const int RF_IMGINFOS = 2; static const int RF_CAMERAS = 3; static const int RF_SIFTKEYS = 4; static const int RF_SIFTMATCHES = 5; static const int RF_SFMPAIR = 6; static void WriteFileR(RecordFile &rf, const zint32 label, const SceneData<zfloat32> &src) { IOObj::WriteFileR1By1(rf, RF_POINTS, src.points_); IOObj::WriteFileR(rf, RF_IMGINFOS, src.imginfos_); IOObj::WriteFileR(rf, RF_CAMERAS, src.cameras_); IOObj::WriteFileR1By1(rf, RF_SIFTKEYS, src.siftkeys_); IOObj::WriteFileR1By1(rf, RF_SIFTMATCHES, src.siftmatches_); IOObj::WriteFileR(rf, RF_SFMPAIR, src.sfmpairs_); } static void ReadFileR(RecordFile &rf, const zint32 label, SceneData<zfloat32> &dst) { IOObj::ReadFileR1By1(rf, RF_POINTS, dst.points_); IOObj::ReadFileR(rf, RF_IMGINFOS, dst.imginfos_); IOObj::ReadFileR(rf, RF_CAMERAS, dst.cameras_); IOObj::ReadFileR1By1(rf, RF_SIFTKEYS, dst.siftkeys_); IOObj::ReadFileR1By1(rf, RF_SIFTMATCHES, dst.siftmatches_); IOObj::ReadFileR(rf, RF_SFMPAIR, dst.sfmpairs_); } }; }; // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/SfM/SceneDataIOObject.hpp
C++
gpl3
3,569
#include "FivePointAlgo.hpp" //#include "5point/5point.h" #include <zMat.hpp> #include "../VisionTools.hpp" #include "Homography.hpp" #include <Math/Poly3.hpp> #include <Math/Matrix.hpp> namespace zzz{ void computeNullspaceBasis(const vector<Vector2d> &ls, const vector<Vector2d> &rs, Matrix<4,9,double> &basis) { zMatrix<double> A(ls.size(),9),U,S,VT; /* Create the 5x9 epipolar constraint matrix */ for (zuint i = 0; i < ls.size(); i++) { A(i,0) = rs[i][0] * ls[i][0]; A(i,1) = rs[i][1] * ls[i][0]; A(i,2) = ls[i][0]; A(i,3) = rs[i][0] * ls[i][1]; A(i,4) = rs[i][1] * ls[i][1]; A(i,5) = ls[i][1]; A(i,6) = rs[i][0]; A(i,7) = rs[i][1]; A(i,8) = 1; } /* Find four vectors that span the right nullspace of the matrix */ SVD(A,U,S,VT); Dress(basis)=VT(Colon(5,8),Colon()); } void compute_constraint_matrix(const Matrix<4,9,double> &basis, Poly3<double> constraints[10]) { /* Basis rows are X, Y, Z, W * Essential matrix is or form x*X + y*Y + z*Z + W */ /* Create a polynomial for each entry of E */ Poly3<double> polys[9]; for (int i=0; i < 9; i++) { polys[i][POLY3_X]=basis(0,i); polys[i][POLY3_Y]=basis(1,i); polys[i][POLY3_Z]=basis(2,i); polys[i][POLY3_UNIT]=basis(3,i); } /* Create a polynormial from the constraint det(E) = 0 */ Poly3<double> poly_term1 (polys[1].Multiply11(polys[5]) - polys[2].Multiply11(polys[4])); poly_term1=poly_term1.Multiply21(polys[6]); // matrix_print(1, 20, poly_term1.v); Poly3<double> poly_term2 (polys[2].Multiply11(polys[3]) - polys[0].Multiply11(polys[5])); poly_term2=poly_term2.Multiply21(polys[7]); Poly3<double> poly_term3 (polys[0].Multiply11(polys[4]) - polys[1].Multiply11(polys[3])); poly_term3=poly_term3.Multiply21(polys[8]); Poly3<double> poly_det = poly_term1 + poly_term2 + poly_term3; /* Create polynomials for the singular value constraint */ Poly3<double> poly_EET[6]; for (int i = 0; i < 6; i++) { int r = 0, c = 0, k; switch(i) { case 0: case 1: case 2: r = 0; c = i; break; case 3: case 4: r = 1; c = i-2; break; case 5: r = 2; c = 2; break; } for (k = 0; k < 3; k++) { poly_EET[i] = poly_EET[i] + polys[r*3+k].Multiply11(polys[c*3+k]); } } Poly3<double> poly_tr = (poly_EET[0] + poly_EET[3] + poly_EET[5]) * 0.5; Poly3<double> poly_lambda0(poly_EET[0] - poly_tr); Poly3<double> poly_lambda1(poly_EET[1]); Poly3<double> poly_lambda2(poly_EET[2]); Poly3<double> poly_lambda3(poly_EET[3] - poly_tr); Poly3<double> poly_lambda4(poly_EET[4]); Poly3<double> poly_lambda5(poly_EET[5] - poly_tr); constraints[0] = poly_lambda0.Multiply(polys[0]) +\ poly_lambda1.Multiply(polys[3]) +\ poly_lambda2.Multiply(polys[6]); constraints[1] = poly_lambda0.Multiply(polys[1]) +\ poly_lambda1.Multiply(polys[4]) +\ poly_lambda2.Multiply(polys[7]); constraints[2] = poly_lambda0.Multiply(polys[2]) +\ poly_lambda1.Multiply(polys[5]) +\ poly_lambda2.Multiply(polys[8]); constraints[3] = poly_lambda1.Multiply21(polys[0]) +\ poly_lambda3.Multiply21(polys[3]) +\ poly_lambda4.Multiply21(polys[6]); constraints[4] = poly_lambda1.Multiply21(polys[1]) +\ poly_lambda3.Multiply21(polys[4]) +\ poly_lambda4.Multiply21(polys[7]); constraints[5] = poly_lambda1.Multiply21(polys[2]) +\ poly_lambda3.Multiply21(polys[5]) +\ poly_lambda4.Multiply21(polys[8]); constraints[6] = poly_lambda2.Multiply21(polys[0]) +\ poly_lambda4.Multiply21(polys[3]) +\ poly_lambda5.Multiply21(polys[6]); constraints[7] = poly_lambda2.Multiply21(polys[1]) +\ poly_lambda4.Multiply21(polys[4]) +\ poly_lambda5.Multiply21(polys[7]); constraints[8] = poly_lambda2.Multiply21(polys[2]) +\ poly_lambda4.Multiply21(polys[5]) +\ poly_lambda5.Multiply21(polys[8]); constraints[9] = poly_det; } void eliminate_gauss_jordan(Poly3<double> constraints[10]) { Matrix<10,20,double> A; int i, j; for (int i = 0; i < 10; i++) { Vector<20,double> &row=A.Row(i); row[0] = constraints[i][POLY3_X3]; row[1] = constraints[i][POLY3_Y3]; row[2] = constraints[i][POLY3_X2Y]; row[3] = constraints[i][POLY3_XY2]; row[4] = constraints[i][POLY3_X2Z]; row[5] = constraints[i][POLY3_X2]; row[6] = constraints[i][POLY3_Y2Z]; row[7] = constraints[i][POLY3_Y2]; row[8] = constraints[i][POLY3_XYZ]; row[9] = constraints[i][POLY3_XY]; row[10] = constraints[i][POLY3_XZ2]; row[11] = constraints[i][POLY3_XZ]; row[12] = constraints[i][POLY3_X]; row[13] = constraints[i][POLY3_YZ2]; row[14] = constraints[i][POLY3_YZ]; row[15] = constraints[i][POLY3_Y]; row[16] = constraints[i][POLY3_Z3]; row[17] = constraints[i][POLY3_Z2]; row[18] = constraints[i][POLY3_Z]; row[19] = constraints[i][POLY3_UNIT]; } for (i = 0; i < 10; i++) { /* Make the leading coefficient of row i = 1 */ A.Row(i) *= (1.0/A(i,i)); /* Subtract from other rows */ for (j = i+1; j < 10; j++) A.Row(j)-= A.Row(i)*A(j,i); } /* Now, do the back substitution (stopping four rows early) */ for (i = 9; i >= 4; i--) { for (j = 0; j < i; j++) A.Row(j) -= A.Row(i)*A(j,i); } /* Copy out results */ for (i = 0; i < 10; i++) { // memcpy(constraints[i].v, A + 20 * i, sizeof(double) * 20); Vector<20,double> &row = A.Row(i); constraints[i][POLY3_X3] = row[0]; constraints[i][POLY3_Y3] = row[1]; constraints[i][POLY3_X2Y] = row[2]; constraints[i][POLY3_XY2] = row[3]; constraints[i][POLY3_X2Z] = row[4]; constraints[i][POLY3_X2] = row[5]; constraints[i][POLY3_Y2Z] = row[6]; constraints[i][POLY3_Y2] = row[7]; constraints[i][POLY3_XYZ] = row[8]; constraints[i][POLY3_XY] = row[9]; constraints[i][POLY3_XZ2] = row[10]; constraints[i][POLY3_XZ] = row[11]; constraints[i][POLY3_X] = row[12]; constraints[i][POLY3_YZ2] = row[13]; constraints[i][POLY3_YZ] = row[14]; constraints[i][POLY3_Y] = row[15]; constraints[i][POLY3_Z3] = row[16]; constraints[i][POLY3_Z2] = row[17]; constraints[i][POLY3_Z] = row[18]; constraints[i][POLY3_UNIT] = row[19]; } } void compute_B_matrix(Poly3<double> constraints[10], Matrix<9,11,double> &B) { Poly3<double> e = constraints[4]; Poly3<double> f = constraints[5]; Poly3<double> g = constraints[6]; Poly3<double> h = constraints[7]; Poly3<double> i = constraints[8]; Poly3<double> j = constraints[9]; B.Zero(); B(0,3) = -f[POLY3_XZ2]; B(0,2) = e[POLY3_XZ2] - f[POLY3_XZ]; B(0,1) = e[POLY3_XZ] - f[POLY3_X]; B(0,0) = e[POLY3_X]; B(1,3) = -f[POLY3_YZ2]; B(1,2) = e[POLY3_YZ2] - f[POLY3_YZ]; B(1,1) = e[POLY3_YZ] - f[POLY3_Y]; B(1,0) = e[POLY3_Y]; B(2,4) = -f[POLY3_Z3]; B(2,3) = e[POLY3_Z3] - f[POLY3_Z2]; B(2,2) = e[POLY3_Z2] - f[POLY3_Z]; B(2,1) = e[POLY3_Z] - f[POLY3_UNIT]; B(2,0) = e[POLY3_UNIT]; B(3,3) = -h[POLY3_XZ2]; B(3,2) = g[POLY3_XZ2] - h[POLY3_XZ]; B(3,1) = g[POLY3_XZ] - h[POLY3_X]; B(3,0) = g[POLY3_X]; B(4,3) = -h[POLY3_YZ2]; B(4,2) = g[POLY3_YZ2] - h[POLY3_YZ]; B(4,1) = g[POLY3_YZ] - h[POLY3_Y]; B(4,0) = g[POLY3_Y]; B(5,4) = -h[POLY3_Z3]; B(5,3) = g[POLY3_Z3] - h[POLY3_Z2]; B(5,2) = g[POLY3_Z2] - h[POLY3_Z]; B(5,1) = g[POLY3_Z] - h[POLY3_UNIT]; B(5,0) = g[POLY3_UNIT]; B(6,3) = -j[POLY3_XZ2]; B(6,2) = i[POLY3_XZ2] - j[POLY3_XZ]; B(6,1) = i[POLY3_XZ] - j[POLY3_X]; B(6,0) = i[POLY3_X]; B(7,3) = -j[POLY3_YZ2]; B(7,2) = i[POLY3_YZ2] - j[POLY3_YZ]; B(7,1) = i[POLY3_YZ] - j[POLY3_Y]; B(7,0) = i[POLY3_Y]; B(8,4) = -j[POLY3_Z3]; B(8,3) = i[POLY3_Z3] - j[POLY3_Z2]; B(8,2) = i[POLY3_Z2] - j[POLY3_Z]; B(8,1) = i[POLY3_Z] - j[POLY3_UNIT]; B(8,0) = i[POLY3_UNIT]; } Vector<11,double> poly1_mult(const Vector<11,double> &a, const Vector<11,double> &b) { Vector<11,double> r(0); for (int i = 0; i <= 10; i++) for (int j = 0; j <= 10; j++) { int place = i + j; if (place > 10) continue; r[place] += a[i] * b[j]; } return r; } void compute_determinant(Matrix<9,11,double> B, Vector<11,double> &p1, Vector<11,double> &p2, Vector<11,double> &p3, Vector<11,double> &det) { p1 = poly1_mult(B.Row(1), B.Row(5)) - poly1_mult(B.Row(2), B.Row(4)); p2 = poly1_mult(B.Row(2), B.Row(3)) - poly1_mult(B.Row(0), B.Row(5)); p3 = poly1_mult(B.Row(0), B.Row(4)) - poly1_mult(B.Row(1), B.Row(3)); det = poly1_mult(p1, B.Row(6)) + poly1_mult(p2, B.Row(7)) + poly1_mult(p3, B.Row(8)); } int poly1_degree(const Vector<11,double> &a) { for (int i = 10; i >= 0; i--) if (fabs(a[i]) > 0.0) return i; return 0; } Vector<11,double> poly1_normalize(const Vector<11,double> &a) { int d = poly1_degree(a); if (a[d] != 0) return a * (1.0 / a[d]); else return a; } void extract_roots(const Vector<11,double> &det, int *nuroots_, Vector<10,double> &roots) { zMatrix<double,zColMajor> C(10,10), evec, eval, evali; C.Zero(); /* Scale the determinant */ Vector<11,double> det_scale = poly1_normalize(det); /* Fill the companion matrix */ for (int i = 0; i < 10; i++) C(0,i) = -det_scale[9-i]; //C(0,Colon())=-Dress(det_scale)(Colon(9,0,-1)); for (int i = 1; i < 10; i++) C(i,i-1) = 1.0; EigRight(C, evec, eval, evali); //take those roots only have real part *nuroots_=0; for (zuint i=0; i<10; i++) { if (evali[i]==0.0) { roots[*nuroots_]=eval[i]; (*nuroots_)++; } } } double poly1_eval(Vector<11,double> &a, double x) { double p = 1.0; double r = 0.0; for (int i = 0; i <= 10; i++) { r += p * a[i]; p = p * x; } return r; } void compute_Ematrices(int nuposes_, Vector<10,double> &roots, const Matrix<4,9,double> &basis, Vector<11,double> &p1, Vector<11,double> &p2, Vector<11,double> &p3, Vector<10,EssentialMat> &E) { for (int i = 0; i < nuposes_; i++) { double z = roots[i]; double den = poly1_eval(p3, z); double den_inv = 1.0 / den; double x = poly1_eval(p1, z) * den_inv; double y = poly1_eval(p2, z) * den_inv; Vector<9,double> X=basis.Row(0)*x; Vector<9,double> Y=basis.Row(1)*y; Vector<9,double> Z=basis.Row(2)*z; Vector<9,double> tmp=X+Y+Z+basis.Row(3); memcpy(E[i].Data(),tmp.Data(),sizeof(double)*9); } } void compute_Grabner_basis(const Poly3<double> constraints[10], Matrix<10,10,double> &Gbasis) { Matrix<10,20,double> A; int i, j; for (i = 0; i < 10; i++) { // memcpy(A + 20 * i, constraints[i].v, sizeof(double) * 20); Vector<20,double> &row = A.Row(i); /* x3 x2y xy2 y3 x2z xyz y2z xz2 yz2 z3 x2 xy y2 xz yz z2 x y z 1 */ row[0] = constraints[i][POLY3_X3]; row[1] = constraints[i][POLY3_X2Y]; row[2] = constraints[i][POLY3_XY2]; row[3] = constraints[i][POLY3_Y3]; row[4] = constraints[i][POLY3_X2Z]; row[5] = constraints[i][POLY3_XYZ]; row[6] = constraints[i][POLY3_Y2Z]; row[7] = constraints[i][POLY3_XZ2]; row[8] = constraints[i][POLY3_YZ2]; row[9] = constraints[i][POLY3_Z3]; row[10] = constraints[i][POLY3_X2]; row[11] = constraints[i][POLY3_XY]; row[12] = constraints[i][POLY3_Y2]; row[13] = constraints[i][POLY3_XZ]; row[14] = constraints[i][POLY3_YZ]; row[15] = constraints[i][POLY3_Z2]; row[16] = constraints[i][POLY3_X]; row[17] = constraints[i][POLY3_Y]; row[18] = constraints[i][POLY3_Z]; row[19] = constraints[i][POLY3_UNIT]; } /* Do a full Gaussian elimination */ for (i = 0; i < 10; i++) { /* Make the leading coefficient of row i = 1 */ double leading = A(i,i); A.Row(i) *= (1.0/leading); /* Subtract from other rows */ for (j = i+1; j < 10; j++) { double leading2 = A(j,i); Vector<20,double> scaled_row=A.Row(i)*leading2; A.Row(j)-=scaled_row; } } /* Now, do the back substitution */ for (i = 9; i >= 0; i--) { for (j = 0; j < i; j++) { double scale = A(j,i); Vector<20,double> scaled_row=A.Row(i)*scale; A.Row(j)-=scaled_row; } } /* Copy out results */ for (i = 0; i < 10; i++) { memcpy(Gbasis.Row(i).Data(), &(A.Row(i)[10]), sizeof(double) * 10); } } void compute_action_matrix(const Matrix<10,10,double> &Gbasis, Matrix<10,10,double> &At) { At.Zero(); At.Row(0) = -Gbasis.Row(0); At.Row(1) = -Gbasis.Row(1); At.Row(2) = -Gbasis.Row(2); At.Row(3) = -Gbasis.Row(4); At.Row(4) = -Gbasis.Row(5); At.Row(5) = -Gbasis.Row(7); At(6,0) = 1.0; At(7,1) = 1.0; At(8,3) = 1.0; At(9,6) = 1.0; } void compute_Ematrices_Gb(const Matrix<10,10,double> &At, const Matrix<4,9,double> &basis, int *nusolns_, Vector<10,EssentialMat> &E) { zMatrix<double,zColMajor> A(Dress(At)), evec, eval, evali; EigRight(A, evec, eval, evali); *nusolns_=0; for (int i = 0; i < 10; i++) { if (evali[i]==0.0) { double x = evec(6,i); double y = evec(7,i); double z = evec(8,i); double w = evec(9,i); double w_inv = 1.0 / w; x = x * w_inv; y = y * w_inv; z = z * w_inv; Vector<9,double> X = basis.Row(0)*x; Vector<9,double> Y = basis.Row(1)*y; Vector<9,double> Z = basis.Row(2)*z; Vector<9,double> tmp=X+Y+Z+basis.Row(3); memcpy(E[(*nusolns_)].Data(),tmp.Data(),sizeof(double)*9); E[(*nusolns_)]/=E[(*nusolns_)](2,2); (*nusolns_)++; } } } void GenerateEmatrixHypotheses(const vector<Vector2d> &ls, const vector<Vector2d> &rs, Vector<10,EssentialMat> &E, int *nuposes_) { Matrix<4,9,double> basis; computeNullspaceBasis(ls, rs, basis); Poly3<double> constraints[10]; compute_constraint_matrix(basis, constraints); #define FIVE_POINT_OPT #ifndef FIVE_POINT_OPT eliminate_gauss_jordan(constraints); Matrix<9,11,double> B; compute_B_matrix(constraints, B); Vector<11,double> p1,p2,p3,det; compute_determinant(B, p1, p2, p3, det); Vector<10,double> roots; extract_roots(det, nuposes_, roots); compute_Ematrices(*nuposes_, roots, basis, p1, p2, p3, E); #else Matrix<10,10,double> Gbasis; compute_Grabner_basis(constraints, Gbasis); Matrix<10,10,double> At; compute_action_matrix(Gbasis, At); compute_Ematrices_Gb(At, basis, nuposes_, E); #endif } int EvaluateEmatrix(const vector<Vector2d> &rs, const vector<Vector2d> &ls, double thresh_norm, const EssentialMat &F, int *best_inlier, double *score) { int nuinliers_ = 0; double min_resid = 1.0e20; double likelihood = 0.0; zuint n=rs.size(); for (zuint i = 0; i < n; i++) { double resid=F.Residue(ls[i],rs[i]); likelihood += log(1.0 + resid * resid / (thresh_norm)); if (resid < thresh_norm) { nuinliers_++; if (resid < min_resid) { min_resid = resid; *best_inlier = i; } } } *score = likelihood; // *score = 1.0 / nuinliers_; return nuinliers_; } int FivePointAlgo(EssentialMat &E, const Matrix3x3d &K, const vector<Vector2d> &ls, const vector<Vector2d> &rs, const double outlier_shreshold, IterExitCond<double> &cond) { //implementation of "An Efficient Solution to the Five-Point Relative Pose Problem" by David Nister //essential matrix and new point correspondence Matrix3x3d K_inv=K.Inverted(); //RANSAC, ramdonly pick 5 point to do five-point algorithm double thresh_norm=outlier_shreshold*outlier_shreshold; cond.Reset(); int max_inliers=0; double min_score=MAX_FLOAT; EssentialMat E_best; typedef RANSACPicker<5> PickerType; PickerType picker(0,ls.size()-1); picker.SeedFromTime(); do { //randomly pick 5 points PickerType::PickType pick=picker.Pick(); //evaluate these 5 points, so they should not make a homography { vector<Vector2d> ls_homo,rs_homo; for (zuint i=0; i<pick.size(); i++) { ls_homo.push_back(ls[pick[i]]); rs_homo.push_back(rs[pick[i]]); } Homography homography; homography.Create(ls_homo,rs_homo); double homo_error=0; for (zuint i=0; i<rs_homo.size(); i++) homo_error += rs_homo[i].DistTo(FromHomogeneous(homography.GetHab()*ToHomogeneous(ls_homo[i]))); if (homo_error<10) { ZLOGE<<"homo_error:"<<homo_error<<endl; continue; } } //normalize to calculate E vector<Vector2d> ls_norm,rs_norm; for (zuint i=0; i<pick.size(); i++) { ls_norm.push_back(FromHomogeneous(K_inv*ToHomogeneous(ls[pick[i]]))); rs_norm.push_back(FromHomogeneous(K_inv*ToHomogeneous(rs[pick[i]]))); } //five-point algorithm Vector<10,EssentialMat> E; int nuhyp_; // ZDEBUG(SplitLine("mine")); GenerateEmatrixHypotheses(ls_norm,rs_norm,E,&nuhyp_); //DEBUG /* ZDEBUG("Num:"+nuhyp_); for (int i=0; i<nuhyp_; i++) ZDEBUG(string("E")<<i<<"=\n"<<E[i]); zout<<SplitLine("theirs"); Vector<10,EssentialMat> E2; int nuhyp2_; v2_t *rt_pts=new v2_t[lls.size()]; v2_t *lt_pts=new v2_t[lls.size()]; memcpy(lt_pts,lls[0].Data(),sizeof(double)*2*lls.size()); memcpy(rt_pts,rrs[0].Data(),sizeof(double)*2*rrs.size()); generate_Ematrix_hypotheses(lls.size(),rt_pts,lt_pts,&nuhyp2_,(double*)E2.Data()); delete[] lt_pts; delete[] rt_pts; ZDEBUG("Num:"+nuhyp2_); for (int i=0; i<nuhyp2_; i++) ZDEBUG(string("E")<<i<<"=\n"<<E2[i]); */ //END OF DEBUG int best=0; int inliers_hyp[10]; for (int i = 0; i < nuhyp_; i++) { int best_inlier; double score = 0.0; EssentialMat F=K_inv.Transposed()*E[i]*K_inv; //convert back //F/=F(2,2); F.Normalize(); int nuinliers_ = EvaluateEmatrix(rs, ls, outlier_shreshold, F, &best_inlier, &score); if (nuinliers_ > max_inliers || (nuinliers_ == max_inliers && score < min_score)) { best = 1; max_inliers = nuinliers_; min_score = score; E_best=E[i]; ZLOG(ZDEBUG)<<SplitLine("E")<<endl \ <<"E=\n"<<E_best<<endl \ <<"nuinliers_:"<<nuinliers_<<endl; } inliers_hyp[i] = nuinliers_; } }while(!cond.IsSatisfied(double(ls.size()-max_inliers)/ls.size())); E=E_best/E_best(2,2); ZLOG(ZVERBOSE)<<"best_E=\n"<<E \ <<"max_inliers=\n"<<max_inliers<<endl; return max_inliers; } }
zzz-engine
zzzEngine/zVision/zVision/SfM/FivePointAlgo.cpp
C++
gpl3
18,984
#pragma once #include <Math/Matrix3x3.hpp> #include <Math/Vector3.hpp> #include <Math/Vector4.hpp> #include "../VisionTools.hpp" #include <Graphics/Rotation.hpp> #include <Graphics/Translation.hpp> namespace zzz{ template<typename DataType=double> class ProjectionMat { public: ProjectionMat() :K_(1,0,0,0,1,0,0,0,1),R_(1,0,0,0,1,0,0,0,1),T_(0,0,0) {} void Identical() { Dress(P_)=(Diag(Ones<DataType>(3,1)),Zeros<DataType>(3,1)); R_.Identical(); T_=0; } void SetP(const Matrix<3,3,DataType> &M, const Vector<3,DataType> &m) { //F=[M|m] Dress(P_)=(Dress(M),Dress(m)); } void SetP(const Matrix<3,4,DataType> &P) { P_=P; } void MakeP() { //P=K[R|T] Dress(P_)=(Dress(K_*R_),Dress(K_*T_)); if (P_(2,3)!=1) P_/=Abs(P_(2,3)); } void SetRT(const Matrix<3,3,DataType> &R, const Vector<3,DataType> &T) { R_=R; T_=T; } void SetRotationTranslation(const Rotation<DataType> &R, const Translation<DataType> &t) { SetRT(R.Inverted(), R.Inverted()*(-t)); } void MakeRT() { Matrix<3,3,DataType> inv_K=K_.Inverted(); Dress(R_)=Dress(P_)(Colon(),Colon(0,2)); Dress(T_)=Dress(P_)(Colon(),3); R_=inv_K*R_; T_=inv_K*T_; // scale to rotation matrix DataType scale = 1.0 / R_.Row(0).Len(); R_ *= scale; T_ *= scale; } void SetK(const Matrix<3,3,DataType> &K) { K_=K; } void SetK(DataType fx, DataType fy, DataType cx, DataType cy) { K_.Zero(); K_(0,0)=fx; K_(1,1)=fy; K_(0,2)=cx; K_(1,2)=cy; K_(2,2)=1; } // Vanishing point, 0:X 1:Y 2:Z Vector<3,DataType> VPoint(int x) { Vector<3,DataType> res; Dress(res)=Dress(P_)(Colon(),x); return res; } // Camera center // Implementation of table 6.1 Vector<3,DataType> CameraCenter() const { Matrix<3,3,DataType> M; Dress(M)=Dress(P_)(Colon(),Colon(0,2)); Vector<3,DataType> p4; Dress(p4)=Dress(P_)(Colon(),3); return -(M.Inverted()*p4); } Vector<3,DataType> PrincipalPoint() const { Matrix<3,3,DataType> M; Dress(M)=Dress(P_)(Colon(),Colon(0,2)); return M*M.Row(2); } Vector<3,DataType> PrincipalRay() const { Matrix<3,3,DataType> M; Dress(M)=Dress(P_)(Colon(),Colon(0,2)); return (M.Determinant()*M.Row(2)).Normalized(); } Vector<4,DataType> PrincipalPlane() const { return P_.Row(2); } // rotation and translation Rotation<DataType> GetRotation() { return Rotation<DataType>(R_.Inverted()); } Translation<DataType> GetTranslation() { return Translation<DataType>(-(R_.Inverted() * T_)); } const Matrix<3,4,DataType>& P() const {return P_;} const Matrix<3,3,DataType>& R() const {return R_;} const Vector<3,DataType>& T() const {return T_;} const Matrix<3,3,DataType>& K() const {return K_;} const Vector<3,DataType> operator*(const Vector<4,DataType> &x) { return P_*x; } const Vector<2,DataType> operator*(const Vector<3,DataType> &x) { return FromHomogeneous(P_*ToHomogeneous(x)); } private: Matrix<3,4,DataType> P_; Matrix<3,3,DataType> R_; Vector<3,DataType> T_; Matrix<3,3,DataType> K_; }; typedef ProjectionMat<double> ProjectionMatd; typedef ProjectionMat<float> ProjectionMatf; }
zzz-engine
zzzEngine/zVision/zVision/SfM/ProjectionMat.hpp
C++
gpl3
3,333
#include "FundamentalMat.hpp" #include "../VisionTools.hpp" #include "CoordNormalizer.hpp" #include "Triangulator.hpp" #include <zMat.hpp> namespace zzz{ bool FundamentalMat::Create8(const vector<Vector2d> &ls, const vector<Vector2d> &rs) { //implementation of 11.1 assert(ls.size()==rs.size()); //1. normalize CoordNormalizer norl(ls),norr(rs); //2. 8 point linear zMatrix<double> A(ls.size(),9),U,S,VT; for (zuint i=0; i<ls.size(); i++) { Vector2d l=ls[i]; norl.Normalize(l); Vector2d r=rs[i]; norr.Normalize(r); A(i,0)=l[0]*r[0]; A(i,1)=l[0]*r[1]; A(i,2)=l[0]; A(i,3)=l[1]*r[0]; A(i,4)=l[1]*r[1]; A(i,5)=l[1]; A(i,6)=r[0]; A(i,7)=r[1]; A(i,8)=1; } //TODO: optimizable, use dgelsy or dgesv zMatrix<double> A2(A); bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed when finding Fundamental Matrix!"; zMatrix<double> F(3,3); F(0,Colon())=VT(8,Colon(0,2)); F(1,Colon())=VT(8,Colon(3,5)); F(2,Colon())=VT(8,Colon(6,8)); //3. make order to 2 // Matrix3x3d F1; // Dress(F1)=F; // zout<<"F="<<F1<<endl; svdres=SVD(F,U,S,VT); ZCHECK(svdres)<<"SVD failed when finding Fundamental Matrix!"; zMatrix<double> DS(Diag(S)); DS(2,2)=0; Matrix3x3d F2; Dress(F2)=U*DS*VT; // zout<<"F'="<<F2<<endl; //4. restore *this=norl.GetT().Transposed()*F2*norr.GetT(); *this/=(*this)(2,2); //CHECK // for (zuint i=0; i<ls.size(); i++) // { // zout<<"CHECK X'FX="<<(ToHomogeneous(ls[i])*(*this)).Dot(ToHomogeneous(rs[i]))<<endl; // zout<<"CHECK residue="<<Residue(ls[i],rs[i])<<endl; // } return true; } int FundamentalMat::Create8RANSAC(const vector<Vector2d> &ls, const vector<Vector2d> &rs, const double outlier_threshold, IterExitCond<double> &cond) { cond.Reset(); int inliers, max_inliers=0; RANSACPicker<8> picker(0,ls.size()-1); Matrix3x3d best_me; do { //randomly pick 8 point Vector<8,int> pick=picker.Pick(); //calculate f vector<Vector2d> lls,rrs; for (zuint i=0; i<8; i++) { lls.push_back(ls[pick[i]]); rrs.push_back(rs[pick[i]]); } Create8(lls,rrs); //check inliers inliers=0; for (zuint i=0; i<ls.size(); i++) { double resi=Residue(ls[i],rs[i]); // zout<<i<<" residue "<<resi<<endl; if (resi<outlier_threshold) inliers++; } if (inliers>max_inliers) { best_me=(*this); max_inliers=inliers; } }while(!cond.IsSatisfied(double(ls.size()-inliers)/ls.size())); Matrix3x3d::operator=(best_me); //refine by all inliers vector<Vector2d> lls,rrs; for (zuint i=0; i<ls.size(); i++) { if (Residue(ls[i],rs[i])<outlier_threshold) { lls.push_back(ls[i]); rrs.push_back(rs[i]); } } if (lls.size()>=8) Create8(lls,rrs); return inliers; } int FundamentalMat::Create8RANSAC(PairData<double> &data, const double outlier_threshold, IterExitCond<double> &cond) { const vector<Vector2d> &ls=data.pos2ds[1],&rs=data.pos2ds[0]; Create8RANSAC(ls,rs,outlier_threshold,cond); int x=0; for (zuint i=0; i<ls.size(); i++) { data.ferror[i]=Residue(ls[i],rs[i]); if (data.ferror[i]>outlier_threshold) data.status[i]=POINT_BADF; else x++; } return x; } bool FundamentalMat::CalEpipoles(Vector3d &left, Vector3d &right) { zMatrixd A(Dress(*this)),U,S,VT; bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed when calculating epipoles!"; Dress(left)=Trans(VT(2,Colon())); Dress(right)=U(Colon(),2); return true; } double FundamentalMat::Residue(const Vector2d &l, const Vector2d &r) const { // return abs((ToHomogeneous(l)*(*this)).Dot(ToHomogeneous(r))); Vector3d fl=ToHomogeneous(l)*(*this); Vector3d fr=(*this)*ToHomogeneous(r); double pt=r[0]*fl[0]+r[1]*fl[1]+fl[2]; return (1.0 / (fl[0]*fl[0] + fl[1]*fl[1]) + 1.0 / (fr[0]*fr[0] + fr[1]*fr[1])) * (pt * pt); } ///////////////////////////////////////////////////////////// bool EssentialMat::GetProjection(ProjectionMatd &P, const Vector2d &l, const Vector2d &r) const { ZLOG(ZDEBUG)<<SplitLine("Get Projection From Essential Matrix")<<endl; vector<Vector2d> pos2ds; pos2ds.push_back(r); pos2ds.push_back(l); vector<ProjectionMatd> PP(2,ProjectionMatd()); PP[0].Identical(); //SVD of E to find R zMatrix<double> A(Dress(*this)),U,S,VT; bool svdres=SVD(A,U,S,VT); ZCHECK(svdres)<<"SVD failed when decompose E"; double s=Sqrt(Sqrt(S(0,0)*S(1,0))); ZLOG(ZDEBUG)<<"S=\n"<<S<<endl; //two possibilities of R Matrix3x3d W(0,-1,0, 1,0,0, 0,0,1),Z(0,1,0, -1,0,0, 0,0,0); Matrix3x3d R[4]; Dress(R[0])=U*Dress(W)*VT; R[0]*=Sign(R[0].Determinant()); //if R=-R, everything will fit, but camera direction will flip, which impossible (two cameras wouldn't shot same points) R[1]=R[0]; Dress(R[2])=U*Trans(Dress(W))*VT; R[2]*=Sign(R[2].Determinant()); R[3]=R[2]; ZLOG(ZDEBUG)<<"R1=\n"<<R[0]<<endl; ZLOG(ZDEBUG)<<"R2=\n"<<R[2]<<endl; //t=u3 Vector3d u3(U(0,2),U(1,2),U(2,2)); Vector3d t[4]={u3,-u3,u3,-u3}; ZLOG(ZDEBUG)<<"t="<<t[0]<<endl; //choose ZLOG(ZDEBUG)<<"l="<<l<<" r="<<r<<endl; int chosen; for (zuint i=0; i<4; i++) { bool good=true; PP[1].SetRT(R[i],t[i]); PP[1].MakeP(); ZLOG(ZDEBUG)<<"CC="<<PP[1].CameraCenter()<<endl; ZLOG(ZDEBUG)<<"PR="<<PP[1].PrincipalRay()<<endl; Vector3d X=Triangulator::LinearTriangulate(PP,pos2ds); ZLOG(ZDEBUG)<<"X="<<X<<endl; string msg; if (X[2]>0) msg<<i<<" X is in front of P1\t"; else { good=false; msg<<i<<" X is NOT in front of P1\t"; } //camera center and orientation of camera double tmp=PP[1].PrincipalRay().Dot(X-PP[1].CameraCenter()); if (tmp>0) msg<<i<<" X is in front of P2"; else { good=false; msg<<i<<" X is NOT in front of P2"; } if (good) chosen=i; ZLOG(ZDEBUG)<<msg<<endl; } ZLOG(ZDEBUG)<<endl; ZLOG(ZDEBUG)<<chosen<<" is chosen\n"; ZLOG(ZVERBOSE)<<"R=\n"<<R[chosen]<<endl; ZLOG(ZVERBOSE)<<"t="<<t[chosen]<<endl; P.SetRT(R[chosen],t[chosen]); P.MakeP(); return true; } }
zzz-engine
zzzEngine/zVision/zVision/SfM/FundamentalMat.cpp
C++
gpl3
6,368
#pragma once #include <zMat.hpp> #include <Math/Vector.hpp> #include <Utility/IOInterface.hpp> #include <Utility/HasFlag.hpp> #include <Utility/STLVector.hpp> #include "../Feature/SIFTKeys.hpp" #include <Xml/RapidXMLNode.hpp> #include "ProjectionMat.hpp" namespace zzz{ template<typename DataType> class ProjectionMat; enum{POINT_GOOD = 0,POINT_BADF, POINT_BADP}; enum{CAMERA_GOOD = 0, CAMERA_UNKNOWN}; static const zuint32 SD_IMAGE = 0x00000001; static const zuint32 SD_CAMERA = 0x00000002; static const zuint32 SD_POINT = 0x00000004; static const zuint32 SD_SIFTKEY = 0x00000010; static const zuint32 SD_SIFTMATCH = 0x00000020; static const zuint32 SD_SFMPAIR = 0x00000100; static const zuint32 SD_TRIPLANE = 0x00001000; static const zuint32 SD_ALL = 0xffffffff; template<typename DataType> class PairData { public: ProjectionMat<DataType> cameras[2]; STLVector<int> oriidx; STLVector<int> ptidx[2]; STLVector<Vector<2,DataType> > pos2ds[2]; STLVector<Vector<3,DataType> > pos3ds; STLVector<double> ferror; STLVector<double> perror; STLVector<zuint> status; }; template<typename DataType=float> class SceneData { public: const double Version; SceneData():Version(5.0){} ///////////////////////////reconstructed points struct Point2D { static const zuint32 BAD; typedef Vector<2,DataType> CoordXY; Point2D():img_id(BAD),pos2d(0),status(POINT_GOOD){} Point2D(int img_id_, const Vector<2,DataType> &pos2d_, int pt_idx_) : img_id(img_id_),pos2d(pos2d_),pt_idx(pt_idx_),status(POINT_GOOD){} zint32 img_id; zint32 pt_idx; Vector<2,DataType> pos2d; zuint32 status; }; struct Point { Point():pos3d(0),ferror(0),perror(0),status(POINT_GOOD){} explicit Point(const Vector<3,DataType> &pos3d_):pos3d(pos3d_),ferror(0),perror(0),status(POINT_GOOD){} Vector<3,DataType> pos3d; STLVector<Point2D> pos2ds; DataType ferror; DataType perror; zuint32 status; }; STLVector<Point> points_; ///////////////////////////image information struct ImageInfo { ImageInfo():size(0,0),focal(-1){} ImageInfo(const string &filename_, int sizex, int sizey):filename(filename_),size(sizex,sizey),focal(-1){} string filename; Vector<2,zint32> size; DataType focal; }; STLVector<ImageInfo> imginfos_; ///////////////////////////reconstructed cameras struct CameraInfo { CameraInfo():status(CAMERA_UNKNOWN),k1(0),k2(0){} explicit CameraInfo(const ProjectionMat<DataType> &v):camera(v),status(CAMERA_GOOD),k1(0.0),k2(0.0){} ProjectionMat<DataType> camera; DataType k1,k2; zuint32 status; }; STLVector<CameraInfo> cameras_; ///////////////////////////sift feature points STLVector<SIFTKeys> siftkeys_; ///////////////////////////siftkey pair matching struct SIFTMatch { typedef pair<zuint32, zuint32> PtIdx; typedef pair<Vector<2,DataType>, Vector<2,DataType> > Matches; static const zuint32 BAD; zuint32 id1,id2; STLVector<PtIdx> ptidx; //Coord_XY STLVector<Matches> matches; }; STLVector<SIFTMatch> siftmatches_; ///////////////////////////SfM camera pair struct SfMPair { int id1,id2; zuint32 matches; zuint32 inliers; Matrix<3,3,DataType> rot; Vector<3,DataType> trans; }; STLVector<SfMPair> sfmpairs_; ///////////////////////////Triangle planes struct TriPlane { Vector3i pts; DataType error; }; STLVector<TriPlane> triplanes_; ////////////////////////////Generator STLVector<string> generators_; void Clear() { points_.clear(); imginfos_.clear(); cameras_.clear(); siftkeys_.clear(); siftmatches_.clear(); sfmpairs_.clear(); triplanes_.clear(); generators_.clear(); } void SaveToFileXml(RapidXMLNode &node, zuint flags=SD_ALL) { node.SetAttribute("Version",Version); if (CheckBit(flags,SD_IMAGE)) { RapidXMLNode imgnode=node.AppendNode("ImageInfoSet"); imgnode.SetAttribute("Number",imginfos_.size()); for (zuint i=0; i<imginfos_.size(); i++) { RapidXMLNode inode=imgnode.AppendNode("ImageInfo"); inode.SetAttribute("ID",i); inode.SetAttribute("FileName",imginfos_[i].filename); inode.SetAttribute("Size",imginfos_[i].size); inode.SetAttribute("Focal",imginfos_[i].focal); } } if (CheckBit(flags,SD_CAMERA)) { RapidXMLNode cameranode=node.AppendNode("CameraSet"); cameranode.SetAttribute("Number",cameras_.size()); for (zuint i=0; i<cameras_.size(); i++) { RapidXMLNode cnode=cameranode.AppendNode("Camera"); cnode.SetAttribute("ID",i); cnode.SetAttribute("K1",cameras_[i].k1); cnode.SetAttribute("K2",cameras_[i].k2); cnode.SetAttribute("Status",cameras_[i].status); cnode.AppendNode("K")<<cameras_[i].camera.K(); cnode.AppendNode("R")<<cameras_[i].camera.R(); cnode.AppendNode("T")<<cameras_[i].camera.T(); cnode.AppendNode("P")<<cameras_[i].camera.P(); } } if (CheckBit(flags,SD_POINT)) { RapidXMLNode pointnode=node.AppendNode("PointSet"); pointnode.SetAttribute("Number",points_.size()); for (zuint i=0; i<points_.size(); i++) { RapidXMLNode pnode=pointnode.AppendNode("Point"); pnode.SetAttribute("Pos3D",points_[i].pos3d); pnode.SetAttribute("F_Error",points_[i].ferror); pnode.SetAttribute("P_Error",points_[i].perror); pnode.SetAttribute("Status",points_[i].status); pnode.SetAttribute("Number",points_[i].pos2ds.size()); for (zuint j=0; j<points_[i].pos2ds.size(); j++) { RapidXMLNode p2node=pnode.AppendNode("Pos2D"); p2node.SetAttribute("ID",points_[i].pos2ds[j].img_id); p2node.SetAttribute("PtIdx",points_[i].pos2ds[j].pt_idx); Vector<2,DataType> pos = points_[i].pos2ds[j].pos2d + Vector<2,DataType>(imginfos_[points_[i].pos2ds[j].img_id].size/2); p2node.SetAttribute("Pos",pos); p2node.SetAttribute("Status",points_[i].pos2ds[j].status); } } } if (CheckBit(flags,SD_SIFTKEY)) { RapidXMLNode siftnode=node.AppendNode("SIFTKeySet"); siftnode.SetAttribute("Number",siftkeys_.size()); for (zuint i=0; i<siftkeys_.size(); i++) { RapidXMLNode ssnode=siftnode.AppendNode("SIFTKeys"); ssnode.SetAttribute("Number",siftkeys_[i].keys_.size()); ssnode.SetAttribute("ID",i); for (zuint j=0; j<siftkeys_[i].keys_.size(); j++) { RapidXMLNode snode=ssnode.AppendNode("SIFTKey"); snode.SetAttribute("X",siftkeys_[i].keys_[j].pos[0]); snode.SetAttribute("Y",siftkeys_[i].keys_[j].pos[1]); snode.SetAttribute("Scale",siftkeys_[i].keys_[j].scale); snode.SetAttribute("Dir",siftkeys_[i].keys_[j].dir); Vector<128,zushort> desc(siftkeys_[i].desc_[j]); snode<<desc; } } } if (CheckBit(flags,SD_SIFTMATCH)) { RapidXMLNode smatchnode=node.AppendNode("SIFTMatchSet"); smatchnode.SetAttribute("Number",siftmatches_.size()); for (zuint i=0; i<siftmatches_.size(); i++) { RapidXMLNode ssnode=smatchnode.AppendNode("SIFTMatches"); ssnode.SetAttribute("Number",siftmatches_[i].matches.size()); ssnode.SetAttribute("ID1",siftmatches_[i].id1); ssnode.SetAttribute("ID2",siftmatches_[i].id2); for (zuint j=0; j<siftmatches_[i].matches.size(); j++) { RapidXMLNode mnode=ssnode.AppendNode("Match"); mnode.SetAttribute("P1",siftmatches_[i].matches[j].first); mnode.SetAttribute("P2",siftmatches_[i].matches[j].second); mnode.SetAttribute("PtIdx1",siftmatches_[i].ptidx[j].first); mnode.SetAttribute("PtIdx2",siftmatches_[i].ptidx[j].second); } } } if (CheckBit(flags,SD_SFMPAIR)) { RapidXMLNode cpnode=node.AppendNode("SfMPairSet"); cpnode.SetAttribute("Number",sfmpairs_.size()); for (zuint i=0; i<sfmpairs_.size(); i++) { RapidXMLNode cnode=cpnode.AppendNode("SfMPair"); cnode.SetAttribute("ID1",sfmpairs_[i].id1); cnode.SetAttribute("ID2",sfmpairs_[i].id2); cnode.SetAttribute("Matches",sfmpairs_[i].matches); cnode.SetAttribute("Inliers",sfmpairs_[i].inliers); cnode.SetAttribute("Rotation",sfmpairs_[i].rot); cnode.SetAttribute("Translation",sfmpairs_[i].trans); } } if (CheckBit(flags,SD_TRIPLANE)) { RapidXMLNode tripnode=node.AppendNode("TriPlaneSet"); tripnode.SetAttribute("Number",triplanes_.size()); for (zuint i=0; i<triplanes_.size(); i++) { RapidXMLNode tnode=tripnode.AppendNode("TriPlane"); tnode.SetAttribute("Pts",triplanes_[i].pts); tnode.SetAttribute("Error",triplanes_[i].error); } } { RapidXMLNode gsnode=node.AppendNode("Generators"); for (zuint i=0; i<generators_.size(); i++) gsnode.AppendNode("Generator")<<generators_[i]; } } void LoadFromFileXml(RapidXMLNode &node,zuint flags=SD_ALL) { double version=99999; node.GetAttribute("Version",version); if (version>Version) { ZLOG(ZERROR)<<"This is not valid file or a file written by a higher version of me\n"; return; } Clear(); if (CheckBit(flags,SD_IMAGE) && node.HasNode("ImageInfoSet")) { RapidXMLNode imgnode=node.GetNode("ImageInfoSet"); int imgn; imgnode.GetAttribute("Number",imgn); imginfos_.assign(imgn,ImageInfo()); for (RapidXMLNode inode=imgnode.GetFirstNode("ImageInfo");inode.IsValid();inode.GotoNextSibling("ImageInfo")) { int id=FromString<int>(inode.GetAttribute("ID")); imginfos_[id].filename=inode.GetAttribute("FileName"); imginfos_[id].size=FromString<Vector<2,DataType> >(inode.GetAttribute("Size")); inode.GetAttribute("Focal",imginfos_[id].focal); } } if (CheckBit(flags,SD_CAMERA) && node.HasNode("CameraSet")) { RapidXMLNode cameranode=node.GetNode("CameraSet"); int camn; cameranode.GetAttribute("Number",camn); cameras_.assign(camn,CameraInfo()); for (RapidXMLNode cnode=cameranode.GetFirstNode("Camera");cnode.IsValid();cnode.GotoNextSibling("Camera")) { int id=FromString<int>(cnode.GetAttribute("ID")); cnode.GetAttribute("K1",cameras_[id].k1); cnode.GetAttribute("K2",cameras_[id].k2); cnode.GetAttribute("Status",cameras_[id].status); cameras_[id].camera.SetK(FromString<Matrix<3, 3, DataType> >(cnode.GetNode("K").GetText())); cameras_[id].camera.SetRT(FromString<Matrix<3, 3, DataType> >(cnode.GetNode("R").GetText()),\ FromString<Vector<3, DataType> >(cnode.GetNode("T").GetText())); cameras_[id].camera.SetP(FromString<Matrix<3,4,DataType> >(cnode.GetNode("P").GetText())); } } if (CheckBit(flags,SD_POINT) && node.HasNode("PointSet")) { RapidXMLNode pointnode=node.GetNode("PointSet"); int pointn; pointnode.GetAttribute("Number",pointn); points_.reserve(pointn); for (RapidXMLNode pnode=pointnode.GetFirstNode("Point");pnode.IsValid();pnode.GotoNextSibling("Point")) { points_.push_back(Point()); Point &point=points_.back(); pnode.GetAttribute("Pos3D",point.pos3d); pnode.GetAttribute("F_Error",point.ferror); pnode.GetAttribute("P_Error",point.perror); pnode.GetAttribute("Status",point.status); int pos2dn; pnode.GetAttribute("Number",pos2dn); point.pos2ds.reserve(pos2dn); for (RapidXMLNode p2node=pnode.GetFirstNode("Pos2D");p2node.IsValid();p2node.GotoNextSibling("Pos2D")) { Point2D pos2d; p2node.GetAttribute("ID",pos2d.img_id); p2node.GetAttribute("PtIdx",pos2d.pt_idx); pos2d.pos2d=FromString<Vector<2,DataType> >(p2node.GetAttribute("Pos")) - Vector<2,DataType>(imginfos_[pos2d.img_id].size/2); p2node.GetAttribute("Status",pos2d.status); point.pos2ds.push_back(pos2d); } } } if (CheckBit(flags,SD_SIFTKEY) && node.HasNode("SIFTKeySet")) { RapidXMLNode siftnode=node.GetNode("SIFTKeySet"); int setn; siftnode.GetAttribute("Number",setn); siftkeys_.assign(setn,SIFTKeys()); for (RapidXMLNode ssnode=siftnode.GetNode("SIFTKeys");ssnode.IsValid();ssnode.GotoNextSibling("SIFTKeys")) { int id; ssnode.GetAttribute("ID",id); SIFTKeys &siftkeys=siftkeys_[id]; int keyn; ssnode.GetAttribute("Number",keyn); siftkeys.keys_.reserve(keyn); siftkeys.desc_.reserve(keyn); for (RapidXMLNode snode=ssnode.GetNode("SIFTKey");snode.IsValid();snode.GotoNextSibling("SIFTKey")) { SIFTKey key; snode.GetAttribute("X",key.pos[0]); snode.GetAttribute("Y",key.pos[1]); snode.GetAttribute("Scale",key.scale); snode.GetAttribute("Dir",key.dir); siftkeys.keys_.push_back(key); Vector<128,zushort> desc=FromString<Vector<128,zushort> >(snode.GetText()); siftkeys.desc_.push_back(Vector<128,zuchar>(desc)); } } } if (CheckBit(flags,SD_SIFTMATCH) && node.HasNode("SIFTMatchSet")) { RapidXMLNode smatchnode=node.GetNode("SIFTMatchSet"); int setn; smatchnode.GetAttribute("Number",setn); siftmatches_.reserve(setn); for (RapidXMLNode ssnode=smatchnode.GetNode("SIFTMatches");ssnode.IsValid();ssnode.GotoNextSibling("SIFTMatches")) { siftmatches_.push_back(SIFTMatch()); SIFTMatch &match=siftmatches_.back(); ssnode.GetAttribute("ID1",match.id1); ssnode.GetAttribute("ID2",match.id2); int matchn; ssnode.GetAttribute("Number",matchn); match.matches.reserve(matchn); match.ptidx.reserve(matchn); for (RapidXMLNode mnode=ssnode.GetNode("Match");mnode.IsValid();mnode.GotoNextSibling("Match")) { pair<Vector<2,DataType>,Vector<2,DataType> > p; mnode.GetAttribute("P1",p.first); mnode.GetAttribute("P2",p.second); match.matches.push_back(p); pair<int,int> ptidx; mnode.GetAttribute("PtIdx1",ptidx.first); mnode.GetAttribute("PtIdx2",ptidx.second); match.ptidx.push_back(ptidx); } } } if (CheckBit(flags,SD_SFMPAIR) && node.HasNode("SfMPairSet")) { RapidXMLNode cpnode=node.GetNode("SfMPairSet"); int setn; cpnode.GetAttribute("Number",setn); sfmpairs_.reserve(setn); for (RapidXMLNode cnode=cpnode.GetNode("SfMPair");cnode.IsValid();cnode.GotoNextSibling("SfMPair")) { SfMPair p; cnode.GetAttribute("ID1",p.id1); cnode.GetAttribute("ID2",p.id2); cnode.GetAttribute("Matches",p.matches); cnode.GetAttribute("Inliers",p.inliers); cnode.GetAttribute("Rotation",p.rot); cnode.GetAttribute("Translation",p.trans); sfmpairs_.push_back(p); } } if (CheckBit(flags,SD_TRIPLANE) && node.HasNode("TriPlaneSet")) { RapidXMLNode tripnode=node.GetNode("TriPlaneSet"); int setn; tripnode.GetAttribute("Number",setn); for (RapidXMLNode tnode=tripnode.GetNode("TriPlane");tnode.IsValid();tnode.GotoNextSibling("TriPlane")) { TriPlane tri; tnode.GetAttribute("Pts",tri.pts); tnode.GetAttribute("Error",tri.error); triplanes_.push_back(tri); } } if (node.HasNode("Generators")) { RapidXMLNode gsnode=node.GetNode("Generators"); for (RapidXMLNode gnode=gsnode.GetNode("Generator");gnode.IsValid();gnode.GotoNextSibling("Generator")) generators_.push_back(string(gnode.GetText())); } } void SaveBDL(const string &filename) { ofstream fo(filename,ios_base::out|ios_base::binary); ZCHECK(fo.good())<<"Cannot open file "<<filename<<endl; fo<<"VMBundleAdjustement {\n\n"; fo<<"xImageSize "<<imginfos_[0].size[0]<<" yImageSize "<<imginfos_[0].size[1]<<"\n"; fo<<"ArePointOk 1 NbViewOk "<<cameras_.size()<<" NbPointOk "<<points_.size()<<"\n"; int nbinlier=0; for (zuint i=0; i<points_.size(); i++) nbinlier+=points_[i].pos2ds.size(); fo<<"NbInlier "<<nbinlier<<" NbOutlier 0 MaxSquareErrorDistance 4 Lambda 1e-06 OldChi2 0 NewChi2 0\n"; fo<<"\n"; for (zuint i=0; i<cameras_.size(); i++) { fo<<"Camera "<<i<<" {\nNumber "<<i<<" Flag 1 Param 1\n"; fo<<cameras_[i].camera.P()<<"\n\n}\n\n"; } for (zuint i=0; i<points_.size(); i++) { fo<<"Point "<<i<<" { "<<ToHomogeneous(points_[i].pos3d)<<" Flag 1 Param 3\n"; for (zuint j=0; j<points_[i].pos2ds.size(); j++) { fo<<points_[i].pos2ds[j].img_id<<" 1 "; if (imginfos_.size()>1) fo<<points_[i].pos2ds[j].pos2d + Vector<2,DataType>(imginfos_[points_[i].pos2ds[j].img_id].size)/2<<' '; else fo<<points_[i].pos2ds[j].pos2d + Vector<2,DataType>(imginfos_[0].size)/2<<' '; } fo<<" }\n"; } fo<<"}\n"; fo.close(); } void BDLCameraDecompose(Matrix<3,4,DataType> &P, Matrix<3,3,DataType> &K, Matrix<3,3,DataType> &R, Vector<3,DataType> &T) { Vector<3,DataType> q1(P.Row(0)); Vector<3,DataType> q2(P.Row(1)); Vector<3,DataType> q3(P.Row(2)); DataType p = 1/(q3.Len()); R.Row(2)= p * q3; //r3 = p * q3; DataType u0 = p * p * (q1.Dot(q3)); DataType v0 = p * p * (q2.Dot(q3)); DataType alpha_u = sqrt(p*p*(q1.Dot(q1)) - u0*u0); DataType alpha_v = sqrt(p*p*(q2.Dot(q2)) - v0*v0); R.Row(0)= p * (q1 - (u0*q3))/alpha_u; //r1 = p * (q1 - (u0*q3))/alpha_u; R.Row(1)= p * (q2 - (v0*q3))/alpha_v; //r2 = p * (q2 - (v0*q3))/alpha_v; T[2] = p * P(2,3); T[0] = p * (P(0,3) - u0*P(2,3)) / alpha_u; T[1] = p * (P(1,3) - v0*P(2,3)) / alpha_v; K.Identical(); K(0,0)=alpha_u; K(1,1)=alpha_v; K(0,2)=u0; K(1,2)=v0; // Check whether the determinant of the rotation of the extrinsic is positive one. if (R.Determinant() < 0) { Matrix<3,4,DataType> E; Dress(E)=(Dress(-R),Dress(-T)); Matrix<3,4,DataType> P2=K*E; // Redo the decomposition. q1=Vector<3,DataType>(P2(0,0),P2(0,1),P2(0,2)); q2=Vector<3,DataType>(P2(1,0),P2(1,1),P2(1,2)); q3=Vector<3,DataType>(P2(2,0),P2(2,1),P2(2,2)); p = 1/(q3.Len()); R.Row(2)= p * q3; //r3 = p * q3; u0 = p * p * FastDot(q1,q3); v0 = p * p * FastDot(q2,q3); alpha_u = Sqrt(p*p*FastDot(q1,q1) - u0*u0); alpha_v = Sqrt(p*p*FastDot(q2,q2) - v0*v0); R.Row(0)= p * (q1 - (u0*q3))/alpha_u; //r1 = p * (q1 - (u0*q3))/alpha_u; R.Row(1)= p * (q2 - (v0*q3))/alpha_v; //r2 = p * (q2 - (v0*q3))/alpha_v; T[2] = p * P(2,3); T[0] = p * (P(0,3) - u0*P(2,3)) / alpha_u; T[1] = p * (P(1,3) - v0*P(2,3)) / alpha_v; K.Identical(); K(0,0)=alpha_u; K(1,1)=alpha_v; K(0,2)=u0; K(1,2)=v0; } } void LoadBDL(const string &filename) { Clear(); BraceFile bf; ZCHECK(bf.LoadFile(filename)); // Convert BraceNode bundleNode=bf.GetFirstNode("VMBundleAdjustement"); string tmp; int ncam, npoint; { istringstream iss(bundleNode.GetFirstNodeInclude("NbViewOk").GetText()); while(!iss.fail()) { iss>>tmp; if (tmp=="NbViewOk") iss>>ncam; if (tmp=="NbPointOk") iss>>npoint; } } cameras_.reserve(ncam); for (BraceNode cameraNode=bundleNode.GetFirstNodeInclude("Camera");cameraNode.IsValid();cameraNode.GotoNextSiblingInclude("Camera")) { string data; cameraNode.GetChildrenText(data); istringstream iss(data); cameras_.push_back(SceneData<DataType>::CameraInfo()); iss>>tmp>>tmp>>tmp>>tmp>>tmp>>tmp; Matrix<3,4,DataType> P; iss>>P; Matrix<3,3,DataType> K,R; Vector<3,DataType> T; BDLCameraDecompose(P,K,R,T); imginfos_.push_back(SceneData<DataType>::ImageInfo()); imginfos_.back().size=Vector2i(K(0,2)*2,K(1,2)*2); imginfos_.back().focal=(K(0,0)+K(1,1))/2.0; // K(0,2)=0; // K(1,2)=0; cameras_.back().camera.SetK(K); cameras_.back().camera.SetRT(R,T); cameras_.back().camera.MakeP(); cameras_.back().status=CAMERA_GOOD; } points_.reserve(npoint); for (BraceNode pointNode=bundleNode.GetFirstNodeInclude("Point");pointNode.IsValid();pointNode.GotoNextSiblingInclude("Point")) { string data; pointNode.GetChildrenText(data); istringstream iss(data); points_.push_back(SceneData<DataType>::Point()); string tmp; Vector<4,DataType> X; int id,status; Vector<2,DataType> x; iss>>X>>tmp>>status>>tmp>>tmp; points_.back().pos3d=FromHomogeneous(X); points_.back().status=status==1?POINT_GOOD:POINT_BADP; while(true) { iss>>id>>status>>x; if (iss.fail()) break; points_.back().pos2ds.push_back(SceneData<DataType>::Point2D()); points_.back().pos2ds.back().status = status==1?POINT_GOOD:POINT_BADP; points_.back().pos2ds.back().img_id = id; points_.back().pos2ds.back().pos2d = x-Vector<2,DataType>(imginfos_[id].size/2); } } } void TakeOutPair(PairData<DataType> &data, int x0, int x1) { data.cameras[0]=cameras_[x0].camera; data.cameras[1]=cameras_[x1].camera; for (zuint i=0; i<points_.size(); i++) { Point2D *p0=NULL,*p1=NULL; for (zuint j=0; j<points_[i].pos2ds.size(); j++) { if (points_[i].pos2ds[j].img_id==x0) p0=&(points_[i].pos2ds[j]); else if (points_[i].pos2ds[j].img_id==x1) p1=&(points_[i].pos2ds[j]); } if (p0!=NULL && p1!=NULL) { data.oriidx.push_back(i); data.pos2ds[0].push_back(p0->pos2d); data.pos2ds[1].push_back(p1->pos2d); data.ptidx[0].push_back(p0->pt_idx); data.ptidx[1].push_back(p1->pt_idx); data.pos3ds.push_back(points_[i].pos3d); data.ferror.push_back(points_[i].ferror); data.perror.push_back(points_[i].perror); data.status.push_back(points_[i].status); } } } void PutBackPair(const PairData<DataType> &data, int x0, int x1) { cameras_[x0].camera=data.cameras[0]; cameras_[x1].camera=data.cameras[1]; for (zuint i=0; i<data.pos3ds.size(); i++) { Point2D *p0=NULL,*p1=NULL; int idx=data.oriidx[i]; for (zuint j=0; j<points_[idx].pos2ds.size(); j++) { if (points_[i].pos2ds[j].img_id==x0) p0=&(points_[i].pos2ds[j]); else if (points_[i].pos2ds[j].img_id==x1) p1=&(points_[i].pos2ds[j]); } if (p0!=NULL && p1!=NULL) { points_[idx].pos3d=data.pos3ds[i]; points_[idx].ferror=data.ferror[i]; points_[idx].perror=data.perror[i]; points_[idx].status=data.status[i]; } } } }; const zuint32 SceneData<zfloat32>::Point2D::BAD = MAX_UINT32; const zuint32 SceneData<zfloat32>::SIFTMatch::BAD = MAX_UINT32; typedef SceneData<zfloat32> SceneDataf64; }
zzz-engine
zzzEngine/zVision/zVision/SfM/SceneData.hpp
C++
gpl3
24,016
#pragma once #include <Image/Image.hpp> //to generate textures according to a homography transformation //input original point on the original image and corresponding projection point on a new image //it will fill the new image by a homography transformation namespace zzz{ template<typename T> class TextureGenerator { public: TextureGenerator(void){} ~TextureGenerator(void){} void SetImage(const Image<T> &r){img_=r;} //ATTENTION: coordinate is homogenous and should be (r,c,w) void Cut(const vector<Vector3d> &orip, const vector<Vector3d> &prjp, Image<T> &tex) { Homography h; h.Create(orip,prjp); for (zuint r=0; r<tex.Rows(); r++) for (zuint c=0; c<tex.Cols(); c++) { Vector3d prj(r,c,1); Vector3d ori=h.ToA(prj); tex.At(r,c)=img_.Interpolate(ori[0],ori[1]); } } private: Image<T> img_; }; }
zzz-engine
zzzEngine/zVision/zVision/SfM/TextureGenerator.hpp
C++
gpl3
889
#include "SceneDataIOObject.hpp"
zzz-engine
zzzEngine/zVision/zVision/SfM/SceneDataIOObject.cpp
C++
gpl3
34
#include "SmallRigid.hpp" #include <zMat.hpp> #include <Utility/Log.hpp> #include "../VisionTools.hpp" namespace zzz{ bool SmallRigid::Create(const vector<Vector2d> &pa, const vector<Vector2d> &pb) { ZCHECK_EQ(pa.size(), pb.size()); zuint n=pa.size(); zMatrix<double> A(Zerosd(n*2,3)); zVector<double> B(n*2); zuint cur=0; for (zuint i=0; i<n; i++) { const Vector2d &a=pa[i],&b=pb[i]; A(cur,0)=-a[1]; A(cur,1)=1; B(cur)=b[0]; cur++; A(cur,0)=a[0]; A(cur,1)=1; B(cur)=b[1]-a[1]; cur++; } zMatrix<double> ATA(Trans(A)*A); if (!Invert(ATA)) return false; zVector<double> X(ATA*Trans(A)*B); double theta = asin(X(0)); Hab_(0,0)=cos(theta); Hab_(0,1)=-sin(theta); Hab_(0,2)=X(1); Hab_(1,0)=sin(theta); Hab_(1,1)=cos(theta); Hab_(1,2)=X(2); Hba_=Hab_.Inverted(); return true; } }
zzz-engine
zzzEngine/zVision/zVision/SfM/SmallRigid.cpp
C++
gpl3
866
#pragma once #include "Renderer/CutRenderer.hpp" #include "Renderer/ImageListRenderer.hpp" #include "Renderer/MatchRenderer.hpp" #include "TensorVoting/TensorVoting.hpp" #include "Feature/SIFT.hpp" #include "Feature/SIFTKeys.hpp" //#include "Feature/SIFTMatcher.hpp" //used ANN_char, will have some redefinition warning,,, #include "SfM/SceneData.hpp" #include "SfM/Triangulator.hpp" #include "SfM/Homography.hpp" #include "SfM/Affine.hpp" #include "SfM/SmallRigid.hpp" #include "SfM/TextureGenerator.hpp" #include "SfM/CoordNormalizer.hpp" #include "SfM/FundamentalMat.hpp" #include "SfM/ProjectionMat.hpp" #include "SfM/FivePointAlgo.hpp" #include "VisionTools.hpp" #include "VisionAlgo/ImageMultiCut.hpp" #include "VisionAlgo/EdgeTracer.hpp"
zzz-engine
zzzEngine/zVision/zVision/zVision.hpp
C++
gpl3
784
#pragma once #include <3rdparty/MaxFlow.hpp> #include <Math/Random.hpp> #include <boost/function.hpp> #include <Math/IterExitCond.hpp> namespace zzz{ #ifdef ZZZ_LIB_GCO template<typename IMGT, typename GRHT=IMGT> class ImageMultiCut { public: typedef boost::function<GRHT (const IMGT &t, const IMGT &p, zuint pos)> CalTLink; typedef boost::function<GRHT (const IMGT &p1, const IMGT &p2)> CalNLink; ImageMultiCut(CalTLink calTLink, CalNLink calNLink, const IterExitCond<GRHT> &cond) :CalTLink_(calTLink),CalNLink_(calNLink),cond_(cond) {} void Expansion(const Image<IMGT> &img, const vector<IMGT> &term, Array<2,zuint> &labels) { zuint labeln=term.size(); if (labels.Size()!=img.Size()) { ZLOGI << "randomly init labels\n"; labels.SetSize(img.Size()); RandomInteger<zuint> rand(0,labeln-1); for (zuint i=0; i<labels.size(); i++) labels[i]=rand.Rand(); } //alpha_expansion cond_.Reset(); int iteration=0; int changed; do { changed=0; for (zuint alpha=0;alpha<labeln;alpha++) { //form a new alpha cut MaxFlow<GRHT>::TLinks tlinks; //ori node for (zuint i=0; i<img.size(); i++) { if (labels[i]==alpha) tlinks.push_back(make_pair(CalTLink_(term[alpha],img[i],i),numeric_limits<GRHT>::max())); else tlinks.push_back(make_pair(CalTLink_(term[alpha],img[i],i),CalTLink_(term[labels[i]],img[i],i))); } //auxiliary node and NLinks MaxFlow<GRHT>::NLinks nlinks; for (zuint r=0; r<img.Rows(); r++) for (zuint c=0; c<img.Cols(); c++) { zuint pos1=labels.ToIndex(Vector2ui(r,c)); if (c!=img.Cols()-1) {//right link zuint pos2=labels.ToIndex(Vector2ui(r,c+1)); float alink1=CalNLink_(term[labels[pos1]],term[alpha]); float alink2=CalNLink_(term[alpha],term[labels[pos2]]); if ((labels[pos1]==alpha && labels[pos2]!=alpha) || (labels[pos1]!=alpha && labels[pos2]==alpha)) { //add an auxiliary node tlinks.push_back(make_pair(GRHT(0),CalNLink_(term[labels[pos1]],term[labels[pos2]]))); zuint apos=tlinks.size()-1; nlinks.push_back(make_pair(make_pair(pos1,apos),make_pair(alink1,alink1))); nlinks.push_back(make_pair(make_pair(pos2,apos),make_pair(alink2,alink2))); } else { //normal edge nlinks.push_back(make_pair(make_pair(pos1,pos2),make_pair(alink1,alink2))); } } if (r!=img.Rows()-1) { //down link zuint pos2=labels.ToIndex(Vector2ui(r+1,c)); float alink1=CalNLink_(term[labels[pos1]],term[alpha]); float alink2=CalNLink_(term[alpha],term[labels[pos2]]); if ((labels[pos1]==alpha && labels[pos2]!=alpha) || (labels[pos1]!=alpha && labels[pos2]==alpha)) { //add an auxiliary node tlinks.push_back(make_pair(GRHT(0),CalNLink_(term[labels[pos1]],term[labels[pos2]]))); zuint apos=tlinks.size()-1; nlinks.push_back(make_pair(make_pair(pos1,apos),make_pair(alink1,alink1))); nlinks.push_back(make_pair(make_pair(pos2,apos),make_pair(alink2,alink2))); } else { //normal edge nlinks.push_back(make_pair(make_pair(pos1,pos2),make_pair(alink1,alink2))); } } } mf_.CalMaxFlow(nlinks,tlinks); //check if changed for (zuint i=0; i<img.size(); i++) if (mf_.InSinkSet(i) && labels[i]!=alpha) { //changed labels[i]=alpha; changed++; } ZLOGI << "alpha expansion: changed "<<changed<<" iteration: "<<iteration<<" alpha: "<<alpha<<'/'<<labeln<<endl; } iteration++; } while(!cond_.IsSatisfied(changed)); } void Swap(const Image<IMGT> &img, const vector<GRHT> &term, Array<2,zuint> &labels) { zuint labeln=term.size(); if (labels.Size()!=img.Size()) { zout<<"randomly init labels\n"; labels.SetSize(img.Size()); RandomInteger<zuint> rand(0,labeln-1); for (zuint i=0; i<labels.size(); i++) labels[i]=rand.Rand(); } //alpha-beta swap int iteration=0; int lastchange=MAX_INT; int changed; cond_.Reset(); do { changed=0; for (zuint alpha=0;alpha<labeln-1;alpha++) for (zuint beta=alpha+1;beta<labeln;beta++) { Array<2,int> oripos(img.Size()); oripos=-1; //tlinks MaxFlow<GRHT>::TLinks tlinks; for (zuint i=0; i<img.size(); i++) { if (labels[i]!=alpha && labels[i]!=beta) continue; //keep only alpha or beta GRHT t_alpha=CalTLink_(term[alpha],img[i],i); GRHT t_beta=CalTLink_(term[beta],img[i],i); Vector2ui curpos=labels.ToIndex(i); if (curpos[0]>0) { zuint label=labels(Vector2ui(curpos[0]-1,curpos[1])); if (label!=alpha && label!=beta) { t_alpha+=CalNLink_(term[alpha],term[label]); t_beta+=CalNLink_(term[beta],term[label]); } } if (curpos[1]>0) { zuint label=labels(Vector2ui(curpos[0],curpos[1]-1)); if (label!=alpha && label!=beta) { t_alpha+=CalNLink_(term[alpha],term[label]); t_beta+=CalNLink_(term[beta],term[label]); } } if (curpos[0]<img.Rows()-1) { zuint label=labels(Vector2ui(curpos[0]+1,curpos[1])); if (label!=alpha && label!=beta) { t_alpha+=CalNLink_(term[alpha],term[label]); t_beta+=CalNLink_(term[beta],term[label]); } } if (curpos[1]<img.Cols()-1) { zuint label=labels(Vector2ui(curpos[0],curpos[1]+1)); if (label!=alpha && label!=beta) { t_alpha+=CalNLink_(term[alpha],term[label]); t_beta+=CalNLink_(term[beta],term[label]); } } tlinks.push_back(make_pair(t_alpha,t_beta)); oripos[i]=tlinks.size()-1; //record ori pos } //NLinks MaxFlow<GRHT>::NLinks nlinks; float link=CalNLink_(term[labels[alpha]],term[labels[beta]]); for (zuint r=0; r<img.Rows(); r++) for (zuint c=0; c<img.Cols(); c++) { zuint pos1=labels.ToIndex(Vector2ui(r,c)); if (labels[pos1]!=alpha && labels[pos1]!=beta) continue; if (c!=img.Cols()-1) { //right link zuint pos2=labels.ToIndex(Vector2ui(r,c+1)); if ((labels[pos2]==alpha || labels[pos2]==beta)) nlinks.push_back(make_pair(make_pair(zuint(oripos[pos1]),zuint(oripos[pos2])),make_pair(link,link))); } if (r!=img.Rows()-1) { //down link zuint pos2=labels.ToIndex(Vector2ui(r+1,c)); if ((labels[pos2]==alpha || labels[pos2]==beta)) nlinks.push_back(make_pair(make_pair(zuint(oripos[pos1]),zuint(oripos[pos2])),make_pair(link,link))); } } mf_.CalMaxFlow(nlinks,tlinks); //check if changed for (zuint i=0; i<img.size(); i++) { if (oripos[i]==-1) continue; if (mf_.InSinkSet(oripos[i]) && labels[i]!=alpha) { //changed labels[i]=alpha; changed++; } if (mf_.InSourceSet(oripos[i]) && labels[i]!=beta) { //changed labels[i]=beta; changed++; } } } ZLOGI<<"alpha-beta swap: round changed "<<changed<<" iteration: "<<iteration++; } while(!cond_.IsSatisfied(changed)); } private: CalTLink CalTLink_; CalNLink CalNLink_; MaxFlow<GRHT> mf_; IterExitCond<GRHT> cond_; }; #endif }
zzz-engine
zzzEngine/zVision/zVision/VisionAlgo/ImageMultiCut.hpp
C++
gpl3
7,923
#pragma once #include <Image/Image.hpp> #include <Algorithm/FibonacciHeap.hpp> //find a path between two points in a image //the path will track along the edges in the image //before track, call Prepare() to prepare //use SetStart() to set the startpoint //Repetitively call FindPath() to track, used DP so will not be slow even if the image is large namespace zzz{ class EdgeTracer { public: EdgeTracer(void); ~EdgeTracer(void); //mask, 1 to indicate edge region void SetMask(const Image<zuchar>& mask); void ClearMask(); //call before process new image void Prepare(const Imagef &ori); void Prepare(const Image3f &ori); void Prepare(const Image4f &ori); //return idx of the nearest lowest link position //search range is defined by optrange_ int OptimizeClick(int pos); Vector2ui OptimizeClick(const Vector2ui &pos); //set new start point void SetStart(int start); void SetStart(const Vector2ui &start); //after setting start, call FindPath real-time, data will be saved so wont be slow //data wont delete before next SetStart void FindPath(int end, vector<int>& backpath); void FindPath(const Vector2ui &end, vector<Vector2ui>& backpath); int optrange_; private: void afterPrepare(); //calculate links zzz::Array<2,Vector<8,float> > links_; float maxlink_; //start point int start_; //Fibonacci Heap for Dijkstra's algorithm struct Fibdata { float cost; int pos; bool operator<(const Fibdata& other)const {return cost<other.cost;} }; FibonacciHeap<Fibdata> heap; //data for each pixel struct PathNode { FibonacciHeap<Fibdata>::NodeType* node; float cost; int backpath; int status; //0: unchecked, 1: checking, 2: checked }; Array<2,PathNode> pathmap; //mask Image<zuchar> mask_; }; }
zzz-engine
zzzEngine/zVision/zVision/VisionAlgo/EdgeTracer.hpp
C++
gpl3
1,881
#include "EdgeTracer.hpp" namespace zzz{ EdgeTracer::EdgeTracer(void) { start_=-1; optrange_=5; } EdgeTracer::~EdgeTracer(void) { } //link direction //3 2 1 //7 p 0 //6 5 4 //only calculate 1 2 3 7 and set 6 5 4 0 accordingly void EdgeTracer::Prepare(const Imagef &ori) { const float SQRT2=Sqrt(2.0f); links_.SetSize(ori.Size()); memset(links_.Data(),0,sizeof(Vector<8,float>)*links_.size()); maxlink_=-MAX_FLOAT; for (zuint r=0; r<ori.Rows(); r++) for (zuint c=0; c<ori.Cols(); c++) { if (r!=0 && c!=ori.Cols()-1) { //link(1)=(p(2)-p(0))/sqrt(2) float link=(ori.At(r-1,c)-ori.At(r,c+1))/SQRT2; links_.At(r,c)[1]=links_.At(Vector2ui(r-1,c+1))[6]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0 && c!=ori.Cols()-1) { //link(2)=(p(1)/2+p(0)-p(3)/2-p(7))/2 float link=(ori.At(r-1,c+1)/2+ori.At(r,c+1)-ori.At(r-1,c-1)/2-ori.At(r,c-1))/2; links_.At(r,c)[2]=links_.At(r-1,c)[5]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0) { //link(3)=(p(2)-p(7))/sqrt(2) float link=(ori.At(r-1,c)-ori.At(r,c-1))/SQRT2; links_.At(r,c)[3]=links_.At(r-1,c-1)[4]=link; if (maxlink_<link) maxlink_=link; } if (c!=0 && r!=0 && r!=ori.Rows()-1) { //link(7)=(p(3)/2+p(2)-p(6)/2-p(5))/2 float link=(ori.At(r-1,c-1)/2+ori.At(r-1,c)-ori.At(r+1,c-1)/2-ori.At(r+1,c))/2; links_.At(Vector2ui(r,c))[7]=links_.At(Vector2ui(r,c-1))[0]=link; if (maxlink_<link) maxlink_=link; } } for (zuint i=0; i<links_.size(); i++) { links_.at(i)[0]=maxlink_-links_.at(i)[0]; links_.at(i)[1]=(maxlink_-links_.at(i)[1])*SQRT2; links_.at(i)[2]=maxlink_-links_.at(i)[2]; links_.at(i)[3]=(maxlink_-links_.at(i)[3])*SQRT2; links_.at(i)[4]=(maxlink_-links_.at(i)[4])*SQRT2; links_.at(i)[5]=maxlink_-links_.at(i)[5]; links_.at(i)[6]=(maxlink_-links_.at(i)[6])*SQRT2; links_.at(i)[7]=maxlink_-links_.at(i)[7]; } afterPrepare(); } //only calculate 1 2 3 7 and set 6 5 4 0 accordingly void EdgeTracer::Prepare(const Image3f &ori) { const float SQRT2=Sqrt(2.0f); links_.SetSize(ori.Size()); memset(links_.Data(),0,sizeof(Vector<8,float>)*links_.size()); maxlink_=-MAX_FLOAT; for (zuint r=0; r<ori.Rows(); r++) for (zuint c=0; c<ori.Cols(); c++) { if (r!=0 && c!=ori.Cols()-1) { //link(1)=(p(2)-p(0))/sqrt(2) Vector3f diff=(ori.At(r-1,c)-ori.At(r,c+1))/SQRT2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[1]=links_.At(Vector2ui(r-1,c+1))[6]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0 && c!=ori.Cols()-1) { //link(2)=(p(1)/2+p(0)-p(3)/2-p(7))/2 Vector3f diff=(ori.At(r-1,c+1)/2+ori.At(r,c+1)-ori.At(r-1,c-1)/2-ori.At(r,c-1))/2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[2]=links_.At(Vector2ui(r-1,c))[5]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0) { //link(3)=(p(2)-p(7))/sqrt(2) Vector3f diff=(ori.At(r-1,c)-ori.At(r,c-1))/SQRT2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[3]=links_.At(Vector2ui(r-1,c-1))[4]=link; if (maxlink_<link) maxlink_=link; } if (c!=0 && r!=0 && r!=ori.Rows()-1) { //link(7)=(p(3)/2+p(2)-p(6)/2-p(5))/2 Vector3f diff=(ori.At(r-1,c-1)/2+ori.At(r-1,c)-ori.At(r+1,c-1)/2-ori.At(r+1,c))/2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[7]=links_.At(Vector2ui(r,c-1))[0]=link; if (maxlink_<link) maxlink_=link; } } for (zuint i=0; i<links_.size(); i++) { links_.at(i)[0]=maxlink_-links_.at(i)[0]; links_.at(i)[1]=(maxlink_-links_.at(i)[1])*SQRT2; links_.at(i)[2]=maxlink_-links_.at(i)[2]; links_.at(i)[3]=(maxlink_-links_.at(i)[3])*SQRT2; links_.at(i)[4]=(maxlink_-links_.at(i)[4])*SQRT2; links_.at(i)[5]=maxlink_-links_.at(i)[5]; links_.at(i)[6]=(maxlink_-links_.at(i)[6])*SQRT2; links_.at(i)[7]=maxlink_-links_.at(i)[7]; } afterPrepare(); } //only calculate 1 2 3 7 and set 6 5 4 0 accordingly void EdgeTracer::Prepare(const Image4f &ori) { const float SQRT2=Sqrt(2.0f); links_.SetSize(ori.Size()); memset(links_.Data(),0,sizeof(Vector<8,float>)*links_.size()); maxlink_=-MAX_FLOAT; for (zuint r=0; r<ori.Rows(); r++) for (zuint c=0; c<ori.Cols(); c++) { if (r!=0 && c!=ori.Cols()-1) { //link(1)=(p(2)-p(0))/sqrt(2) Vector4f diff=(ori.At(r-1,c)-ori.At(r,c+1))/SQRT2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[1]=links_.At(Vector2ui(r-1,c+1))[6]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0 && c!=ori.Cols()-1) { //link(2)=(p(1)/2+p(0)-p(3)/2-p(7))/2 Vector4f diff=(ori.At(r-1,c+1)/2+ori.At(r,c+1)-ori.At(r-1,c-1)/2-ori.At(r,c-1))/2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[2]=links_.At(Vector2ui(r-1,c))[5]=link; if (maxlink_<link) maxlink_=link; } if (r!=0 && c!=0) { //link(3)=(p(2)-p(7))/sqrt(2) Vector4f diff=(ori.At(r-1,c)-ori.At(r,c-1))/SQRT2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[3]=links_.At(Vector2ui(r-1,c-1))[4]=link; if (maxlink_<link) maxlink_=link; } if (c!=0 && r!=0 && r!=ori.Rows()-1) { //link(7)=(p(3)/2+p(2)-p(6)/2-p(5))/2 Vector4f diff=(ori.At(r-1,c-1)/2+ori.At(r-1,c)-ori.At(r+1,c-1)/2-ori.At(r+1,c))/2; float link=sqrt(diff.LenSqr()/3); links_.At(Vector2ui(r,c))[7]=links_.At(Vector2ui(r,c-1))[0]=link; if (maxlink_<link) maxlink_=link; } } for (zuint i=0; i<links_.size(); i++) { links_.at(i)[0]=maxlink_-links_.at(i)[0]; links_.at(i)[1]=(maxlink_-links_.at(i)[1])*SQRT2; links_.at(i)[2]=maxlink_-links_.at(i)[2]; links_.at(i)[3]=(maxlink_-links_.at(i)[3])*SQRT2; links_.at(i)[4]=(maxlink_-links_.at(i)[4])*SQRT2; links_.at(i)[5]=maxlink_-links_.at(i)[5]; links_.at(i)[6]=(maxlink_-links_.at(i)[6])*SQRT2; links_.at(i)[7]=maxlink_-links_.at(i)[7]; } afterPrepare(); } void EdgeTracer::FindPath(int end, vector<int>& backpath) { //link direction //3 2 1 //7 p 0 //6 5 4 int linelength=links_.Size(1); int offsets[8]={+1,-linelength+1,-linelength,-linelength-1,linelength+1,linelength,linelength-1,-1}; int offsetr[8]={0,-1,-1,-1,1,1,1,0}; int offsetc[8]={1,1,0,-1,1,0,-1,-1}; //Dijkstra's algorithm Fibdata fibdata; while(pathmap.at(end).status!=2) { Fibdata thisdata=heap.ExtractMin(); Vector2ui thisrc=links_.ToIndex(thisdata.pos); for (int link=0;link<8;link++) { Vector2i rc(thisrc); rc[0]+=offsetr[link]; rc[1]+=offsetc[link]; if (!Within<int>(0,rc[0],links_.Size(0)-1)) continue; //check if out of boundary if (!Within<int>(0,rc[1],links_.Size(1)-1)) continue; //check if out of boundary int otherpos=thisdata.pos+offsets[link]; double maskratio=1; if (mask_.at(otherpos)==1) maskratio=0.01; PathNode &pathnode=pathmap.at(otherpos); if (pathnode.status==2) continue; //fixed float thiscost=thisdata.cost+links_.at(thisdata.pos)[link]*maskratio; //cost at here plus cost to go there if (thiscost<pathmap.at(otherpos).cost) { pathnode.cost=thiscost; //update the minimum cost pathnode.backpath=7-link; //store where the minimum cost comes from //update heap fibdata.cost=thiscost; fibdata.pos=otherpos; if (pathnode.status==1) //already in heap, so need to update it { heap.DecreaseKey(pathnode.node,fibdata); } else //not in the heap, need to add(new pos cost is MAX_INT, so code will go here) { pathnode.node=heap.Insert(fibdata); } } } pathmap.at(thisdata.pos).node=NULL; pathmap.at(thisdata.pos).status=2; } backpath.clear(); backpath.push_back(end); while(backpath.back()!=start_) { backpath.push_back(backpath.back() + offsets[pathmap.at(backpath.back()).backpath]); } return; } void EdgeTracer::FindPath(const Vector2ui &end, vector<Vector2ui>& backpath) { vector<int> backpathint; FindPath(links_.ToIndex(end), backpathint); backpath.clear(); for (zuint i=0; i<backpathint.size(); i++) backpath.push_back(links_.ToIndex(backpathint[i])); } void EdgeTracer::SetStart(int start) { start_=start; pathmap.SetSize(links_.Size()); PathNode initpathnode; initpathnode.node=NULL; initpathnode.cost=MAX_INT; initpathnode.backpath=-1; initpathnode.status=0; for (zuint i=0; i<pathmap.size(); i++) pathmap.at(i)=initpathnode; heap.Clear(); Fibdata fibdata; fibdata.cost=0; fibdata.pos=start_; pathmap.at(start_).node=heap.Insert(fibdata); return; } void EdgeTracer::SetStart(const Vector2ui &start) { SetStart(links_.ToIndex(start)); } int EdgeTracer::OptimizeClick(int start) { Vector2i rc(links_.ToIndex(start)); int pos=-1; float minlink=MAX_FLOAT; for (int r=Max<int>(0,rc[0]-optrange_); r<=Min<int>(links_.Size(0)-1,rc[0]+optrange_); r++) for (int c=Max<int>(0,rc[1]-optrange_); c<=Min<int>(links_.Size(1)-1,rc[1]+optrange_); c++) for (int link=0;link<8;link++) { int thispos=links_.ToIndex(Vector2ui(r,c)); if (links_.at(thispos)[link]<minlink) { minlink=links_.at(thispos)[link]; pos=thispos; } } return pos; } zzz::Vector2ui EdgeTracer::OptimizeClick(const Vector2ui &pos) { return links_.ToIndex(OptimizeClick(links_.ToIndex(pos))); } void EdgeTracer::SetMask(const Image<zuchar>& mask) { if (mask_.size()==0) return; mask_.SetData(mask.Data()); pathmap.SetSize(links_.Size()); PathNode initpathnode; initpathnode.node=NULL; initpathnode.cost=MAX_INT; initpathnode.backpath=-1; initpathnode.status=0; for (zuint i=0; i<pathmap.size(); i++) pathmap.at(i)=initpathnode; heap.Clear(); Fibdata fibdata; fibdata.cost=0; fibdata.pos=start_; pathmap.at(start_).node=heap.Insert(fibdata); } void EdgeTracer::ClearMask() { if (mask_.size()==0) return; memset(mask_.Data(),0,mask_.size()); pathmap.SetSize(links_.Size()); PathNode initpathnode; initpathnode.node=NULL; initpathnode.cost=MAX_INT; initpathnode.backpath=-1; initpathnode.status=0; for (zuint i=0; i<pathmap.size(); i++) pathmap.at(i)=initpathnode; heap.Clear(); Fibdata fibdata; fibdata.cost=0; fibdata.pos=start_; pathmap.at(start_).node=heap.Insert(fibdata); } void EdgeTracer::afterPrepare() { heap.Clear(); mask_.SetSize(links_.Size()); memset(mask_.Data(),0,mask_.size()); start_=-1; } }
zzz-engine
zzzEngine/zVision/zVision/VisionAlgo/EdgeTracer.cpp
C++
gpl3
11,055
#pragma once #include <Graphics/AABB.hpp> #include <Renderer/Renderer.hpp> #include <Resource/Shader/ShaderSpecify.hpp> #include <Math/Math.hpp> #include <Utility/CacheSet.hpp> #include <3rdParty/boostsignal2.hpp> namespace zzz{ template<typename T> class ImageListRenderer : public Renderer , public GraphicsHelper { public: ImageListRenderer(CacheSet<Image<T>*, zuint> *imgSet, zuint nimage) :imgSet_(imgSet), margin_(5), curleft_(0), posleft_(0), mode_(ILMODE_ORI), nimages_(nimage), curimg_(-1) {showMsg_=false;} void DrawBox(int x1, int y1, int x2, int y2) { x1-=2;y1-=2;x2+=2;y2+=2; Vector3d p0=UnProject(x1, y1, camera_.zNear_); Vector3d p1=UnProject(x1, y2, camera_.zNear_); Vector3d p2=UnProject(x2, y2, camera_.zNear_); Vector3d p3=UnProject(x2, y1, camera_.zNear_); ColorDefine::yellow.ApplyGL(); GLLineWidth::Set(2); ZCOLORSHADER->Begin(); GraphicsHelper::DrawLine(p0,p1); GraphicsHelper::DrawLine(p1,p2); GraphicsHelper::DrawLine(p2,p3); GraphicsHelper::DrawLine(p3,p0); Shader::End(); GLLineWidth::Restore(); } bool Draw() { image_range_.clear(); switch(mode_) { case ILMODE_ORI: { Image<T> *img=imgSet_->Get(curleft_); glPixelZoom(1,1); int posx=posleft_+margin_, posy=postop_+margin_; SetRasterPos(posx,posy); DrawImage(*img); if (curimg_ == curleft_) DrawBox(posx, posy, posx+img->Cols(), posy+img->Rows()); image_range_.push_back(make_pair(curleft_, AABB2i(Vector2i(posx, posy), Vector2i(posx+img->Cols(), posy+img->Rows())))); } break; case ILMODE_SINGLE: { int imgheight=height_-margin_-margin_; int imgwidth=width_-margin_-margin_; Image<T> *img=imgSet_->Get(curleft_); //decide ratio float zoomratio=Min(float(imgheight)/float(img->Rows()),float(imgwidth)/float(img->Cols())); glPixelZoom(zoomratio,zoomratio); int posx=(width_-img->Cols()*zoomratio)/2, posy=(height_-img->Rows()*zoomratio)/2; SetRasterPos(posx,posy); DrawImage(*img); if (curimg_ == curleft_) DrawBox(posx, posy, posx+img->Cols()*zoomratio, posy+img->Rows()*zoomratio); image_range_.push_back(make_pair(curleft_, AABB2i(Vector2i(posx, posy), Vector2i(posx+img->Cols()*zoomratio, posy+img->Rows()*zoomratio)))); } break; case ILMODE_HCONT: case ILMODE_HSTEP: { int imgheight=height_-margin_-margin_; int pos=posleft_; zuint cur=curleft_; while(true) { Image<T> *img=imgSet_->Get(cur); //decide ratio float zoomratio=float(imgheight)/float(img->Rows()); glPixelZoom(zoomratio,zoomratio); SetRasterPos(pos,margin_); DrawImage(*img); if (curimg_ == cur) DrawBox(pos, margin_, pos+img->Cols()*zoomratio, margin_+img->Rows()*zoomratio); image_range_.push_back(make_pair(cur, AABB2i(Vector2i(pos, margin_), Vector2i(pos+img->Cols()*zoomratio, margin_+img->Rows()*zoomratio)))); //prepare next pos+=img->Cols()*zoomratio; pos+=margin_; if (pos>width_) break; cur++; if (cur>=nimages_) break; } } break; case ILMODE_VCONT: case ILMODE_VSTEP: { int imgwidth=width_-margin_-margin_; int pos=posleft_; zuint cur=curleft_; while(true) { Image<T> *img=imgSet_->Get(cur); //decide ratio float zoomratio=float(imgwidth)/float(img->Cols()); glPixelZoom(zoomratio,zoomratio); int posx=margin_, posy=height_-pos-img->Rows()*zoomratio; SetRasterPos(posx,posy); DrawImage(*img); if (curimg_ == cur) DrawBox(posx, posy, posx+img->Cols()*zoomratio, posy+img->Rows()*zoomratio); image_range_.push_back(make_pair(cur, AABB2i(Vector2i(posx, posy), Vector2i(posx+img->Cols()*zoomratio, posy+img->Rows()*zoomratio)))); //prepare next pos+=img->Rows()*zoomratio; pos+=margin_; if (pos>height_) break; cur++; if (cur>=nimages_) break; } } break; } return true; } void SetCurrent(zuint i) { curleft_=i; posleft_=0; } void SetMargin(zuint s) { margin_=s; Redraw(); } typedef enum {ILMODE_ORI, ILMODE_SINGLE, ILMODE_HCONT, ILMODE_VCONT, ILMODE_HSTEP, ILMODE_VSTEP} ILMODE; void SetMode(ILMODE mode) { mode_=mode; switch(mode_) { case ILMODE_ORI: postop_=0; case ILMODE_SINGLE: case ILMODE_HSTEP: case ILMODE_VSTEP: posleft_=0; break; case ILMODE_HCONT: case ILMODE_VCONT: break; } Redraw(); } void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y) { switch(mode_) { case ILMODE_VCONT: case ILMODE_HCONT: posleft_+=Sign(zDelta)*60; Normalize(); break; case ILMODE_ORI: case ILMODE_SINGLE: case ILMODE_HSTEP: case ILMODE_VSTEP: { int oldleft=curleft_; curleft_-=Sign(zDelta); curleft_=Clamp<int>(0,curleft_,nimages_-1); if (oldleft!=curleft_) { posleft_=0; postop_=0; } } break; } Redraw(); } void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { switch(nChar) { case ZZZKEY_F1: SetMode(ILMODE_ORI); break; case ZZZKEY_F2: SetMode(ILMODE_SINGLE); break; case ZZZKEY_F3: SetMode(ILMODE_HCONT); break; case ZZZKEY_F4: SetMode(ILMODE_HSTEP); break; case ZZZKEY_F5: SetMode(ILMODE_VCONT); break; case ZZZKEY_F6: SetMode(ILMODE_VSTEP); break; case ZZZKEY_PAGEDOWN: if (curleft_<(int)nimages_-1) { curleft_++; posleft_=0; } break; case ZZZKEY_PAGEUP: if (curleft_>0) { curleft_--; posleft_=0; } break; case ZZZKEY_HOME: if (curleft_>0) { curleft_=0; posleft_=0; } break; case ZZZKEY_END: if (curleft_<(int)nimages_-1) { curleft_=nimages_-1; posleft_=0; } break; case ZZZKEY_UP: case ZZZKEY_LEFT: switch(mode_) { case ILMODE_HCONT: case ILMODE_VCONT: posleft_+=60; Normalize(); break; case ILMODE_ORI: postop_=0; case ILMODE_SINGLE: case ILMODE_HSTEP: case ILMODE_VSTEP: if (curleft_>0) { curleft_--; posleft_=0; } break; } break; case ZZZKEY_DOWN: case ZZZKEY_RIGHT: switch(mode_) { case ILMODE_HCONT: case ILMODE_VCONT: posleft_-=60; Normalize(); break; case ILMODE_ORI: postop_=0; case ILMODE_SINGLE: case ILMODE_HSTEP: case ILMODE_VSTEP: if (curleft_<(int)nimages_-1) { curleft_++; posleft_=0; } break; } break; } Redraw(); } void OnMouseMove(unsigned int nFlags,int x,int y) { const int drag_margin=200; if (!CheckBit(nFlags, ZZZFLAG_LMOUSE)) return; if (Abs(x-lastx_)> 2 || Abs(y-lasty_)>2) mouse_moved_=true; switch(mode_) { case ILMODE_ORI: posleft_+=x-lastx_; lastx_=x; postop_-=y-lasty_; lasty_=y; { Image<T> *img=imgSet_->Get(curleft_); int dragtopmost=Min<int>(0,height_-int(img->Rows())-margin_); int dragleftmost=Min<int>(0,width_-int(img->Cols())-margin_); postop_=Clamp<int>(dragtopmost, postop_, 0); posleft_=Clamp<int>(dragleftmost, posleft_, 0); } Redraw(); break; case ILMODE_HCONT: posleft_+=x-lastx_; Normalize(); lastx_=x; Redraw(); break; case ILMODE_HSTEP: posleft_+=x-lastx_; { int imgheight=height_-margin_-margin_; Image<T> *img=imgSet_->Get(curleft_); float zoomratio=float(imgheight)/float(img->Rows()); int dragleftmost=Min<int>(0,-zoomratio*img->Cols()-margin_+width_); if (Within<int>(dragleftmost,posleft_,0)) lastx_=x; else if (Within<int>(0,posleft_,drag_margin)) posleft_=0; else if (Within<int>(dragleftmost-drag_margin,posleft_,dragleftmost)) posleft_=dragleftmost; else if (posleft_<0) { curleft_++; curleft_=Clamp<int>(0,curleft_,int(nimages_)-1); lastx_=x; posleft_=0; } else { curleft_--; curleft_=Clamp<int>(0,curleft_,int(nimages_)-1); lastx_=x; posleft_=0; } } Redraw(); break; case ILMODE_VCONT: posleft_+=y-lasty_; Normalize(); lasty_=y; Redraw(); break; case ILMODE_VSTEP: posleft_+=y-lasty_; { int imgwidth=width_-margin_-margin_; Image<T> *img=imgSet_->Get(curleft_); float zoomratio=float(imgwidth)/float(img->Cols()); int dragleftmost=Min<int>(0,-zoomratio*img->Rows()-margin_+height_); if (Within<int>(dragleftmost,posleft_,0)) lasty_=y; else if (Within<int>(0,posleft_,drag_margin)) posleft_=0; else if (Within<int>(dragleftmost-drag_margin,posleft_,dragleftmost)) posleft_=dragleftmost; else if (posleft_<0) { curleft_++; curleft_=Clamp<int>(0,curleft_,int(nimages_)-1); lasty_=y; posleft_=0; } else { curleft_--; curleft_=Clamp<int>(0,curleft_,int(nimages_)-1); lasty_=y; posleft_=0; } } Redraw(); break; } } void OnLButtonDown(unsigned int nFlags,int x,int y) { lastx_=x; lasty_=y; mouse_moved_=false; } void OnLButtonUp(unsigned int nFlags,int x,int y) { if (!mouse_moved_) { Vector2i pos(x, height_-y-1); for (zuint i=0; i<image_range_.size(); i++) { if (image_range_[i].second.IsInside(pos)) { // signal_select_(image_range_[i].first); curimg_=image_range_[i].first; Redraw(); break; } } } } // boost::signals2::signal<void(zuint)> signal_select_; protected: zuint curimg_; private: void Normalize() { switch(mode_) { case ILMODE_HCONT: case ILMODE_HSTEP: { int imgheight=height_-margin_-margin_; int pos=posleft_; zuint cur=curleft_; while(true) { if (cur==0) break; if (pos<0) break; Image<T> *img=imgSet_->Get(cur-1); float zoomratio=float(imgheight)/float(img->Rows()); pos-=margin_; pos-=img->Cols()*zoomratio; cur--; } while(true) { Image<T> *img=imgSet_->Get(cur); float zoomratio=float(imgheight)/float(img->Rows()); pos+=img->Cols()*zoomratio; if (pos>0) { pos-=img->Cols()*zoomratio; break; } pos+=margin_; cur++; if (cur>=nimages_-1) break; } if (cur==0 && pos>0){cur=0;pos=0;} if (cur>=nimages_-1){cur=nimages_-1;pos=0;} posleft_=pos; curleft_=cur; } break; case ILMODE_VCONT: case ILMODE_VSTEP: { int imgwidth=width_-margin_-margin_; int pos=posleft_; zuint cur=curleft_; while(true) { if (cur==0) break; if (pos<0) break; Image<T> *img=imgSet_->Get(cur-1); float zoomratio=float(imgwidth)/float(img->Cols()); pos-=margin_; pos-=img->Rows()*zoomratio; cur--; } while(true) { Image<T> *img=imgSet_->Get(cur); float zoomratio=float(imgwidth)/float(img->Cols()); pos+=img->Rows()*zoomratio; if (pos>0) { pos-=img->Rows()*zoomratio; break; } pos+=margin_; cur++; if (cur>=nimages_-1) break; } if (cur==0 && pos>0){cur=0;pos=0;} if (cur>=nimages_-1){cur=nimages_-1;pos=0;} posleft_=pos; curleft_=cur; } break; } } CacheSet<Image<T>*, zuint> *imgSet_; int margin_; int curleft_; int posleft_; int postop_; ILMODE mode_; int lastx_, lasty_; zuint nimages_; vector<pair<zuint, AABB<2,int> > > image_range_; bool mouse_moved_; }; }
zzz-engine
zzzEngine/zVision/zVision/Renderer/ImageListRenderer.hpp
C++
gpl3
12,862
#pragma once #include <GraphicsGUI/GraphicsGUI.hpp> #include <Renderer/Vis2DRenderer.hpp> namespace zzz { class BrushGUI : public GraphicsGUI<Vis2DRenderer> { public: BrushGUI(); bool OnLButtonDown(unsigned int nFlags,int x,int y); bool OnLButtonUp(unsigned int nFlags,int x,int y); bool OnRButtonDown(unsigned int nFlags,int x,int y); bool OnRButtonUp(unsigned int nFlags,int x,int y); bool OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); bool OnMouseMove(unsigned int nFlags,int x,int y); void Prepare(const Image4f &img); Image4f show_; Imageuc mask_; zuchar sel_id_; private: bool left_, right_; int x_, y_; Vector2ui pos_, last_; Image4f ori_; int brushsize_; void PrepareShow(); }; } // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Renderer/BrushGUI.hpp
C++
gpl3
795
#pragma once #include <Renderer/Vis2DRenderer.hpp> #include <GraphicsGUI/GraphicsGUI.hpp> #include <Math/Vector2.hpp> #include <VisionAlgo/EdgeTracer.hpp> namespace zzz { class CutGUI : public GraphicsGUI<Vis2DRenderer> { public: CutGUI(); bool OnLButtonDown(unsigned int nFlags,int x,int y); bool OnLButtonUp(unsigned int nFlags,int x,int y); bool OnRButtonDown(unsigned int nFlags,int x,int y); bool OnRButtonUp(unsigned int nFlags,int x,int y); bool OnMouseMove(unsigned int nFlags,int x,int y); bool OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); bool OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags); void Prepare(const Image4f &img); void GetCurSeg(Imageuc &saveimg); Image4f show_; zzz::Imageuc segments_; zuchar curseg_; private: bool left_, right_; int x_, y_; Vector2ui pos_; // data Image4f ori_; Imageuc mask_; //segment static const zuchar CUT_EDGE=1; static const zuchar CUT_INSIDE=0; static const zuchar CUT_OUTSIDE=2; void GetCurCut(Imageuc &img); void CombineSeg(Imageuc &cut, zuchar seg_id); // click optimization bool optmode_; zzz::Vector2ui opt_; int boxsize_; // mask bool usemask_; zzz::Vector2ui last_; int masksize_; // core path finder EdgeTracer pathfinder_; // path vector<vector<Vector2ui> > fixedpath_; vector<Vector2ui> curpath_; vector<Vector2ui> seeds_; //input status enum {FIRST_CLICK,REST_CLICK,FINISH_CLICK} inputstatus_; //prepare what to show enum ShowMode{CUT_MODE, MASK_MODE}; void PrepareShow(ShowMode showmode); }; } // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Renderer/CutGUI.hpp
C++
gpl3
1,691
#include "CutGUI.hpp" #include <Renderer\Vis2DRenderer.hpp> #include <Image\ImageDrawer.hpp> #include <Graphics\ColorDefine.hpp> namespace zzz { CutGUI::CutGUI() :left_(false), right_(false), inputstatus_(FIRST_CLICK), optmode_(true), usemask_(false), masksize_(10), boxsize_(5), curseg_(1) { } bool CutGUI::OnMouseMove(unsigned int nFlags,int x,int y) { x_ = x; y_ = y; if (ori_.size()==0) return false; pos_=Vector2ui(renderer_->GetHoverPixel(x,y)); // If it is not inside image if (!show_.IsInside(pos_)) { opt_[0]=-1; return true; } // Draw mask if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) { ImageDrawer<zuchar> drawer(mask_); // Draw if (left_) { vector<Vector2i> path; RasterizeLine(last_[0], last_[1], pos_[0], pos_[1], path); for (zuint i=0; i<path.size(); i++) drawer.FillCircle(1, path[i][0], path[i][1], masksize_); pathfinder_.SetMask(mask_); last_=pos_; } else if (right_) { // Erase vector<Vector2i> path; RasterizeLine(last_[0], last_[1], pos_[0], pos_[1], path); for (zuint i=0; i<path.size(); i++) drawer.FillCircle(0, path[i][0], path[i][1], masksize_); pathfinder_.SetMask(mask_); last_=pos_; } PrepareShow(MASK_MODE); } else if (CheckBit(nFlags,ZZZFLAG_SHIFT)) { // straight line if (inputstatus_==FIRST_CLICK) opt_=pos_; else if (inputstatus_==REST_CLICK) { opt_=pos_; const Vector2ui &last(seeds_.back()); vector<Vector2i> path; RasterizeLine(last[0], last[1], pos_[0], pos_[1], path); curpath_.clear(); for (zuint i=0; i<path.size(); i++) curpath_.push_back(Vector2ui(path[i])); } PrepareShow(CUT_MODE); } else { // snap if (inputstatus_==FIRST_CLICK) { if (optmode_) opt_=pathfinder_.OptimizeClick(pos_); } else if (inputstatus_==REST_CLICK) { const Vector2ui firstpos=seeds_.front(); // Check close loop if (seeds_.size()>=3 && Abs((int)pos_[0]-(int)firstpos[0])<=boxsize_ && Abs((int)pos_[1]-(int)firstpos[1])<=boxsize_) opt_=firstpos; // Optimize click else if (optmode_) opt_=pathfinder_.OptimizeClick(pos_); pathfinder_.FindPath(opt_,curpath_); } PrepareShow(CUT_MODE); } renderer_->Redraw(); return true; } bool CutGUI::OnLButtonDown(unsigned int nFlags,int x,int y) { left_=true; if (!show_.IsInside(pos_)) return false; if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) { last_=pos_; OnMouseMove(nFlags,x,y); } return true; } bool CutGUI::OnLButtonUp(unsigned int nFlags,int x,int y) { left_=false; if (ori_.size()==0) return false; //not load, do nothing if (!show_.IsInside(pos_)) return false; // Drawing mask, do nothing if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) { return false; } switch(inputstatus_) { case FIRST_CLICK: seeds_.clear(); pathfinder_.SetStart(opt_); seeds_.push_back(opt_); inputstatus_=REST_CLICK; PrepareShow(CUT_MODE); break; case REST_CLICK: fixedpath_.push_back(curpath_); curpath_.clear(); pathfinder_.SetStart(opt_); seeds_.push_back(opt_); if (seeds_.size()>=4 && opt_==seeds_.front()) { inputstatus_=FINISH_CLICK; } PrepareShow(CUT_MODE); break; case FINISH_CLICK: Imageuc cut; GetCurCut(cut); CombineSeg(cut, curseg_); fixedpath_.clear(); seeds_.clear(); inputstatus_=FIRST_CLICK; PrepareShow(CUT_MODE); } renderer_->Redraw(); return true; } bool CutGUI::OnRButtonDown(unsigned int nFlags,int x,int y) { Vis2DRenderer *r = reinterpret_cast<Vis2DRenderer*>(renderer_); right_=true; if (usemask_ && CheckBit(nFlags, ZZZFLAG_CTRL)) { if (!show_.IsInside(pos_)) return false; last_=pos_; OnMouseMove(nFlags,x,y); } return true; } bool CutGUI::OnRButtonUp(unsigned int nFlags,int x,int y) { right_=false; if (ori_.size()==0) return false; if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) { return false; } if (inputstatus_==REST_CLICK || inputstatus_==FINISH_CLICK) { seeds_.pop_back(); if (seeds_.empty()) { inputstatus_=FIRST_CLICK; curpath_.clear(); } else { fixedpath_.pop_back(); pathfinder_.SetStart(seeds_.back()); OnMouseMove(nFlags,x,y); inputstatus_=REST_CLICK; } PrepareShow(CUT_MODE); renderer_->Redraw(); } return true; } bool CutGUI::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (ori_.size()==0) return false; if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) PrepareShow(MASK_MODE); else PrepareShow(CUT_MODE); renderer_->Redraw(); return true; } bool CutGUI::OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (ori_.size()==0) return false; if (usemask_ && CheckBit(nFlags,ZZZFLAG_CTRL)) { if (nChar=='-') masksize_=Max(0, masksize_-1); if (nChar=='=') masksize_++; PrepareShow(MASK_MODE); renderer_->Redraw(); } else { if (nChar=='-') boxsize_=Max(0, boxsize_-1); if (nChar=='=') boxsize_++; pathfinder_.optrange_=boxsize_; PrepareShow(CUT_MODE); renderer_->Redraw(); } return true; } void CutGUI::PrepareShow(ShowMode showmode) { const int offsetr[8]={0,-1,-1,-1,1,1,1,0}; const int offsetc[8]={1,1,0,-1,1,0,-1,-1}; //combine segment for (zuint i=0; i<show_.size(); i++) if (segments_[i]!=0) show_[i]=ori_.at(i) * *(ColorDefine::DistinctValue[segments_[i]]); else show_[i]=ori_.at(i); // Imageuc cut; // GetCurCut(cut); // for (zuint i=0; i<show_.size(); i++) // if (cut[i]!=CUT_OUTSIDE) // show_[i]=ori_.at(i) * *(ColorDefine::DistinctValue[curseg_]); //draw mask if (usemask_) for (zuint i=0; i<ori_.size(); i++) if (mask_[i]) show_[i]*=0.8; ImageDrawer<Vector4f> drawer(show_); //draw path for (zuint i=0; i<fixedpath_.size(); i++) for (zuint j=0; j<fixedpath_[i].size(); j++) drawer.DrawPoint(Vector4f(0,0,1,1),show_.ToIndex(Vector2i(fixedpath_[i][j]))); for (zuint j=0; j<curpath_.size(); j++) drawer.DrawPoint(Vector4f(1,0,0,1),show_.ToIndex(Vector2i(curpath_[j]))); //draw mouse position { if (ori_.IsInside(pos_)) { if (showmode==CUT_MODE) { if (inputstatus_==FINISH_CLICK) return; if (optmode_) //show optimize search box drawer.DrawBox(Vector4f(1,1,0,1),pos_[0]-boxsize_,pos_[1]-boxsize_,pos_[0]+boxsize_,pos_[1]+boxsize_); if (seeds_.size()>=3 && opt_==seeds_.front()) drawer.DrawCircle(Vector4f(0,0,1,1),opt_[0],opt_[1],2); //loop else drawer.DrawCross(Vector4f(1,1,0,1),opt_[0],opt_[1],2); } else if (showmode==MASK_MODE) { drawer.DrawCircle(Vector4f(0.8,0.8,0.8,1),pos_[0],pos_[1],masksize_); } } } } void CutGUI::Prepare(const Image4f &img) { ori_=img; //SetCenter(ori_.Cols(),ori_.Rows()); pathfinder_.Prepare(ori_); show_=img; seeds_.clear(); fixedpath_.clear(); curpath_.clear(); inputstatus_=FIRST_CLICK; mask_.SetSize(img.Size()); mask_.Zero(); //all segment id init to 0 segments_.SetSize(img.Size()); segments_.Zero(); PrepareShow(CUT_MODE); } void CutGUI::GetCurCut(Imageuc &saveimg) { const zuchar CUT_UNKNOWN=255; const zuchar CUT_CHECKING=254; const zuchar CUT_CUR=253; saveimg.SetSize(ori_.Size()); memset(saveimg.Data(),CUT_UNKNOWN,saveimg.size()); // Draw path. ImageDrawer<zuchar> drawer(saveimg); for (zuint i=0; i<fixedpath_.size(); i++) for (zuint j=0; j<fixedpath_[i].size(); j++) drawer.DrawPoint(CUT_EDGE,saveimg.ToIndex(Vector2i(fixedpath_[i][j]))); // Region growing. deque<Vector2ui> q; for (zuint r=0; r<saveimg.Rows(); r++) for(zuint c=0; c<saveimg.Cols(); c++) { if (saveimg(r,c)!=CUT_UNKNOWN) continue; bool mainRegion=true; //if region touches boundary of image, it is not mainRegion q.push_front(Vector2ui(r,c)); saveimg(r,c)=CUT_CHECKING; while(!q.empty()) { Vector2ui p(q.back()); q.pop_back(); saveimg[p]=CUT_CUR; if (p[0]>0 && saveimg(p[0]-1,p[1])==CUT_UNKNOWN) { q.push_front(Vector2ui(p[0]-1,p[1])); saveimg(p[0]-1,p[1])=CUT_CHECKING; } if (p[0]<saveimg.Rows()-1 && saveimg(p[0]+1,p[1])==CUT_UNKNOWN) { q.push_front(Vector2ui(p[0]+1,p[1])); saveimg(p[0]+1,p[1])=CUT_CHECKING; } if (p[1]>0 && saveimg(p[0],p[1]-1)==CUT_UNKNOWN) { q.push_front(Vector2ui(p[0],p[1]-1)); saveimg(p[0],p[1]-1)=CUT_CHECKING; } if (p[1]<saveimg.Cols()-1 && saveimg(p[0],p[1]+1)==CUT_UNKNOWN) { q.push_front(Vector2ui(p[0],p[1]+1)); saveimg(p[0],p[1]+1)=CUT_CHECKING; } if (p[0]==0 || p[0]==saveimg.Rows()-1 || p[1]==0 || p[1]==saveimg.Cols()-1) mainRegion=false; } if (mainRegion) { for (zuint i=0; i<saveimg.size(); i++) if (saveimg[i]==CUT_CUR) saveimg[i]=CUT_INSIDE; } else { for (zuint i=0; i<saveimg.size(); i++) if (saveimg[i]==CUT_CUR) saveimg[i]=CUT_OUTSIDE; } } } void CutGUI::CombineSeg(Imageuc &cut, zuchar seg_id) { for (zuint i=0; i<cut.size(); i++) if (cut[i]!=CUT_OUTSIDE) segments_[i]=seg_id; } }; // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Renderer/CutGUI.cpp
C++
gpl3
9,629
#pragma once #include <Renderer/Vis2DRenderer.hpp> namespace zzz{ template<typename T> class MatchRenderer : public Vis2DRenderer, public GraphicsHelper { public: typedef pair<Vector2i,Vector2i> MatchPair; MatchRenderer():shows_(10){} void DrawObj() { if (shows_>match_.size()) shows_=match_.size(); DrawImage(*img1_); SetRasterPosRelative(img1_->Cols(),0); DrawImage(*img2_); for (zuint i=0; i<shows_; i++) { Draw2DLine( match_[i].first[0], match_[i].first[1],\ img1_->Cols()+match_[i].second[0], match_[i].second[1],\ *(ColorDefine::Value[(i*10)%ColorDefine::Size]), 1); } Draw2DLine( match_[shows_-1].first[0], match_[shows_-1].first[1],\ img1_->Cols()+match_[shows_-1].second[0], match_[shows_-1].second[1],\ *(ColorDefine::Value[((shows_-1)*10)%ColorDefine::Size]), 4); } void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { switch(nChar) { case ZZZKEY_RIGHT: if (shows_<match_.size()) { shows_++; zout<<"("<<match_[shows_-1].first[0]<<","<<match_[shows_-1].first[1]<<")==>"; zout<<"("<<match_[shows_-1].second[0]<<","<<match_[shows_-1].second[1]<<")\n"; } break; case ZZZKEY_LEFT: if (shows_>1) { shows_--; zout<<"("<<match_[shows_-1].first[0]<<","<<match_[shows_-1].first[1]<<")==>"; zout<<"("<<match_[shows_-1].second[0]<<","<<match_[shows_-1].second[1]<<")\n"; } break; case ZZZKEY_UP: if (shows_<match_.size()) { if (shows_<match_.size()-9) shows_+=10; else shows_=match_.size(); zout<<"("<<match_[shows_-1].first[0]<<","<<match_[shows_-1].first[1]<<")==>"; zout<<"("<<match_[shows_-1].second[0]<<","<<match_[shows_-1].second[1]<<")\n"; } break; case ZZZKEY_DOWN: if (shows_>1) { if (shows_>9) shows_-=10; else shows_=1; zout<<"("<<match_[shows_-1].first[0]<<","<<match_[shows_-1].first[1]<<")==>"; zout<<"("<<match_[shows_-1].second[0]<<","<<match_[shows_-1].second[1]<<")\n"; } break; case ZZZKEY_END: shows_=match_.size(); break; case ZZZKEY_HOME: shows_=1; break; } Redraw(); } Image<T> *img1_, *img2_; vector<MatchPair> match_; zuint shows_; }; }
zzz-engine
zzzEngine/zVision/zVision/Renderer/MatchRenderer.hpp
C++
gpl3
2,494
#include "BrushGUI.hpp" #include <Graphics\ColorDefine.hpp> #include <zImage.hpp> namespace zzz { BrushGUI::BrushGUI() :sel_id_(1), brushsize_(5), left_(false), right_(false) { } void BrushGUI::Prepare(const Image4f &img) { ori_=img; mask_.SetSize(ori_.Size()); mask_.Zero(); show_=ori_; } bool BrushGUI::OnMouseMove(unsigned int nFlags,int x,int y) { x_ = x; y_ = y; if (ori_.size()==0) return false; pos_ = Vector2ui(renderer_->GetHoverPixel(x,y)); if (left_) { ImageDrawer<zuchar> drawer(mask_); vector<Vector2i> path; RasterizeLine(last_[0], last_[1], pos_[0], pos_[1], path); for (zuint i=0; i<path.size(); i++) drawer.FillCircle(sel_id_, path[i][0], path[i][1], brushsize_); last_=pos_; } else if (right_) { ImageDrawer<zuchar> drawer(mask_); vector<Vector2i> path; RasterizeLine(last_[0], last_[1], pos_[0], pos_[1], path); for (zuint i=0; i<path.size(); i++) drawer.FillCircle(0, path[i][0], path[i][1], brushsize_); last_=pos_; } PrepareShow(); renderer_->Redraw(); return true; } bool BrushGUI::OnLButtonDown(unsigned int nFlags,int x,int y) { left_=true; if (!show_.IsInside(pos_)) return false; last_ = pos_; OnMouseMove(nFlags, x, y); return true; } bool BrushGUI::OnLButtonUp(unsigned int nFlags,int x,int y) { left_=false; return true; } bool BrushGUI::OnRButtonDown(unsigned int nFlags,int x,int y) { right_ = true; if (!show_.IsInside(pos_)) return false; last_ = pos_; OnMouseMove(nFlags, x, y); return true; } bool BrushGUI::OnRButtonUp(unsigned int nFlags,int x,int y) { right_ = false; return true; } bool BrushGUI::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (nChar == ZZZKEY_MINUS) { if (brushsize_ > 0) brushsize_--; } else if (nChar == ZZZKEY_EQUAL) { brushsize_++; } return true; } void BrushGUI::PrepareShow() { for (zuint i=0; i<show_.size(); i++) if (mask_[i]!=0) show_[i]=ori_.at(i) * *(ColorDefine::DistinctValue[mask_[i]]); else show_[i]=ori_.at(i); //draw mouse position ImageDrawer<Vector4f> drawer(show_); drawer.DrawCircle(Vector4f(0.8,0.8,0.8,1),pos_[0],pos_[1],brushsize_); } }; // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Renderer/BrushGUI.cpp
C++
gpl3
2,341
#pragma once //#include <sigslot.h> #include <3rdParty/boostsignal2.hpp> #include "../VisionAlgo/EdgeTracer.hpp" #include <Renderer/OneImageRenderer.hpp> #include "CutGUI.hpp" #include "BrushGUI.hpp" // USAGE: to cut out a piece from a image with Intelligent Scissor // call Prepare to init // click will optimize inside a square // use +/- to change the square's size // if you do not want optimization, change the size to minimal // left click to add fix point // right click to delete last fix point // when close to the first fix point, it will snap, click to close the loop // press control to draw preferance region // path will prefer to go inside preferance region // left click to draw // right click to erase // use ctrl+ +/- to change the brush size // hold shift to draw straight line, rather than trace edge // wheel to zoom, middle button to move // press Enter to finish, it will send a signal FinishCut(const Image4f &) // paramenter is the cutout, if no cut, it will send the whole image namespace zzz{ template<typename T> class CutRenderer : public OneImageRenderer<T> { public: CutRenderer() { lock_=false; cutgui_.Init(this); brushgui_.Init(this); guitype_=GUICUT; } void OnMouseMove(unsigned int nFlags,int x,int y) { OneImageRenderer::OnMouseMove(nFlags,x,y); if (guitype_==GUICUT) cutgui_.OnMouseMove(nFlags, x, y); else brushgui_.OnMouseMove(nFlags, x, y); } void OnLButtonDown(unsigned int nFlags,int x,int y) { if (lock_) return; if (guitype_==GUICUT) cutgui_.OnLButtonDown(nFlags, x, y); else brushgui_.OnLButtonDown(nFlags, x, y); } void OnLButtonUp(unsigned int nFlags,int x,int y) { if (lock_) return; if (guitype_==GUICUT) cutgui_.OnLButtonUp(nFlags, x, y); else brushgui_.OnLButtonUp(nFlags, x, y); } void OnRButtonDown(unsigned int nFlags,int x,int y) { if (lock_) return; if (guitype_==GUICUT) cutgui_.OnRButtonDown(nFlags, x, y); else brushgui_.OnRButtonDown(nFlags, x, y); } void OnRButtonUp(unsigned int nFlags,int x,int y) { if (lock_) return; if (guitype_==GUICUT) cutgui_.OnRButtonUp(nFlags, x, y); else brushgui_.OnRButtonUp(nFlags, x, y); } void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (lock_) return; if (nChar==ZZZKEY_SPACE) { if (guitype_==GUICUT) { brushgui_.mask_=cutgui_.segments_; guitype_=GUIBRUSH; } else { cutgui_.segments_=brushgui_.mask_; guitype_=GUICUT; } return; } if (guitype_==GUICUT) cutgui_.OnKeyDown(nChar, nRepCnt, nFlags); else brushgui_.OnKeyDown(nChar, nRepCnt, nFlags); } void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags) { if (lock_) return; if (guitype_==GUICUT) cutgui_.OnKeyUp(nChar, nRepCnt, nFlags); else brushgui_.OnKeyUp(nChar, nRepCnt, nFlags); if (Within<zuint>(ZZZKEY_0,nChar,ZZZKEY_9)) { cutgui_.curseg_=nChar-ZZZKEY_0; brushgui_.sel_id_=nChar-ZZZKEY_0; } } void Prepare(const Image<T> &img) { cutgui_.Prepare(img); brushgui_.Prepare(img); } const Imageuc& GetSegments() const { if (guitype_==GUICUT) return cutgui_.segments_; else return brushgui_.mask_; } void Lock(bool locked) { lock_=locked; } void DrawObj() { if (guitype_== GUICUT) DrawImage(cutgui_.show_); else DrawImage(brushgui_.show_); } private: bool lock_; CutGUI cutgui_; BrushGUI brushgui_; enum GuiType {GUICUT, GUIBRUSH} guitype_; }; }
zzz-engine
zzzEngine/zVision/zVision/Renderer/CutRenderer.hpp
C++
gpl3
3,805
#include "SIFTKeys.hpp" #include <Image/ImageDrawer.hpp> namespace zzz{ SIFTKeys::SIFTKeys(){} SIFTKeys::SIFTKeys(const string &filename) { LoadKeyFile(filename); } SIFTKeys::SIFTKeys(const SIFTKeys& other) { *this=other; } void SIFTKeys::LoadKeyFile(const string &filename) { ifstream fi(filename); if (!fi.good()) { zout<<"Cannot open file: "<<filename<<endl; return; } int keynum,keylen; fi>>keynum>>keylen; assert(keylen==KEY_LEN); keys_.assign(keynum,SIFTKey()); desc_.assign(keynum,Vector<KEY_LEN,zuchar>()); for (int i=0; i<keynum; i++) { fi>>keys_[i].pos[1]>>keys_[i].pos[0]>>keys_[i].scale>>keys_[i].dir; // fi>>desc_[i]; //since >>zuchar will consider it as a char,,, for (zuint j=0; j<128; j++) { int x; fi>>x; desc_[i][j]=x; } } fi.close(); } void SIFTKeys::DrawOnImage(Image3uc &img, Colorf color) { Vector3uc c=color.ToColor<zuchar>().RGB(); ImageDrawer<Vector3uc> drawer(img); for (zuint i=0; i<keys_.size(); i++) { drawer.DrawCircle(c, img.Rows()-1-keys_[i].pos[1], keys_[i].pos[0], keys_[i].scale); drawer.DrawLine(c, \ img.Rows()-1-keys_[i].pos[1], keys_[i].pos[0], \ img.Rows()-1-keys_[i].pos[1]+cos(keys_[i].dir)*keys_[i].scale,keys_[i].pos[0]-sin(keys_[i].dir)*keys_[i].scale); } } const SIFTKeys& SIFTKeys::operator=(const SIFTKeys &other) { keys_=other.keys_; desc_=other.desc_; return *this; } }
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFTKeys.cpp
C++
gpl3
1,506
#include "SIFT.hpp" #include <Math/Matrix3x3.hpp> #include <Image/ImageFilter.hpp> #include <common.hpp> using namespace std; namespace zzz { void SIFT::RefineKeypoint() { Matrix3x3f A; //Hessian Vector3f B,X; for (size_t o=0; o<keypoint_.size(); o++) { int octave_scale=Pow(2,o); int nrow=nrow_/octave_scale, ncol=ncol_/octave_scale, nscale=dog_[o].size(); for (size_t i=0; i<keypoint_[o].size(); i++) { //local search bool good=true; int counter=0; while(true) { Vector3f &pos=keypoint_[o][i]; #define AT(dr,dc,ds) dog_[o][int(pos[2])+(ds)]->At(int(pos[0])+(dr),int(pos[1])+(dc)) float Dr=0.5*(AT(1,0,0)-AT(-1,0,0)); float Dc=0.5*(AT(0,1,0)-AT(0,-1,0)); float Ds=0.5*(AT(0,0,1)-AT(0,0,-1)); float Drr = (AT(+1,0,0) + AT(-1,0,0) - 2.0 * AT(0,0,0)) ; float Dcc = (AT(0,+1,0) + AT(0,-1,0) - 2.0 * AT(0,0,0)) ; float Dss = (AT(0,0,+1) + AT(0,0,-1) - 2.0 * AT(0,0,0)) ; float Drc = 0.25 * (AT(+1,+1,0) + AT(-1,-1,0) - AT(-1,+1,0) - AT(+1,-1,0)) ; float Drs = 0.25 * (AT(+1,0,+1) + AT(-1,0,-1) - AT(-1,0,+1) - AT(+1,0,-1)) ; float Dcs = 0.25 * (AT(0,+1,+1) + AT(0,-1,-1) - AT(0,-1,+1) - AT(0,+1,-1)) ; #undef AT A(0,0)=Drr; A(1,1)=Dcc; A(2,2)=Dss; A(0,1)=Drc; A(1,0)=Drc; A(0,2)=Drs; A(2,0)=Drs; A(1,2)=Dcs; A(2,1)=Dcs; B[0]=-Dr; B[1]=-Dc; B[2]=-Ds; if (!A.Invert()) { good=false; break; } X=A*B; ZLOG(ZVERBOSE)<<pos<<X<<endl; Vector3f dX(0,0,0); dX[0]= ((X[0] > 0.6 && pos[0] < nrow-2) ? 1 : 0) + ((X[0] < -0.6 && pos[0] > 1) ? -1 : 0) ; dX[1]= ((X[1] > 0.6 && pos[1] < ncol-2) ? 1 : 0) + ((X[1] < -0.6 && pos[1] > 1) ? -1 : 0) ; dX[2]= ((X[2] > 0.6 && pos[2] < nscale-2) ? 1 : 0) + ((X[2] < -0.6 && pos[2] > 1) ? -1 : 0) ; if (counter++>5 || (dX[0]==0 && dX[1]==0 && dX[2]==0)) { //done searching //check if value is big enough float value=dog_[o][int(pos[2])]->At(int(pos[0]),int(pos[1])); value+=-0.5*B.Dot(X); if (value<THRESH) { good=false; break; } //eliminate edge response float score=(Drr+Dcc)*(Drr+Dcc)/(Drr*Dcc-Drc*Drc); if (score<0 && score>(EDGETHRESH+1)*(EDGETHRESH+1)/EDGETHRESH) { good=false; break; } //out of range pos+=X; if (pos[0]<0 || pos[0]>nrow-1 || pos[1]<0 || pos[1]>ncol-1 || pos[2]<0 || pos[2]>nscale-1) { good=false; break; } break; } else { pos+=dX; continue; //set new init point and search again } if (good=false) { keypoint_[o].erase(keypoint_[o].begin()+i); i--; } } } } } void SIFT::FindLocalMaxima() { keypoint_.clear(); for (size_t o=0; o<dog_.size(); o++) { int octave_scale=Pow(2,o); int nrow=nrow_/octave_scale, ncol=ncol_/octave_scale, nscale=dog_[o].size(); vector<Vector3f> curoctave; const int neighbor[][3]={ //r,c,s {-1,0,0},{-1,-1,0},{-1,1,0},{0,-1,0},{0,1,0},{1,0,0},{1,-1,0},{1,1,0}, {-1,0,-1},{-1,-1,-1},{-1,1,-1},{0,-1,-1},{0,1,-1},{1,0,-1},{1,-1,-1},{1,1,-1},{0,0,-1}, {-1,0,1},{-1,-1,1},{-1,1,1},{0,-1,1},{0,1,1},{1,0,1},{1,-1,1},{1,1,1},{0,0,1}}; //find maxima for (int s=1; s<nscale-2; s++) for (int r=IMAGEEDGEDIST+1; r<nrow-IMAGEEDGEDIST-2; r++) for (int c=IMAGEEDGEDIST+1; c<ncol-IMAGEEDGEDIST-2; c++) { float cur=dog_[o][s]->At(r,c); bool good=true; for (int i=0; i<26; i++) { if (cur - dog_[o][s+neighbor[i][2]]->At(r+neighbor[i][0],c+neighbor[i][1]) < THRESH) { good=false; break; } } if (good) { curoctave.push_back(Vector3f(r,c,s)); #ifdef ZZZ_LIB_BOOST ReportMaxima(dog_[o][s],r,c); #endif // ZZZ_LIB_BOOST } } //find minima for (int s=1; s<nscale-2; s++) for (int r=IMAGEEDGEDIST+1; r<nrow-IMAGEEDGEDIST-2; r++) for (int c=IMAGEEDGEDIST+1; c<ncol-IMAGEEDGEDIST-2; c++) { float cur=dog_[o][s]->At(r,c); bool good=true; for (int i=0; i<26; i++) { if (dog_[o][s+neighbor[i][2]]->At(r+neighbor[i][1],c+neighbor[i][0]) - cur < THRESH) { good=false; break; } } if (good) { curoctave.push_back(Vector3f(r,c,s)); #ifdef ZZZ_LIB_BOOST ReportMaxima(dog_[o][s],r,c); #endif // ZZZ_LIB_BOOST } } keypoint_.push_back(curoctave); } } void SIFT::BuildDoGOctaves(Image<float> * image) { ori_=image; BuildGaussianOctaves(); BuildDoGOctaves(); } void SIFT::BuildDoGOctaves() { ClearOctave(dog_); for (size_t i=0; i<gauss_.size(); i++) { vector<Image<float> *> cur; for (size_t j=1; j<gauss_[i].size(); j++) { Image<float> *img=new Image<float>(*(gauss_[i][j])); *img-=*(gauss_[i][j-1]); cur.push_back(img); #ifdef ZZZ_LIB_BOOST ReportBuildOctave(img); #endif // ZZZ_LIB_BOOST } dog_.push_back(cur); } } Image<float> * SIFT::ScaleInitImage() { //scale by omin and blur by initsigma int scale; if (OMIN<0) scale=-OMIN; else scale=OMIN; Image<float> scale_img(*ori_); for (int i=0; i<scale; i++) scale_img.Resize(scale_img.Rows()*2,scale_img.Cols()*2); double sigma = sqrt(SIGMA * SIGMA - INITSIGMA * INITSIGMA * Pow(2,scale*2)); //Why minus? Image<float> *ret=new Image<float>; ImageFilter<float>::GaussBlurImage(&scale_img, ret,4, sigma); //treat the scaled image as the first one, easier for later process ncol_=ori_->Cols()*Pow(2,scale); nrow_=ori_->Rows()*Pow(2,scale); return ret; } void SIFT::BuildGaussianOctaves() { ClearOctave(gauss_); // start with initial source image Image<float> * timage = ScaleInitImage(); for (int i = 0; i < NOCTAVE; i++) { zout<<"BuildGaussianOctave:"<<i<<endl; vector<Image<float> *> scales = BuildGaussianScales(timage); gauss_.push_back(scales); // halve the image size for next iteration Image<float> *simage=new Image<float>; scales[NSCALE]->HalfImageTo(*simage); timage = simage; //ATTENTION: //timage is push_backed into scales when call BuildGaussianScales() //so don't delete timage except for the last useless one } delete timage; } vector<Image<float> *> SIFT::BuildGaussianScales(Image<float> * image) { vector<Image<float> *> GScales; double k = Pow(2, 1.0/(float)NSCALE); GScales.push_back(image); for (int i = 1; i < NSCALE + 3; i++) { // 2 passes of 1D on original float sigma1 = Pow(k, i - 1) * SIGMA; float sigma2 = Pow(k, i) * SIGMA; float sigma = sqrt(sigma2*sigma2 - sigma1*sigma1); Image<float>* dst = new Image<float>; ImageFilter<float>::GaussBlurImage(GScales[GScales.size() - 1], dst,4, sigma); GScales.push_back(dst); #ifdef ZZZ_LIB_BOOST ReportBuildGaussian(dst); #endif // ZZZ_LIB_BOOST } return GScales; } void SIFT::ClearOctave(Octave &octave) { for (size_t i=0; i<octave.size(); i++) for (size_t j =0; j<octave[i].size(); j++) delete octave[i][j]; octave.clear(); } } // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFT.cpp
C++
gpl3
7,497
#pragma once #include <Image/Image.hpp> #include <Math/Math.hpp> #include <3rdParty/boostsignal2.hpp> #include <Utility/Log.hpp> namespace zzz{ class SIFT { public: SIFT(){} ~SIFT() { ClearOctave(gauss_); ClearOctave(dog_); } void FindKeypoint(Image<float> *img) { ori_=img; ncol_=img->Cols(); nrow_=img->Rows(); NSCALE=3; OMIN=0; NOCTAVE=(int)floor(log(double(Min(ncol_,nrow_)))/log(2.0))-OMIN-3; SIGMA = (float)1.6*Pow(2,1/NSCALE); INITSIGMA = 0.5f ; THRESH = 0; //0.04f / NSCALE / 2 ; EDGETHRESH = 10.0; IMAGEEDGEDIST = 10; zout<<"BuildGaussianOctaves\n"; BuildGaussianOctaves(); zout<<"BuildDoGOctaves\n"; BuildDoGOctaves(); zout<<"FindLocalMaxima\n"; FindLocalMaxima(); zout<<"RefineKeypoint\n"; RefineKeypoint(); // int nkey=0; // for (size_t i=0; i<keypoint_.size(); i++) // nkey+=keypoint_[i].size(); // zout<<"found:"<<nkey<<endl; } public: #ifdef ZZZ_LIB_BOOST boost::signals2::signal<void(Image<float>*)> ReportBuildGaussian; boost::signals2::signal<void(Image<float>*)> ReportBuildOctave; boost::signals2::signal<void(Image<float>*,int,int)> ReportMaxima; #endif //private: typedef vector<vector<Image<float>*> > Octave; Image<float> *ori_; int ncol_,nrow_; //size Octave gauss_,dog_; vector<vector<Vector3f> > keypoint_; //parameters float INITSIGMA, SIGMA, THRESH, EDGETHRESH,IMAGEEDGEDIST; int NSCALE, OMIN, NOCTAVE; //clear void ClearOctave(Octave &octave); //refine key point, eliminate low value and edge response void RefineKeypoint(); //find local maxima/minima(init keypoint) void FindLocalMaxima(); //build dog void BuildDoGOctaves(Image<float> * image); void BuildDoGOctaves(); //build gaussian void BuildGaussianOctaves(); //init the original image, scale and blur Image<float> * ScaleInitImage(); //helper for gaussian, blur vector<Image<float> *> BuildGaussianScales(Image<float> * image); }; } // namespace zzz
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFT.hpp
C++
gpl3
2,083
#pragma once #include <common.hpp> #include <Image/Image.hpp> #include <Image/ImageCoord.hpp> #include <Graphics/ColorDefine.hpp> #include <Utility/STLVector.hpp> namespace zzz{ struct SIFTKey { CoordX_Yf32 pos; zfloat32 scale; zfloat32 dir; }; class SIFTKeys { public: static const int KEY_LEN = 128; SIFTKeys(); explicit SIFTKeys(const string &filename); SIFTKeys(const SIFTKeys& other); const SIFTKeys& operator=(const SIFTKeys &other); void LoadKeyFile(const string &filename); void DrawOnImage(Image3uc &img, Colorf color=ColorDefine::white); STLVector<SIFTKey> keys_; STLVector<Vector<KEY_LEN, zuint8> > desc_; }; SIMPLE_IOOBJECT(SIFTKey); template<> class IOObject<SIFTKeys> { public: typedef SIFTKeys DataType; static const int RF_KEYS = 1; static const int RF_DESC = 2; static void WriteFileR(RecordFile &rf, const DataType &src) { IOObj::WriteFileR(rf, RF_KEYS, src.keys_); IOObj::WriteFileR(rf, RF_DESC, src.desc_); } static void ReadFileR(RecordFile &rf, DataType &dst) { IOObj::ReadFileR(rf, RF_KEYS, dst.keys_); IOObj::ReadFileR(rf, RF_DESC, dst.desc_); } }; }
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFTKeys.hpp
C++
gpl3
1,184
#pragma once #include <3rdParty/ANNChar4Vector.hpp> #include <common.hpp> #include "SIFTKeys.hpp" namespace zzz{ #ifdef ZZZ_LIB_ANN_CHAR class SIFTMatcher { public: SIFTMatcher(); SIFTMatcher(const SIFTKeys &keys); void Prepair(const SIFTKeys &keys); void Match(const SIFTKeys &keys); void Sort(); vector<pair<zuint, zuint> > matches_; vector<double> dists_; private: ANNChar4Vector<128> ann_; zuint keys1n_; }; #endif }
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFTMatcher.hpp
C++
gpl3
467
#include "SIFTMatcher.hpp" #ifdef ZZZ_LIB_ANN_CHAR #include <boost/lambda/lambda.hpp> #include <Utility/CheckPoint.hpp> #include <Utility/CmdParser.hpp> using namespace boost::lambda; namespace zzz{ ZFLAGS_INT(ann_max_visit_pt, 200, "Maximum visit point number for each ann search"); SIFTMatcher::SIFTMatcher(){} SIFTMatcher::SIFTMatcher(const SIFTKeys &keys) { Prepair(keys); } void SIFTMatcher::Prepair(const SIFTKeys &keys) { keys1n_=keys.desc_.size(); ann_.SetData(keys.desc_); } void SIFTMatcher::Match(const SIFTKeys &keys) { //use matching strategy described in Photo Tourism vector<int> dists(keys1n_,-1); vector<int> key12(keys1n_,-1); vector<int> key21(keys.keys_.size(),-1); vector<int> idx; vector<int> dist; ann_.SetMaxPointVisit(ZFLAG_ann_max_visit_pt); //this will increase the search speed severly for (zuint i=0; i<keys.keys_.size(); i++) { ann_.Query(keys.desc_[i],2,idx,dist); if (dist[0]>=0.6*0.6*dist[1]) continue; //only if the first match is far better than the second one if (key12[idx[0]]==-1 && key21[i]==-1) { key12[idx[0]]=i; key21[i]=idx[0]; dists[idx[0]]=dist[0]; } else //if some match happens before, none of them can count as a match! { key12[idx[0]]=-2; key21[i]=-2; } } //write to vector matches_.clear(); matches_.reserve(keys1n_); dists_.clear(); dists_.reserve(keys1n_); for (zuint i=0; i<keys1n_; i++) { if (key12[i]>=0) { matches_.push_back(make_pair(i,key12[i])); dists_.push_back(dists[i]); } } } void SIFTMatcher::Sort() { vector<pair<double,int> > nodes; for (zuint i=0; i<dists_.size(); i++) nodes.push_back(make_pair(dists_[i],i)); sort(nodes.begin(),nodes.end()); vector<pair<zuint,zuint> > new_matches; vector<double> new_dists; for (zuint i=0; i<nodes.size(); i++) { new_matches.push_back(matches_[nodes[i].second]); new_dists.push_back(dists_[nodes[i].second]); } matches_=new_matches; dists_=new_dists; } } #endif // ZZZ_LIB_ANN_CHAR
zzz-engine
zzzEngine/zVision/zVision/Feature/SIFTMatcher.cpp
C++
gpl3
2,138
#pragma once #include "TensorVoter.hpp" #include <3rdparty/ANN4Vector.hpp> #include <GraphicsAlgo/RotationMatrix.hpp> #include <Utility/TextProgress.hpp> #include <Xml/XML.hpp> #include <Math/Random.hpp> namespace zzz{ template<int D> class TensorVoting : public IOData { public: TensorVoting():sigma_(18.25),pred_(false) { int e=180; SampleNumbers[0]=0; SampleNumbers[1]=e; for (int i=2; i<D; i++) SampleNumbers[i]=SampleNumbers[i-1]*e; for (int i=1; i<D; i++) { SampleDirections[i].reserve(SampleNumbers[i]); for (int j=0; j<SampleNumbers[i]; j++) { Vector<D,double> dir=RandGen.RandOnDim(i+1); if (Abs(dir.Len()-1.0)<EPSILON) SampleDirections[i].push_back(dir); else cout<<"bad "<<dir<<endl; } } } //from voter vote voters, result in votees //votees are the same position as voters //ANN to decide which to vote //search scheme is hard coded, need change void Vote(vector<TensorVoter<D> > &voters, vector<TensorVoter<D> > &votees) { vector<int> votecount(voters.size(),0); vector<int> (voters.size(),0); votees.assign(voters.begin(),voters.end()); //not clear means it vote to itself // for (zuint i=0; i<votees.size(); i++) votees[i].T=Matrix<D,D,double>(0.0); vector<Vector<D,double> > pos; for (zuint i=0; i<voters.size(); i++) pos.push_back(voters[i].Position); ANN4Vector<D,double> anntree(pos); TextProgress tp("%b %n",voters.size()-1,0); tp.ShowProgressBegin(); for (zuint i=0; i<voters.size(); i++) { tp.ShowProgress(i); //this part decide which votees will receive the voting //may need to change for future usage vector<int> idx; vector<double> dist; int number=anntree.RangeQuery(voters[i].Position,10,0,idx,dist); anntree.RangeQuery(voters[i].Position,10,number,idx,dist); // anntree.Query(voters[i].Position,7,idx,dist); for (zuint j=0; j<idx.size(); j++) if (i!=idx[j]) { votees[idx[j]].T+=GenTensorVote(voters[i],votees[idx[j]]); if (IsBad(votees[idx[j]].T[0])) cout<<"bad\n"; votecount[idx[j]]++; } } for (zuint i=0; i<votees.size(); i++) { if (votecount[i]>0) votees[i].T/=votecount[i]; } tp.ShowProgressEnd(); } //private: int SampleNumbers[D]; Vector<D,vector<Vector<D,double> > > SampleDirections; RandomHyperSphere2<D,double> RandGen; const double sigma_; //private: //just encode the StickTensor and add void Combine(Matrix<D,D,double> &TensorVote, const Vector<D,double> &StickVote) { //it performs tensor addition, given a stick vote for (int i=0; i<D; i++) for (int j=i; j<D; j++) { double more=StickVote[i]*StickVote[j]; TensorVote(i,j)+=more; if (i!=j) TensorVote(j,i)+=more; } } //just encode the StickTensor and add void Combine(Matrix<D,D,double> &TensorVote, const Vector<D,double> &StickVote, double Weight) { //it performs tensor addition, given a stick vote for (int i=0; i<D; i++) for (int j=i; j<D; j++) { double more=Weight*StickVote[i]*StickVote[j]; TensorVote(i,j)+=more; if (i!=j) TensorVote(j,i)+=more; } } //lookup table and interpolate //result should be the close to GenStickVote Matrix<D,D,double> GetVotePre(const Vector<D,double> &voterPosition, \ const Vector<D,double> &Direction, \ const Vector<D,double> &voteePosition,\ int level) { Vector<D,double> newVoteePosition=voteePosition-voterPosition; Vector<D,double> newNormal(0); newNormal[0]=1; Matrix<D,D,double> mat=GetRotationBetweenVectors(Direction,newNormal); newVoteePosition=mat*newVoteePosition; Matrix<D,D,double> tensor=GetPreData(level,newVoteePosition); Matrix<D,D,double> matt(mat); matt.Transpose(); tensor=matt*tensor*mat; return tensor; } //voterPosition is at 0 and Direction is (1,0,...) //help funciton for GenStickVote2 Vector<D,double> GenStickVote2Helper(const Vector<D,double> &voteePosition) { //a stick vote (vector) is returned. Vector<D,double> l=voteePosition; //check if voter and votee are connected by high curvature double llen=l.Normalize(); double cosangle=l[0]; double angle=SafeACos(cosangle); if (angle>C_PI_2) angle=Abs(angle-PI); if (angle<C_PI_4) return Vector<D,double>(0); //smoothness constrain violated //voter and votee on a straight line, or voter and votee are the same point //this could avoid no sphere center exist if (angle==C_PI_2 || voteePosition==Vector<D,double>(0)) { Vector<D,double> nor(0); nor[0]=1.0; return nor; } //decide stick direction and length double sintheta=cosangle; double arclen=(C_PI_2-angle)*llen/sintheta; double phi=2*sintheta/llen; Vector<D, double> center(0); center[0]=1.0/phi; Vector<D, double> stick_vote=center-voteePosition; stick_vote.Normalize(); stick_vote*=exp(- (arclen*arclen+phi*phi)/sigma_/sigma_); return stick_vote; } //rotate and translate to make voterPosition to 0 and Direction to (1,0,...) //result should be the same as GenStickVote Vector<D,double> GenStickVote2(const Vector<D,double> &voterPosition, \ const Vector<D,double> &Direction, \ const Vector<D,double> &voteePosition) { Vector<D,double> newVoteePosition=voteePosition-voterPosition; Vector<D,double> newNormal(0); newNormal[0]=1; Matrix<D,D,double> mat=GetRotationBetweenVectors(Direction,newNormal); newVoteePosition=mat*newVoteePosition; Vector<D,double> stick_vote=GenStickVote2Helper(newVoteePosition); //mat.Invert(); mat.Transpose(); //for rotation matrix transpose is invert return mat*stick_vote; } //original version Vector<D,double> GenStickVote(const Vector<D,double> &voterPosition, \ const Vector<D,double> &Direction, \ const Vector<D,double> &voteePosition) { //a stick vote (vector) is returned. Vector<D,double> v=voteePosition-voterPosition; //check if voter and votee are connected by high curvature double llen=v.Normalize(); double cosangle=Dot(Direction,v); double angle=SafeACos(cosangle); if (angle>C_PI_2) angle=Abs(angle-PI); if (angle<C_PI_4) return Vector<D,double>(0); //smoothness constrain violated //voter and votee on a straight line, or voter and votee are the same point //this could avoid no sphere center exist if (angle==C_PI_2 || voterPosition==voteePosition) return Direction*exp(-llen*llen/sigma_/sigma_); //decide stick direction and length double sintheta=cosangle; double arclen=(C_PI_2-angle)*llen/sintheta; double phi=2*sintheta/llen; Vector<D, double> stick_vote=voterPosition+Direction/phi-voteePosition; stick_vote.Normalize(); stick_vote*=exp(- (arclen*arclen+phi*phi)/sigma_/sigma_); return stick_vote; } //isolated get tensor for different level //it can be stick tensor, n-dimentianl plate tensor or ball tensor //this version automatically detect precomputed data //if exist it prefer to use those data to computer or return directly //if not it will computer from raw Matrix<D,D,double> GetLevelTensorPre(const TensorVoter<D> &voter, const Vector<D,double> &voteePosition, int level) { if (pred_[level]) return GetVotePre(voter.Position,voter.Directions.Row(level),voteePosition,level); if (level==0) { Matrix<D,D,double> stickTensor(0); Vector<D,double> vecVote=GenStickVote(voter.Position,voter.Directions.Row(0),voteePosition); Combine(stickTensor, vecVote); return stickTensor; } else if (level==D-1) { Matrix<D,D,double> ballTensor(0); for (int j=0; j<SampleNumbers[level]; j++) { Vector<D,double> randomDirection=SampleDirections[level][j]; if (pred_[0]) { ballTensor+=GetVotePre(voter.Position,randomDirection,voteePosition,0); if (IsBad(ballTensor[0])) { cout<<voter.Position<<endl; cout<<randomDirection<<endl; cout<<voteePosition<<endl; exit(0); } } else { Vector<D,double> vecVote=GenStickVote(voter.Position,randomDirection,voteePosition); Combine(ballTensor, vecVote); } } return ballTensor/SampleNumbers[level]; } else { Matrix<D,D,double> plateTensor(0); for (int j=0; j<SampleNumbers[level]; j++) { Vector<D,double> randomDirection=voter.Directions*SampleDirections[level][j]; double x=randomDirection.Len(); if (pred_[0]) plateTensor+=GetVotePre(voter.Position,randomDirection,voteePosition,0); else { Vector<D,double> vecVote=GenStickVote(voter.Position,randomDirection,voteePosition); Combine(plateTensor, vecVote); } } return plateTensor/SampleNumbers[level]; } } //isolated get tensor for different level //it can be stick tensor, n-dimentianl plate tensor or ball tensor Matrix<D,D,double> GetLevelTensor(const TensorVoter<D> &voter, const Vector<D,double> &voteePosition, int level) { if (level==0) { Matrix<D,D,double> stickTensor(0); Vector<D,double> vecVote=GenStickVote(voter.Position,voter.Directions.Row(0),voteePosition); Combine(stickTensor, vecVote); return stickTensor; } else if (level==D-1) { Matrix<D,D,double> ballTensor(0); for (int j=0; j<SampleNumbers[level]; j++) { Vector<D,double> randomDirection=SampleDirections[level][j]; Vector<D,double> vecVote=GenStickVote(voter.Position,randomDirection,voteePosition); Combine(ballTensor, vecVote); } return ballTensor/SampleNumbers[level]; } else { Matrix<D,D,double> plateTensor(0); for (int j=0; j<SampleNumbers[level]; j++) { Vector<D,double> randomDirection=voter.Directions*SampleDirections[level][j]; randomDirection=voter.Directions*randomDirection; double x=randomDirection.Len(); Vector<D,double> vecVote=GenStickVote(voter.Position,randomDirection,voteePosition); Combine(plateTensor, vecVote); } return plateTensor/SampleNumbers[level]; } } //one voter votes one votee //in this function, GenStickVote can be replace by several version, should give out the same result Matrix<D,D,double> GenTensorVote(const TensorVoter<D>&voter, const TensorVoter<D>&votee) { //First, the stick components of a tensor vote is computed (if direction is given). Then, all other tensor components (plates and balls) are computed, by integrating the resulting stick votes cast by a rotating stick at the voter. Vector<D,double> voterSaliency; for (int i=0; i<D-1; i++) voterSaliency[i]=voter.Lambda[i]-voter.Lambda[i+1]; voterSaliency[D-1]=voter.Lambda[D-1]; Matrix<D,D,double> outTensor(0); for (int i=0; i<D; i++) { if (voterSaliency[i]>0) { outTensor+=GetLevelTensorPre(voter,votee.Position,i)*voterSaliency[i]; } } return outTensor; } public: //pre compute data //sigma is parameter, 0.18 in the paper //radius is half the length of square //gridsize is the sample density, with radius will define the sample number void Precompute(double sigma, double radius, double gridsize) { TensorVoter<D> tmpvoter(Vector<D,double>(0)); gridSize_=gridsize; int size=radius/gridsize; center_=size; size=size*2+1; Vector<D,zuint> Size(size); for (int i=0; i<D; i++) { if (pred_[i]) continue; cout<<i<<'/'<<D<<endl; data_[i].SetSize(Size); Vector<D,zuint> coord(0); int curpos=0; TextProgress tp("%b %n",data_[i].size()-1,0); tp.ShowProgressBegin(); bool good=true; while(good) { tp.ShowProgress(curpos++); //cal real coord Vector<D,double> realcoord(coord); realcoord-=Vector<D,double>(center_); realcoord*=gridSize_; //sample data_[i](coord)=GetLevelTensorPre(tmpvoter,realcoord,i); //next coord coord[D-1]++; //normalize int cur=D-1; while(true) { if (coord[cur]==size) { coord[cur]=0; cur--; if (cur==-1) //overflow { good=false; break; } coord[cur]++; } else break; //done } } tp.ShowProgressEnd(); pred_[i]=true; } } //get precomputed data //voter at (0,0,0) normal (1,0,0) //n-d interpolation Matrix<D,D,double> GetPreData(int level, Vector<D,double> coord) { coord/=gridSize_; coord+=Vector<D,double>((data_[level].Size()-Vector<D,zuint>(1))/2); return data_[level].Interpolate(coord); } //save pre computed data bool SaveFile(const string &filename) { XML xml; XMLNode head=xml.AppendNode("TensorVotePreData"); head<<make_pair("GridSize",ToString(gridSize_)); head<<make_pair("Dimension",ToString(D)); for (int i=0; i<D; i++) { XMLNode tnode=head.AppendNode(StringPrintf("TensorNode_%d",i).c_str()); tnode<<make_pair("SampleSize",ToString(data_[i].Size())); string code; Base64Encode((char*)data_[i].Data(),data_[i].size()*sizeof(Matrix<D,D,double>),code); tnode<<code; } return xml.SaveFile(filename); } //load pre computed data bool LoadFile(const string &filename) { XML xml; if (!xml.LoadFile(filename)) return false; XMLNode head=xml.GetNode("TensorVotePreData"); if (D!=FromString<int>(head.GetAttribute("Dimension"))) { cout<<"Load error, Dimension dismatch!\n"; return false; } pred_=false; gridSize_=FromString<double>(head.GetAttribute("GridSize")); for (int i=0; i<D; i++) { XMLNode tnode=head.GetNode(StringPrintf("TensorNode_%d",i).c_str()); Vector<D,zuint> size=FromString<Vector<D,zuint> >(tnode.GetAttribute("SampleSize")); data_[i].SetSize(size); Base64Decode(tnode.GetText(),(char*)data_[i].Data(),data_[i].size()*sizeof(Matrix<D,D,double>)); pred_[i]=true; } center_=(data_[0].Size()-Vector<D,zuint>(1))/2; return true; } //private: //precomputed data_ Vector<D, Array<D,Matrix<D,D,double> > > data_; Vector<D, bool> pred_; double gridSize_; Vector<D, zuint> center_; }; }
zzz-engine
zzzEngine/zVision/zVision/TensorVoting/TensorVoting.hpp
C++
gpl3
15,139
#pragma once #include <zMat.hpp> namespace zzz{ template<int D> struct TensorVoter { TensorVoter():Position(0),Lambda(0),Directions(0),T(0){} //init from position //and init as a uniform ball tensor TensorVoter(const Vector<D, double> &pos) :Position(pos),Lambda(1),Directions(0),T(0) { //ball init for (int i=0; i<D; i++) Directions(i,i)=1; } //init from a vector //and init as a stick tensor //stick from pos point to normal, therefore normal-pos is normal TensorVoter(const Vector<D, double> &pos, Vector<D, double> normal) :Position(pos),Lambda(0),Directions(0),T(0) { //stick init normal-=pos; Lambda[0]=normal.Normalize(); Vector<D, double> ori(0); ori[0]=1; Matrix<D,D,double> mat=GetRotationBetweenVectors(ori,normal); for (int i=0; i<D; i++) { Directions(i,i)=1; Directions.Row(i)=mat*Directions.Row(i); } } //init from Tensor //you can save and load T TensorVoter(const Vector<D, double> &pos, const Matrix<D, D, double> &t) :Position(pos),T(t) { //init from Tensor Decomp(); } void Decomp() { zMatrix<double> A(Dress(T)),U,S,VT; SVD(A,U,S,VT); Dress<zColMajor,double,D>(Lambda)=S; Dress(Directions)=Trans(U); } void Encode() { Matrix<D, D, double> stick(GetStickVote()); Matrix<D, D, double> plate(GetPlateVote()); Matrix<D, D, double> ball(GetBallVote()); T=stick+plate+ball; } //StickVote part Matrix<D, D, double> GetStickVote() { //TODO Optimize Matrix<D, D, double> mat; double lambda=Lambda[0]-Lambda[1]; for (int i=0; i<D; i++) for (int j=0; j<D; j++) mat(i,j)=lambda*Directions(0,i)*Directions(0,j); return mat; } //PlateVote part Matrix<D, D, double> GetPlateVote() { //TODO Optimize Matrix<D, D, double> mat(0); Matrix<D, D, double> Pk=Matrix<D,1,double>(&(Directions(0,0)))*Matrix<1,D,double>(&(Directions(0,0))); for (int i=1; i<D-1; i++) { double lambda=Lambda[i]-Lambda[i+1]; Pk+=Matrix<D,1,double>(&(Directions(i,0)))*Matrix<1,D,double>(&(Directions(i,0))); mat+=Pk*lambda; } return mat; } //BallVote part Matrix<D, D, double> GetBallVote() { Matrix<D, D, double> Pk=Matrix<D,1,double>(&(Directions(0,0)))*Matrix<1,D,double>(&(Directions(0,0))); for (int i=1; i<D; i++) { Pk+=Matrix<D,1,double>(&(Directions(i,0)))*Matrix<1,D,double>(&(Directions(i,0))); } Matrix<D, D, double> mat(Pk*Lambda[D-1]); return mat; } bool operator==(const TensorVoter<D>&other){return Position==other.Position;} //data //voter 3d position Vector<D,double> Position; //eigen values Vector<D,double> Lambda; //eigen vectors Matrix<D,D,double> Directions; //T Matrix<D, D, double> T; }; }
zzz-engine
zzzEngine/zVision/zVision/TensorVoting/TensorVoter.hpp
C++
gpl3
2,936
#pragma once // Separate link so when change a lib, only link needs redo. #include "zImageConfig.hpp" #ifndef ZZZ_NO_PRAGMA_LIB #ifdef ZZZ_COMPILER_MSVC #ifdef ZZZ_DEBUG #ifndef ZZZ_OS_WIN64 #pragma comment(lib,"zVisionD.lib") #else #pragma comment(lib,"zVisionD_x64.lib") #endif // ZZZ_OS_WIN64 #else #ifndef ZZZ_OS_WIN64 #pragma comment(lib,"zVision.lib") #else #pragma comment(lib,"zVision_x64.lib") #endif // ZZZ_OS_WIN64 #endif #ifdef ZZZ_LIB_FAST #ifdef _DEBUG #pragma comment(lib,"fastD.lib") #else #pragma comment(lib,"fast.lib") #endif // _DEBUG #endif // ZZZ_LIB_DEVIL #endif // ZZZ_COMPILER_MSVC #endif // ZZZ_NO_PRAGMA_LIB
zzz-engine
zzzEngine/zVision/zVision/zVisionAutoLink.hpp
C++
gpl3
679
SET(THISLIB zCore) FILE(GLOB_RECURSE LibSrc *.cpp *.c) IF( "${DEBUG_MODE}" EQUAL "1") SET(THISLIB ${THISLIB}D) ENDIF() IF( "${BIT_MODE}" EQUAL "64" ) SET(THISLIB ${THISLIB}_X64) ENDIF() ADD_LIBRARY(${THISLIB} STATIC ${LibSrc}) #MESSAGE("zCore Lib Path: ${BASENAME}")
zzz-engine
zzzEngine/zCore/CMakeLists.txt
CMake
gpl3
279
#pragma once // Separate link so when change a lib, only link needs redo. #include "zCoreConfig.hpp" #ifndef ZZZ_NO_PRAGMA_LIB #ifdef ZZZ_COMPILER_MSVC #ifdef ZZZ_LIB_ZLIB #ifdef ZZZ_OS_WIN64 #pragma comment(lib, "zlib_x64.lib") #else #pragma comment(lib, "zlib.lib") #endif #endif #ifdef ZZZ_LIB_ANN #pragma comment(lib, "ann.lib") #endif // ZZZ_LIB_ANN #ifdef ZZZ_LIB_ANN_CHAR #pragma comment(lib, "ann_1.1_char.lib") #endif // ZZZ_LIB_ANN_CHAR #ifdef ZZZ_LIB_LAPACK #ifdef ZZZ_OS_WIN64 #pragma comment(lib, "clapack_X64.lib") #pragma comment(lib, "libf2c_X64.lib") // fortune to c #pragma comment(lib, "BLAS_X64.lib") // original blas, use this or following atlas #else //#pragma comment(lib, "atlas_clapack.lib") #pragma comment(lib, "clapack.lib") #pragma comment(lib, "libf2c.lib") // fortune to c //#pragma comment(lib, "BLAS.lib") // original blas, use this or following atlas #pragma comment(lib, "cblaswrap.lib") // f2c_blas to c_blas #pragma comment(lib, "libcblas.lib") // cblas to atlas implementation #pragma comment(lib, "libatlas.lib") // atlas implementation #endif // ZZZ_OS_WIN64 #endif // ZZZ_LIB_LAPACK #ifdef ZZZ_LIB_EXIF #ifdef ZZZ_DEBUG #pragma comment(lib, "exiv2D.lib") #pragma comment(lib, "libexpatD.lib") #pragma comment(lib, "xmpsdkD.lib") #pragma comment(lib, "zlib.lib") #else #pragma comment(lib, "exiv2.lib") #pragma comment(lib, "libexpat.lib") #pragma comment(lib, "xmpsdk.lib") #pragma comment(lib, "zlib.lib") #endif #endif // ZZZ_LIB_EXIF #ifdef ZZZ_LIB_FFTW #pragma comment(lib, "libfftw3-3.lib") #endif // ZZZ_LIB_FFTW #ifdef ZZZ_LIB_GCO #ifdef ZZZ_DEBUG #pragma comment(lib, "gcolibD.lib") #else #pragma comment(lib, "gcolib.lib") #endif // ZZZ_DEBUG #endif // ZZZ_LIB_GCO #ifdef ZZZ_LIB_LOKI #ifdef ZZZ_DEBUG #pragma comment(lib, "lokiD.lib") #else #pragma comment(lib, "loki.lib") #endif #endif // ZZZ_LIB_LOKI #ifdef ZZZ_LIB_MINPACK #pragma comment(lib, "cminpack.lib") #endif // ZZZ_LIB_MINPACK #ifdef ZZZ_LIB_TINYXML #ifdef ZZZ_DEBUG #pragma comment(lib, "tinyxmld_STL.lib") #else #pragma comment(lib, "tinyxml_STL.lib") #endif #endif // ZZZ_LIB_TINYXML #ifdef ZZZ_LIB_PTHREAD #pragma comment(lib, "pthreadVC2.lib") #endif // ZZZ_LIB_PTHREAD #ifdef ZZZ_LIB_SBA #ifdef ZZZ_OS_WIN64 #ifdef ZZZ_DEBUG #pragma comment(lib, "sbaD_X64.lib") #else #pragma comment(lib, "sba_X64.lib") #endif // ZZZ_DEBUG #else #ifdef ZZZ_DEBUG #pragma comment(lib, "sbaD.lib") #else #pragma comment(lib, "sba.lib") #endif // ZZZ_DEBUG #endif // ZZZ_OS_WIN64 #endif // ZZZ_LIB_SBA #ifdef ZZZ_LIB_CGAL #ifdef ZZZ_DEBUG #pragma comment(lib, "CGAL-vc100-mt-gd.lib") #pragma comment(lib, "libgmp-10.lib") #else #pragma comment(lib, "CGAL-vc100-mt.lib") #pragma comment(lib, "libgmp-10.lib") #endif // ZZZ_DEBUG #endif // ZZZ_LIB_CGAL #ifdef ZZZ_LIB_FAST #ifdef ZZZ_DEBUG #pragma comment(lib, "fastD.lib") #else #pragma comment(lib, "fast.lib") #endif // ZZZ_DEBUG #endif // ZZZ_LIB_FAST #ifdef ZZZ_LIB_OPENCV #ifdef ZZZ_DEBUG #pragma comment(lib, "opencv_calib3d220d.lib") #pragma comment(lib, "opencv_contrib220d.lib") #pragma comment(lib, "opencv_core220d.lib") #pragma comment(lib, "opencv_features2d220d.lib") #pragma comment(lib, "opencv_ffmpeg220d.lib") #pragma comment(lib, "opencv_flann220d.lib") #pragma comment(lib, "opencv_gpu220d.lib") #pragma comment(lib, "opencv_highgui220d.lib") #pragma comment(lib, "opencv_imgproc220d.lib") #pragma comment(lib, "opencv_legacy220d.lib") #pragma comment(lib, "opencv_ml220d.lib") #pragma comment(lib, "opencv_objdetect220d.lib") #pragma comment(lib, "opencv_video220d.lib") #else #pragma comment(lib, "opencv_calib3d220.lib") #pragma comment(lib, "opencv_contrib220.lib") #pragma comment(lib, "opencv_core220.lib") #pragma comment(lib, "opencv_features2d220.lib") #pragma comment(lib, "opencv_ffmpeg220.lib") #pragma comment(lib, "opencv_flann220.lib") #pragma comment(lib, "opencv_gpu220.lib") #pragma comment(lib, "opencv_highgui220.lib") #pragma comment(lib, "opencv_imgproc220.lib") #pragma comment(lib, "opencv_legacy220.lib") #pragma comment(lib, "opencv_ml220.lib") #pragma comment(lib, "opencv_objdetect220.lib") #pragma comment(lib, "opencv_video220.lib") #endif // ZZZ_DEBUG #endif // ZZZ_LIB_FAST #ifdef ZZZ_LIB_TAUCS #pragma comment(lib, "libtaucs.lib") #pragma comment(lib, "libmetis.lib") #pragma comment(lib, "libf77blas.lib") #pragma comment(lib, "clapack.lib") #pragma comment(lib, "libf2c.lib") // fortune to c #pragma comment(lib, "cblaswrap.lib") // f2c_blas to c_blas #pragma comment(lib, "f77blaswrap.lib") // f2c_blas to f77_blas //#pragma comment(lib, "BLAS.lib") // original blas, use this or following atlas #pragma comment(lib, "libcblas.lib") // cblas to atlas implementation #pragma comment(lib, "libatlas.lib") // atlas implementation #endif // ZZZ_LIB_TAUCS #ifdef ZZZ_LIB_ALGLIB #ifdef ZZZ_DEBUG #pragma comment(lib, "alglibD.lib") #else #pragma comment(lib, "alglib.lib") #endif // ZZZ_DEBUG #endif // ZZZ_LIB_ALGLIB #ifdef ZZZ_LIB_YAML_CPP #ifdef ZZZ_OS_WIN64 #ifdef ZZZ_DEBUG #pragma comment(lib, "yaml-cppD_X64.lib") #else #pragma comment(lib, "yaml-cpp_X64.lib") #endif // ZZZ_DEBUG #else #ifdef ZZZ_DEBUG #pragma comment(lib, "yaml-cppD.lib") #else #pragma comment(lib, "yaml-cpp.lib") #endif // ZZZ_DEBUG #endif // ZZZ_OS_WIN64 #endif // ZZZ_LIB_YAML_CPP #endif // ZZZ_COMPILER_MSVC #endif // ZZZ_NO_PRAGMA_LIB
zzz-engine
zzzEngine/zCore/zCore/zCoreAutoLink3rdParty.hpp
C++
gpl3
5,632
#define ZCORE_SOURCE #include "BraceFile.hpp" #include "StringTools.hpp" #include "Log.hpp" namespace zzz{ BraceItem::~BraceItem() { Clear(); } void BraceItem::Clear() { for (vector<BraceItem*>::iterator vi=children_.begin();vi!=children_.end();vi++) delete *vi; children_.clear(); } BraceItem* BraceItem::AddNode(const string &str, const char h, const char t) { children_.push_back(new SmallBraceItem); children_.back()->text_=str; children_.back()->head_=h; children_.back()->tail_=t; return children_.back(); } ///////////////////////////////////////////////////////////////////////////////// //BraceFile void BraceFile::SetBraces(const string &braces) { braces_=braces; } bool BraceFile::LoadFile(const string & filename) { head_.Clear(); stack<BraceItem*> parents; parents.push(&head_); BraceItem* parent=&head_; ifstream fi(filename); if (!fi.good()) { ZLOG(ZERROR)<<"Cannot open file: "<<filename<<endl; return false; } bool inQuote=false; bool inComment=false; string str; while(true) { string line; getline(fi,line); if (fi.fail()) break; zuint linelen=line.size(); for (zuint i=0; i<linelen; i++) { char now=line[i]; if (inComment && now!='*') continue; //in block comment, ignore else if (inQuote && now!='\"') //in quotation, add { str+=now; continue; } else if (now=='*') { if (i<linelen-1 && line[i+1]=='/') //go out of block comment, eat next / { inComment=false; i++; continue; } } else if (now=='/') { if (i<linelen-1 && line[i+1]=='/') //go in line comment, stop processing this line; { break; } if (i<linelen-1 && line[i+1]=='*') //go in into block comment, eat the next '*' { i++; inComment=true; continue; } } else if (now=='\"') //go in or out of quotation, add anyway { str+=now; inQuote=!inQuote; continue; } else { bool eaten=false; for (zuint j=0; j<braces_.size(); j+=2) { if (now==braces_[j]) //go into block children, finish current, and set new parent { str = Trim(str); if (!str.empty()) { parent->AddNode(str); str.clear(); } //Check Error else if (!parent->children_.empty() || parent->children_.back()->head_==0) { ZLOG(ZERROR)<<"No head for block!\n"; break; } parents.push(parent->children_.back()); //always need to set the back as parent anyway parent=parents.top(); parent->head_=braces_[j]; parent->tail_=braces_[j+1]; eaten=true; break; } else if (now==braces_[j+1]) //go out of block children, finish current, and set old parent { str = Trim(str); if (!str.empty()) { parent->AddNode(str); str.clear(); } parents.pop(); parent=parents.top(); eaten=true; break; } } if (eaten) continue; //already processed, so go on next char } str+=now; //not any special case, just add } //line finish if (inComment || inQuote) continue; //not in any special case, so finish current str = Trim(str); if (!str.empty()) { parent->AddNode(str); str.clear(); } } str = Trim(str); if (!str.empty()) { parent->AddNode(str); str.clear(); } fi.close(); //Check Error if (parents.size()!=1) { ZLOG(ZERROR)<<"Unmatched brace in: "<<parent->text_<<" "<<parent->head_<<endl; return false; } if (inComment) { ZLOG(ZERROR)<<"Unmatched block command /*...*/\n"; return false; } if (inQuote) { ZLOG(ZERROR)<<"Unmatched quotation marks \"...\"\n"; return false; } return true; } bool BraceFile::SaveFile(const string &filename, const string &indent) { ofstream fo(filename.c_str()); if (!fo.good()) { ZLOG(ZERROR)<<"Cannot open file: "<<filename<<endl; return false; } string head=""; stack<BraceItem*> parents; stack<zuint> parents_idx; parents.push(&head_); BraceItem* parent=&head_; zuint i=0; while (true) { if (i==parent->children_.size()) { if (parents.size()==1) break; //finished else { head.erase(head.size() - indent.size(), indent.size()); fo<<head<<parent->tail_<<endl; parents.pop(); parent=parents.top(); i=parents_idx.top()+1; parents_idx.pop(); continue; } } BraceItem* node=parent->children_[i]; istringstream iss(node->text_); while(true) { string line; getline(iss,line); if (iss.fail()) break; if (node->head_==0) fo<<head<<line<<endl; else fo<<head<<line<<' '<<node->head_<<endl; } if (node->head_!=0) //print children { parents.push(node); parent=parents.top(); parents_idx.push(i); i=0; head+=indent; continue; } else i++; } fo.close(); return true; } BraceFile::BraceFile(const string &brace) :BraceNode(&head_,NULL, 0) { SetBraces(brace); } }
zzz-engine
zzzEngine/zCore/zCore/Utility/BraceFile.cpp
C++
gpl3
5,787
#pragma once #include <zCoreConfig.hpp> #include <Define.hpp> #include <common.hpp> namespace zzz { typedef pair<int, zint64> TableItem; class ZCORE_CLASS RecordItem { public: RecordItem(FILE *fp, zint64 itebegin_pos_, RecordItem *parent); void ReadTable(); RecordItem* ReadChild(const zint32 label); RecordItem* ReadFinish(); RecordItem* ReadRepeatBegin(const zint32 label); RecordItem* ReadRepeatChild(); size_t GetRepeatNumber(); RecordItem* ReadRepeatEnd(); size_t Read(const zint32 label, void *data, size_t size, size_t count); size_t Read(void *data, size_t size, size_t count); //////////////////////////////////////////// RecordItem* WriteChild(const zint32 label); RecordItem* WriteFinish(); RecordItem* WriteRepeatBegin(const zint32 label); RecordItem* WriteRepeatChild(); RecordItem* WriteRepeatEnd(); size_t Write(const zint32 label, const void *data, size_t size, size_t count); size_t Write(const void *data, size_t size, size_t count); bool LabelExist(const zint32 label); size_t GetItemNumber(); private: FILE *fp_; zint64 itebegin_pos__; zint64 table_begin_pos_; vector<TableItem> table_; RecordItem *child_; RecordItem *parent_; int repeat_label_; bool CheckLabelExist(const zint32 label); zint64 GetChildPos(const zint32 label); zint64 GetPos(); void SetPos(zint64 pos); friend class RecordFile; }; class ZCORE_CLASS RecordFile { public: RecordFile(); /// Start loading file, it will open the file and wait to read. void LoadFileBegin(const string &filename); /// Finish loading file, it will close file. void LoadFileEnd(); /// Start saving file, it will open the file and wait to write. void SaveFileBegin(const string &filename); /// Finishi saving file, it will write additional data to finish the RecordFile structure void SaveFileEnd(); /////////////////////////////////////////////////// /// Read function /// Start reading a new child node void ReadChildBegin(const zint32 label); /// Finish reading the current node and return to parent node void ReadChildEnd(); /// Start reading a repeat child node void ReadRepeatBegin(const zint32 label); /// Start reading the next repeat child, this need to be called even /// before reading the first repeat child. When it return false, means /// there is no more child. bool ReadRepeatChild(); /// Finish reading a repeat child node. void ReadRepeatEnd(); size_t Read(void *data, size_t size, size_t count); size_t Read(const zint32 label, void *data, size_t size, size_t count); ////////////////////////////////////////////////// /// Write funciton /// Start writing a new child node. void WriteChildBegin(const zint32 label); /// Finish writing the current node and return to parent node. void WriteChildEnd(); /// Start writing a repeat child node void WriteRepeatBegin(const zint32 label); /// Start writing the next repeat child, this need to be called even /// before writing the first repeat child. void WriteRepeatChild(); /// Finish writing a repeat child node. void WriteRepeatEnd(); size_t Write(const void *data, size_t size, size_t count); size_t Write(const zint32 label, const void *data, size_t size, size_t count); bool LabelExist(const zint32 label); private: bool write_; RecordItem *head_; RecordItem *cur_; FILE* fp_; }; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/RecordFile.hpp
C++
gpl3
3,521
#pragma once #include <zCoreConfig.hpp> #include "../common.hpp" #include "Log.hpp" //%b = progress bar //%s = spin //%p = percentage //%n = number namespace zzz { class ZCORE_CLASS TextProgress { public: TextProgress(const string &_content="%s", int endvalue=0, int startvalue=0); void SetValue(int _endvalue, int _startvalue=0); void SetAppearance(char _beginchar='[', char _endchar=']', char _blankchar='-', char _fillchar='+', int _length=10); void SetContent(const string &_content="%s"); void ShowProgressBegin(); void ShowProgress(int _value); void ShowProgressAutoIncrease(); void ShowProgressEnd(bool clear=false); private: void clearLastMsg(); void showBar(); void showSpin(); void showPercentage(); void showNumber(); void showContent(); private: int startvalue; int endvalue; int value; char beginchar, endchar, blankchar, fillchar; int length; string content; int lastlength; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/TextProgress.hpp
C++
gpl3
977
#pragma once #include "../common.hpp" #include "../Xml/RapidXMLNode.hpp" namespace zzz{ class IOData { public: virtual bool LoadFile(const string &)=0; virtual bool SaveFile(const string &)=0; }; class IODataA : public IOData { public: bool SaveFile(const string &filename) { ofstream fo(filename); if (!fo.good()) return false; WriteFileA(fo); fo.close(); } bool LoadFile(const string &filename) { ifstream fi(filename); if (!fi.good()) return false; ReadFileA(fi); fi.close(); } virtual void WriteFileA(ostream &fo)=0; virtual void ReadFileA(istream &fi)=0; }; class IODataB : public IOData { public: bool SaveFile(const string &filename) { FILE *fp = fopen(filename.c_str(), "wb"); if (!fp) return false; WriteFileB(fp); fclose(fp); } bool LoadFile(const string &filename) { FILE *fp = fopen(filename.c_str(), "rb"); if (!fp) return false; ReadFileB(fp); fclose(fp); } virtual void WriteFileB(FILE *fp)=0; virtual void ReadFileB(FILE *fp)=0; }; class IODataXml : public IOData { public: virtual void WriteFileXml(RapidXMLNode &node)=0; virtual void ReadFileXml(RapidXMLNode &node)=0; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/IOInterface.hpp
C++
gpl3
1,251
#pragma once #include "AnyHolder.hpp" // Options is a AnyHolder that holds porperties. // These properties should be simple variables and string. namespace zzz { class Options : public AnyHolder { public: bool Parse(const string &str); }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/Options.hpp
C++
gpl3
270
#pragma once #include "FileTools.hpp" #include <3rdParty/SmallObj.hpp> #include "BraceNode.hpp" namespace zzz{ class BraceItem { public: BraceItem():head_(0),tail_(0){} virtual ~BraceItem(); void Clear(); BraceItem* AddNode(const string &str, const char h=0, const char t=0); string text_; char head_,tail_; vector<BraceItem*> children_; }; #ifdef ZZZ_LIB_LOKI typedef SmallObj<BraceItem> SmallBraceItem; #else typedef BraceItem SmallBraceItem; #endif class BraceFile : public BraceNode { public: BraceFile(const string &braces="{}[]"); void SetBraces(const string &braces="{}[]"); bool LoadFile(const string &filename); bool SaveFile(const string &filename, const string &indent="\t"); protected: string braces_; BraceItem head_; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/BraceFile.hpp
C++
gpl3
807
#pragma once #include <zCoreConfig.hpp> #include <vector> #include "Log.hpp" #include "IOObject.hpp" // This class wrapped std::vector // It implements all vector's interface, so simply replace std::vector to zzz::STLVector will make it. // It will print out error instead of crush when allocation fails. namespace zzz { #ifdef ZZZ_STLVECTOR template<typename T> class STLVector : public std::vector<T> { public: typedef std::vector<T>::iterator iterator; typedef std::vector<T>::reverse_iterator reverse_iterator; typedef std::vector<T>::const_iterator const_iterator; typedef std::vector<T>::const_reverse_iterator const_reverse_iterator; typedef typename std::vector<T>::reference reference; typedef typename std::vector<T>::const_reference const_reference; STLVector():vector<T>(){} explicit STLVector(size_type n, const T& value = T()){assign(n, value);} template <class InputIterator> STLVector(InputIterator first, InputIterator last){assign(first, last);} explicit STLVector(const vector<T>& x){assign(x.begin(), x.end());} STLVector(const STLVector<T>& x){assign(x.begin(), x.end());} // iterators STLVector<T>& operator=(const vector<T>& x) { assign(x.begin(), x.end()); return *this; } STLVector<T>& operator=(const STLVector<T>& x) { assign(x.begin(), x.end()); return *this; } using vector<T>::begin; using vector<T>::end; using vector<T>::rbegin; using vector<T>::rend; // capacity using vector<T>::size; using vector<T>::max_size; using vector<T>::resize; using vector<T>::capacity; using vector<T>::clear; using vector<T>::empty; void reserve(size_type n) { try { vector<T>::reserve(n); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } } // element access reference operator[](size_type i) {return at(i);} const_reference operator[](size_type i) const {return at(i);} reference at(size_type i) { ZRCHECK_LT(i, size()); return vector<T>::at(i); } const_reference at(size_type i) const { ZRCHECK_LT(i, size()); return vector<T>::at(i); } reference front() { ZRCHECK_FALSE(empty()) << "Calling front() when vector is empty!"; return vector<T>::front(); } const_reference front() const { ZRCHECK_FALSE(empty()) << "Calling front() when vector is empty!"; return vector<T>::front(); } reference back() { ZRCHECK_FALSE(empty()) << "Calling back() when vector is empty!"; return vector<T>::back(); } const_reference back() const { ZRCHECK_FALSE(empty()) << "Calling back() when vector is empty!"; return vector<T>::back(); } // modifiers template <class InputIterator> void assign(InputIterator first, InputIterator last) { try { vector<T>::assign(first, last); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } } void assign(size_type n, const T& u) { try { vector<T>::assign(n, u); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } } void push_back(const_reference x) { try { vector<T>::push_back(x); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } } using vector<T>::pop_back; iterator insert (iterator position, const T& x) { try { return vector<T>::insert(position, x); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } return end(); } void insert (iterator position, size_type n, const T& x) { try { return vector<T>::insert(position, n, x); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } return end(); } template <class InputIterator> void insert (iterator position, InputIterator first, InputIterator last) { try { vector<T>::insert(position, first, last); } catch(std::bad_alloc) { ZLOGF<<"STLVector: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLVector: Length of vector is longer than "<<ZVAR(max_size())<<ZVAR(sizeof(T)); } } using vector<T>::erase; using vector<T>::swap; // Allocator using vector<T>::get_allocator; // Special T* Data() {return &(front());} const T* Data() const {return &(front());} }; #else template<typename T> class STLVector : public std::vector<T> { public: typedef std::vector<T>::iterator iterator; typedef std::vector<T>::reverse_iterator reverse_iterator; typedef std::vector<T>::const_iterator const_iterator; typedef std::vector<T>::const_reverse_iterator const_reverse_iterator; typedef typename std::vector<T>::reference reference; typedef typename std::vector<T>::const_reference const_reference; STLVector():vector<T>(){} explicit STLVector(size_type n, const T& value = T()):vector<T>(n, value){} template <class InputIterator> STLVector(InputIterator first, InputIterator last):vector<T>(first, last){} explicit STLVector(const vector<T>& x):vector<T>(x){} STLVector(const STLVector<T>& x):vector<T>(x){} // iterators using vector<T>::operator=; using vector<T>::begin; using vector<T>::end; using vector<T>::rbegin; using vector<T>::rend; // capacity using vector<T>::size; using vector<T>::max_size; using vector<T>::resize; using vector<T>::capacity; using vector<T>::empty; using vector<T>::reserve; // element access using vector<T>::operator[]; using vector<T>::at; using vector<T>::front; using vector<T>::back; // modifiers using vector<T>::assign; using vector<T>::push_back; using vector<T>::pop_back; using vector<T>::insert; using vector<T>::erase; using vector<T>::swap; using vector<T>::clear; // Allocator using vector<T>::get_allocator; // Special T* Data() {return &(front());} const T* Data() const {return &(front());} }; #endif template<typename T> class IOObject<STLVector<T*> > { public: static void WriteFileR(RecordFile &rf, const zint32 label, const STLVector<T*> &src) { return WriteFileR1By1(rf, label, src); } static void ReadFileR(RecordFile &rf, const zint32 label, STLVector<T*> &dst) { return ReadFileR1By1(rf, label, dst); } /// When the object inside STLVector is not SIMPLE_IOOBJECT, it must access 1 by 1, /// instead of access as a raw array. static const int RF_SIZE = 1; static const int RF_DATA = 2; static void WriteFileR1By1(RecordFile &rf, const zint32 label, const STLVector<T*> &src) { zuint64 len = src.size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_DATA); for (zuint64 i = 0; i < len; ++i) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, *(src[i])); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR1By1(RecordFile &rf, const zint32 label, STLVector<T*> &dst) { for (zuint i = 0; i < dst.size(); ++i) delete dst[i]; dst.clear(); if (!rf.LabelExist(label)) { return; } rf.ReadChildBegin(label); zuint64 len; IOObj::ReadFileR(rf, RF_SIZE, len); if (len != 0) { dst.reserve(len); } rf.ReadRepeatBegin(RF_DATA); while(rf.ReadRepeatChild()) { T* v = new T; IOObj::ReadFileR(rf, *v); dst.push_back(v); } rf.ReadRepeatEnd(); ZCHECK_EQ(dst.size(), len) << "The length recorded is different from the actual length of data"; rf.ReadChildEnd(); } }; template<typename T> class IOObject<STLVector<T> > { public: static void WriteFileB(FILE *fp, const STLVector<T> &src) { zuint64 len = src.size(); IOObj::WriteFileB(fp, len); if (len != 0) IOObject<T>::WriteFileB(fp, src.data(), len); } static void ReadFileB(FILE *fp, STLVector<T> &dst) { zuint64 len; IOObj::ReadFileB(fp, len); if (len != 0) { dst.resize(len); IOObj::ReadFileB(fp, dst.data(), len); } else { dst.clear(); } } static void WriteFileR(RecordFile &rf, const zint32 label, const STLVector<T> &src) { zuint64 len = src.size(); IOObj::WriteFileR(rf, label, len); if (len != 0) IOObj::WriteFileR(rf, src.data(), len); } static void ReadFileR(RecordFile &rf, const zint32 label, STLVector<T> &dst) { if (!rf.LabelExist(label)) { dst.clear(); return; } zuint64 len; IOObj::ReadFileR(rf, label, len); if (len != 0) { dst.resize(len); IOObj::ReadFileR(rf, dst.data(), len); } else { dst.clear(); } } /// When the object inside STLVector is not SIMPLE_IOOBJECT, it must access 1 by 1, /// instead of access as a raw array. static const int RF_SIZE = 1; static const int RF_DATA = 2; static void WriteFileR1By1(RecordFile &rf, const zint32 label, const STLVector<T> &src) { zuint64 len = src.size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_DATA); for (zuint64 i = 0; i < len; ++i) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, src[i]); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR1By1(RecordFile &rf, const zint32 label, STLVector<T> &dst) { dst.clear(); if (!rf.LabelExist(label)) { return; } rf.ReadChildBegin(label); zuint64 len; IOObj::ReadFileR(rf, RF_SIZE, len); if (len != 0) { dst.reserve(len); } rf.ReadRepeatBegin(RF_DATA); while(rf.ReadRepeatChild()) { T v; IOObj::ReadFileR(rf, v); dst.push_back(v); } rf.ReadRepeatEnd(); ZCHECK_EQ(dst.size(), len) << "The length recorded is different from the actual length of data"; rf.ReadChildEnd(); } }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/STLVector.hpp
C++
gpl3
10,731
#define ZCORE_SOURCE #include "BraceNode.hpp" #include "BraceFile.hpp" #include "Log.hpp" namespace zzz{ BraceNode::BraceNode(const BraceNode &node) :item(node.item),parent(node.parent),idx(node.idx) {} BraceNode::BraceNode(BraceItem *_item,BraceItem *_parent,int i) :item(_item),parent(_parent),idx(i) {} bool BraceNode::IsValid() const { return item!=NULL; } zuint BraceNode::NodeNumber() const { return item->children_.size(); } BraceNode BraceNode::GetNode(zuint n) { ZCHECK_LT(n, NodeNumber())<<"BraceNode::GetNode subsript overflow!"; return BraceNode(item->children_[n],item, n); } bool OptionFind(const string &line, const string &opt) { istringstream iss(line); string part; while(true) { iss>>part; if (iss.fail()) return false; if (part==opt) return true; } return false; } BraceNode BraceNode::AppendNode(const string &str, const char h, const char t) const { item->AddNode(str.c_str(), h, t); return BraceNode(item->children_.back(),item,item->children_.size()-1); } bool BraceNode::HasNode(const string &str) { for (vector<BraceItem*>::iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { const string &t=(*vi)->text_; if (OptionFind(t,str)) return true; } return false; } bool BraceNode::RemoveNode(zuint i) { ZCHECK_LT(i, NodeNumber())<<"BraceNode::RemoveNode subsript overflow!"; item->children_.erase(item->children_.begin()+i); return true; } zzz::BraceNode BraceNode::GetFirstNode(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { return BraceNode(*vi,item,vi-item->children_.begin()); } } else { for (vector<BraceItem*>::iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { const string &t=(*vi)->text_; if (t==str) return BraceNode(*vi,item,vi-item->children_.begin()); } } return BraceNode(NULL,NULL, -1); } zzz::BraceNode BraceNode::GetNextSibling(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { return BraceNode(*vi,parent,vi-parent->children_.begin()); } } else { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { const string &t=(*vi)->text_; if (t==str) return BraceNode(*vi,parent,vi-parent->children_.begin()); } } return BraceNode(NULL,NULL, -1); } void BraceNode::GotoNextSibling(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { item=*vi;idx=vi-parent->children_.begin();return; } } else { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { const string &t=(*vi)->text_; if (t==str) {item=*vi;idx=vi-parent->children_.begin();return;} } } item=NULL;parent=NULL;idx=-1; } zzz::BraceNode BraceNode::GetFirstNodeInclude(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { return BraceNode(*vi,item,vi-item->children_.begin()); } } else { for (vector<BraceItem*>::iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { const string &t=(*vi)->text_; if (OptionFind(t,str)) return BraceNode(*vi,item,vi-item->children_.begin()); } } return BraceNode(NULL,NULL, -1); } zzz::BraceNode BraceNode::GetNextSiblingInclude(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { return BraceNode(*vi,parent,vi-parent->children_.begin()); } } else { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { const string &t=(*vi)->text_; if (OptionFind(t,str)) return BraceNode(*vi,parent,vi-parent->children_.begin()); } } return BraceNode(NULL,NULL, -1); } void BraceNode::GotoNextSiblingInclude(const string &str) { if (str.empty()) { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { item=*vi;idx=vi-parent->children_.begin();return; } } else { for (vector<BraceItem*>::iterator vi=parent->children_.begin()+idx+1;vi!=parent->children_.end();vi++) { const string &t=(*vi)->text_; if (OptionFind(t,str)) {item=*vi;idx=vi-parent->children_.begin();return;} } } item=NULL;parent=NULL;idx=-1; } void BraceNode::operator++() { GotoNextSibling(); } char BraceNode::GetHeadBrace() { return item->head_; } char BraceNode::GetTailBrace() { return item->tail_; } void BraceNode::SetHeadTail(char h, char t) { item->head_=h; item->tail_=t; } const string& BraceNode::GetText() const { return item->text_; } void BraceNode::SetText(const string &str) { item->text_=str; } void BraceNode::GetChildrenText(string &str) const { str.clear(); for (vector<BraceItem*>::const_iterator vi=item->children_.begin();vi!=item->children_.end();vi++) { str+=(*vi)->text_; str+="\n"; } } }
zzz-engine
zzzEngine/zCore/zCore/Utility/BraceNode.cpp
C++
gpl3
5,574
#ifdef WIN32 #include <stdarg.h> inline void va_copy(va_list &a, va_list &b) { a = b; } typedef int uid_t; #endif
zzz-engine
zzzEngine/zCore/zCore/Utility/Port.hpp
C++
gpl3
124
#pragma once #include "../common.hpp" #include "IndexSet.hpp" namespace zzz{ class StringGenerator : public IndexSet<string> { public: StringGenerator(){} StringGenerator(const vector<string> &strs){strings_=strs;} StringGenerator(const StringGenerator &other){strings_=other.strings_;} const StringGenerator& operator=(const StringGenerator &other){strings_=other.strings_;} const StringGenerator& operator=(const vector<string> &strs){strings_=strs;} string Get(const zuint &i){return strings_[i];} zuint Size(){return strings_.size();} void Clear(){strings_.clear();} void PopBack(const string &str){strings_.pop_back();} void PushBack(const string &str){strings_.push_back(str);} private: vector<string> strings_; }; class StringContGenerator : public IndexSet<string> { public: StringContGenerator() :start_(0), end_(0) {} StringContGenerator(const string &pattern, int start, int end) :pattern_(pattern), start_(start), end_(end) {} StringContGenerator(const StringContGenerator &other) :pattern_(other.pattern_), start_(other.start_), end_(other.end_) {} const StringContGenerator& operator=(const StringContGenerator &other) { pattern_=other.pattern_; start_=other.start_; end_=other.end_; } void Set(const string &pattern, int start, int end) { pattern_=pattern; start_=start; end_=end; } string Get(zuint i) { char str[1024]; sprintf(str,pattern_.c_str(), i+start_); return string(str); } zuint Size(){return end_-start_+1;} private: string pattern_; int start_,end_; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/StringGenerator.hpp
C++
gpl3
1,657
#pragma once #include <zCoreConfig.hpp> #include "../common.hpp" #include "Timer.hpp" // Mimic Google progress bar behavior namespace zzz { #define ZVERBOSE_PROGRESS_BAR (ZINFO) class ZCORE_CLASS TextProgressBar { public: typedef enum {STYLE_NORMAL, STYLE_Z} Style; TextProgressBar(const string &msg, bool active_mode = false, Style style = STYLE_Z); void SetActiveMode(bool mode); void SetMaximum(int x); void SetMinimum(int x); void SetValue(int x); void SetDelayStart(double sec); void SetNormalChar(char blank, char fill); void SetZChar(const string &zstyle_char); void SetUpdateRate(double rate); void Start(); void End(bool clear = false); void Update(int value); void DeltaUpdate(int value_delta=1); void Pulse(); private: bool CheckDelayStart(); void Show(bool end); void ShowActive(bool end); void Clear(); string SecondsToTime(double sec); Style style_; bool active_mode_; int console_width_; // for bar string msg_; string bar_; int max_, min_, value_; int bar_length_; // for non-zstyle char blank_, fill_; int running_char_count_; // for zstyle string zstyle_char_; zuint next_update_; vector<int> bar_char_count_; vector<int> update_order_; int actbar_length_; int actbar_pos_; int percentage_; Timer timer_, last_timer_; int last_timer_count_; double update_rate_; double delay_start_; bool started_; }; class ScopeTextProgressBar : public TextProgressBar { public: ScopeTextProgressBar(const string& msg, int minv, int maxv, double delay_start = 0) : TextProgressBar(msg) { SetMinimum(minv); SetMaximum(maxv); SetDelayStart(delay_start); Start(); } ~ScopeTextProgressBar() { End(); } }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/TextProgressBar.hpp
C++
gpl3
1,830
#define ZCORE_SOURCE #include "TextProgress.hpp" namespace zzz { TextProgress::TextProgress(const string &_content, int endvalue, int startvalue) { SetContent(_content); SetValue(endvalue,startvalue); SetAppearance('[', ']', '-', '+',30); } void TextProgress::SetValue(int _endvalue, int _startvalue) { startvalue=_startvalue; endvalue=_endvalue; value=startvalue; } void TextProgress::SetAppearance(char _beginchar, char _endchar, char _blankchar, char _fillchar, int _length) { beginchar=_beginchar; endchar=_endchar; blankchar=_blankchar; fillchar=_fillchar; length=_length; } void TextProgress::SetContent(const string &_content) { content=_content; } void TextProgress::ShowProgressBegin() { value=startvalue; lastlength=0; showContent(); } void TextProgress::ShowProgress(int _value) { clearLastMsg(); value=_value; showContent(); } void TextProgress::ShowProgressAutoIncrease() { clearLastMsg(); value++; showContent(); } void TextProgress::ShowProgressEnd(bool clear) { if (clear) clearLastMsg(); else cout<<endl; } void TextProgress::clearLastMsg() { for (int i=0; i<lastlength; i++) printf("\b"); lastlength=0; } void TextProgress::showBar() { ostringstream oss; oss<<beginchar; int filllen=((double)value-startvalue)/(endvalue-startvalue)*length; for (int i=0; i<filllen; i++) oss<<fillchar; for (int i=filllen; i<length; i++) oss<<blankchar; oss<<endchar; lastlength+=oss.str().size(); cout<<oss.str(); } void TextProgress::showSpin() { static int spinvalue=0; const char symbol[]="-\\|/"; cout<<symbol[spinvalue%4]; lastlength+=1; spinvalue++; } void TextProgress::showPercentage() { char msg[1024]; sprintf(msg, "%.2f%%", ((float)value-startvalue)/(endvalue-startvalue)*100); lastlength+=strlen(msg); cout<<msg; } void TextProgress::showNumber() { char msg[1024]; sprintf(msg, "%d / %d",value,endvalue); lastlength+=strlen(msg); cout<<msg; } void TextProgress::showContent() { for (zuint i=0; i<content.size(); i++) { if (content[i]=='%') { if (i==content.size()-1) break; else if (content[i+1]=='b') showBar(); else if (content[i+1]=='s') showSpin(); else if (content[i+1]=='p') showPercentage(); else if (content[i+1]=='n') showNumber(); else if (content[i+1]=='%') { cout<<'%'; lastlength++; } i++; } else { cout<<content[i]; lastlength++; } } } }
zzz-engine
zzzEngine/zCore/zCore/Utility/TextProgress.cpp
C++
gpl3
2,633
#pragma once #include <zCoreConfig.hpp> #ifdef ZZZ_LIB_PTHREAD #include <pthread.h> namespace zzz{ class ZCORE_CLASS Thread { public: Thread(); void Start(); void Wait(); bool IsRunning(); virtual void Main()=0; pthread_t thread; bool running; }; class ZCORE_CLASS Mutex { public: Mutex(); ~Mutex(); void Lock(); void Unlock(); bool TryLock(); pthread_mutex_t mutex; }; class ZCORE_CLASS Condition { public: Condition(); ~Condition(); virtual bool IsSatisfied()=0; void Check(); void Wait(); pthread_mutex_t mutex; pthread_cond_t cond; }; } #endif // ZZZ_LIB_PTHREAD
zzz-engine
zzzEngine/zCore/zCore/Utility/Thread.hpp
C++
gpl3
658
#define ZCORE_SOURCE #include <EnvDetect.hpp> #include "FileTools.hpp" #include "Log.hpp" #include <sys/stat.h> #ifdef ZZZ_OS_WIN #include <3rdParty/dirent.h> #include <direct.h> #define _GetCurrentDir _getcwd #define _MkDir _mkdir #define SPLITOR "\\" #else #include <dirent.h> #include <unistd.h> #define _GetCurrentDir getcwd #define _MkDir mkdir #define SPLITOR "/" #endif namespace zzz{ // This should be called on program initialization, before main string INITIAL_PATH = CompleteDirName(CurrentPath()); #ifdef ZZZ_LIB_BOOST // Boost Implementation /////////////////////////////////////////////// //path Path RelativeTo(const Path &src, const Path &dest) { ZCHECK(dest.is_complete() && src.is_complete()); Path srcpath=src.has_filename()?src.parent_path():src; Path::iterator dest_begin = dest.begin(), dest_end = dest.end(); Path::iterator src_begin = srcpath.begin(), src_end = srcpath.end(); Path result; #if defined(BOOST_WINDOWS) //#if defined(WIN32) // paths are on different drives (like, "c:/test/t.txt" and "d:/home") if (dest.root_name() != srcpath.root_name()) return dest; if (src_begin != src_end) ++src_begin; if (dest_begin != dest_end) ++dest_begin; #endif // ignore directories that are same while ((src_begin != src_end) && (dest_begin != dest_end)) { if (*src_begin != *dest_begin) break; ++src_begin, ++dest_begin; } // now, we begin to relativize while (src_begin != src_end) { result /= ".."; ++src_begin; } while (dest_begin != dest_end) { result /= *dest_begin; ++dest_begin; } return result; } string GetExt(const string &str) { Path p(str); return p.extension(); } string GetBase(const string &str) { Path p(str); return p.stem(); } string GetFilename(const string &str) { Path p(str); return p.filename(); } string GetPath(const string &str) { Path p(str); string parent_path = p.parent_path().file_string(); if (!parent_path.empty()) parent_path += '\\'; else parent_path = ".\\"; return parent_path; } vector<string> SplitPath(const string &path) { Path p(path); vector<string> splits(p.begin(), p.end()); return splits; } string PathFile(const string &path,const string &file) { Path p(path); Path f(file); p.remove_filename(); if (!f.has_root_path()) p/=f; else p=f; return p.file_string(); } void NormalizePath(string &path) { Path p(path); p.normalize(); path=p.file_string(); } string RelativeTo(const string &a,const string &to_a) { return RelativeTo(Path(a),Path(to_a)).file_string(); } bool FileExists(const string &filename) { Path p(filename); return boost::filesystem2::exists(p) && boost::filesystem2::is_regular_file(p); } bool DirExists(const string &filename) { Path p(filename); return boost::filesystem2::exists(p) && boost::filesystem2::is_directory(p); } bool IsSymlink(const string &filename) { Path p(filename); return boost::filesystem2::exists(p) && boost::filesystem2::is_symlink(p); } void ListFileOnly(const string &path, bool recursive, vector<string> &files) { Path dir_path(path); if (!exists(dir_path)) return; boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { if (boost::filesystem2::is_directory(itr->status())) { if (recursive) ListFileOnly(itr->path().string(), recursive, files); } else { files.push_back(itr->path().string()); } } } void ListDirOnly(const string &path, bool recursive, vector<string> &files) { Path dir_path(path); if (!exists(dir_path)) return; boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { if (boost::filesystem2::is_directory(itr->status())) { files.push_back(CompleteDirName(itr->path().string())); if (recursive) ListDirOnly(itr->path().string(), recursive, files); } } } void ListFileAndDir(const string &path, bool recursive, vector<string> &files) { Path dir_path(path); if (!exists(dir_path)) return; boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { if (boost::filesystem2::is_directory(itr->status()) && recursive) { files.push_back(CompleteDirName(itr->path().string())); ListFileAndDir(itr->path().string(), recursive, files); } else files.push_back(itr->path().string()); } } bool PathEquals(const string &f1, const string &f2) { Path p1(f1),p2(f2); return p1==p2; } string CurrentPath() { return boost::filesystem::current_path().file_string()+"\\"; } bool CopyFile(const string &from, const string &to) { if (!FileCanOpen(from) || FileCanOpen(to)) return false; boost::filesystem::copy_file(Path(from),Path(to)); return true; } bool RenameFile(const string &from, const string &to) { if (!FileCanOpen(from) || FileCanOpen(to)) return false; boost::filesystem::rename(Path(from),Path(to)); return true; } bool RemoveFile(const string &f, bool recursive) { Path p(f); if (!boost::filesystem::exists(p)) return false; if (!recursive && boost::filesystem::is_directory(p) && !boost::filesystem::is_empty(p)) return false; if (recursive) return boost::filesystem::remove_all(p)>0; else return boost::filesystem::remove(p); } bool MakeDir(const string &dir) { return boost::filesystem::create_directories(Path(dir)); } bool MakeHardLink(const string &from, const string &to) { if (!FileCanOpen(from) || FileCanOpen(to)) return false; boost::filesystem::create_hard_link(Path(from),Path(to)); return true; } bool MakeSymLink(const string &from, const string &to) { if (!FileCanOpen(from) || FileCanOpen(to)) return false; boost::filesystem::create_symlink(Path(from),Path(to)); return true; } #else /////////////////////////////////////////////////////////////////////// // Native Implementation string GetExt(const string &str) { string::size_type dot_pos = str.rfind('.'); string::size_type slash_pos = str.rfind('/'); if (slash_pos == string::npos) slash_pos = str.rfind('\\'); if (dot_pos == string::npos) return string("."); if (slash_pos == string::npos) { return str.substr(dot_pos, str.size() - dot_pos); } else if (slash_pos < dot_pos) { return str.substr(dot_pos, str.size() - dot_pos); } else { return string("."); } } string GetBase(const string &str) { string::size_type dot_pos = str.rfind('.'); string::size_type slash_pos = str.rfind('/'); if (slash_pos == string::npos) slash_pos = str.rfind('\\'); if (dot_pos == string::npos) dot_pos = str.size(); if (slash_pos == string::npos) { return str.substr(0, dot_pos); } else if (slash_pos < dot_pos) { return str.substr(slash_pos + 1, dot_pos - slash_pos - 1); } else { return string(); } } string GetFilename(const string &str) { string::size_type slash_pos = str.rfind('/'); if (slash_pos == string::npos) slash_pos = str.rfind('\\'); if (slash_pos == string::npos) { return str; } else { return str.substr(slash_pos + 1, str.size() - slash_pos - 1); } } string GetPath(const string &str) { string::size_type slash_pos = str.rfind('/'); if (slash_pos == string::npos) slash_pos = str.rfind('\\'); if (slash_pos == string::npos) { return CompleteDirName("."); } else { return str.substr(0, slash_pos+1); } } vector<string> SplitPath(const string &path) { vector<string> splits(1); for (string::const_iterator si = path.begin(); si != path.end(); si++) { if (*si == '/' || *si == '\\') { if (splits.size() == 1 && splits[0][1] == ':') splits.push_back("/"); splits.push_back(string()); } else { splits.back().push_back(*si); } } if (splits.back().empty()) splits.back() = "."; return splits; } bool HasRoot(const string &str) { #ifdef ZZZ_OS_WIN if (isalpha(str[0]) && str[1] == ':') return true; #else if (str[0] == '/') return true; #endif return false; } string PathFile(const string &path,const string &file) { if (!HasRoot(file)) return GetPath(path) + file; else return file; } bool FileExists(const string &filename) { struct stat stFileInfo; return stat(filename.c_str(), &stFileInfo) == 0 && (stFileInfo.st_mode & S_IFMT) == S_IFREG; } bool DirExists(const string &filename) { struct stat stFileInfo; return stat(filename.c_str(), &stFileInfo) == 0 && (stFileInfo.st_mode & S_IFMT) == S_IFDIR; } void ListFileOnly(const string &path, bool recursive, vector<string> &files) { DIR *dp; dirent *dirp; if((dp = opendir(path.c_str())) == NULL) { ZLOGE << "Error(" << errno << ") opening " << path << endl; } while ((dirp = readdir(dp)) != NULL) { if (dirp->d_type == DT_DIR) { if (recursive) ListFileOnly(dirp->d_name, recursive, files); } else files.push_back(string(dirp->d_name)); } closedir(dp); } void ListDirOnly(const string &path, bool recursive, vector<string> &files) { DIR *dp; dirent *dirp; if((dp = opendir(path.c_str())) == NULL) { ZLOGE << "Error(" << errno << ") opening " << path << endl; } while ((dirp = readdir(dp)) != NULL) { if (dirp->d_type == DT_DIR) { files.push_back(string(dirp->d_name)); if (recursive) ListFileOnly(dirp->d_name, recursive, files); } } closedir(dp); } void ListFileAndDir(const string &path, bool recursive, vector<string> &files) { DIR *dp; dirent *dirp; if((dp = opendir(path.c_str())) == NULL) { ZLOGE << "Error(" << errno << ") opening " << path << endl; } while ((dirp = readdir(dp)) != NULL) { files.push_back(string(dirp->d_name)); if (dirp->d_type == DT_DIR) { if (recursive) ListFileOnly(dirp->d_name, recursive, files); } } closedir(dp); } string CurrentPath() { char cCurrentPath[FILENAME_MAX]; _GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)); return CompleteDirName(cCurrentPath); } bool CopyFile(const string &from, const string &to) { ifstream f1(from, fstream::binary); ofstream f2(to, fstream::trunc|fstream::binary); f2 << f1.rdbuf(); f1.close(); f2.close(); if (!FileCanOpen(from) || FileCanOpen(to)) return false; return true; } bool RenameFile(const string &from, const string &to) { return rename(from.c_str(), to.c_str()) == 0; } bool RemoveFile(const string &f, bool recursive) { return remove(f.c_str()) == 0; } bool MakeDir(const string &dir) { return _MkDir(dir.c_str()) == 0; } #endif // ZZZ_LIB_BOOST string InitialPath() { return INITIAL_PATH; } std::string CompleteDirName(const string &str) { if (str.back()=='/' || str.back()=='\\') return str; else return str + SPLITOR; } ////////////////////////////////////////// //file bool ReadFileToString(const string &filename,char **buf) { unsigned long len=GetFileSize(filename); FILE *fp=fopen(filename.c_str(), "rb"); if (fp==NULL) { ZLOGE<<"Cannot open file: "<<filename<<endl; return false; } *buf=new char[len+1]; memset(*buf, 0,sizeof(char)*(len+1)); //VERY IMPORTANT, otherwise fread may read out wrong data ZCHECK(fread(*buf,len, 1,fp)==1); fclose(fp); return true; } bool ReadFileToString(const string &filename,string &buf) { char *charbuf; ReadFileToString(filename, &charbuf); buf=charbuf; delete[] charbuf; return true; } bool SaveStringToFile(const string &filename,string &buf) { FILE *fp=fopen(filename.c_str(), "wb"); if (fp==NULL) { printf("Cannot open file: %s\n",filename); return false; } fwrite(buf.c_str(),buf.size(), 1,fp); fclose(fp); return true; } unsigned long GetFileSize(const string &filename) { FILE *pFile = fopen(filename.c_str(), "rb"); if (pFile==NULL) return 0; fseek(pFile, 0, SEEK_END); unsigned long size = ftell(pFile); fclose(pFile); return size; } bool FileCanOpen(const string &filename) { FILE *fp=fopen(filename.c_str(), "rb"); if(fp!=NULL) { fclose(fp); return true; } return false; } string RemoveComments_copy(const string &buf) { string buf2; bool incomment1=false,incomment2=false; int len=buf.size(); for(int i=0; i<len; i++) { char x=buf[i]; if (incomment1) { if (x=='\n') { incomment1=false; buf2.push_back(x); } continue; } if (incomment2) { if (x=='*' && i+1!=len && buf[i+1]=='/') { incomment2=false; i++; continue; } if (x=='\n') buf2.push_back(x); continue; } if (x=='/') { if (i+1!=len && buf[i+1]=='/') { incomment1=true; i++; continue; } if (i+1!=len && buf[i+1]=='*') { incomment2=true; i++; continue; } } if (x=='\\' && buf[i+1]=='\n') { i++; continue; } if (x=='; ') x='\n'; buf2.push_back(x); } return buf2; } bool RemoveComments(string &buf) { string buf2=RemoveComments_copy(buf); buf=buf2; return true; } zzz::zuint FileCountLine(ifstream &fi) { streampos oripos=fi.tellg(); int line=0; string tmp; while(true) { getline(fi,tmp, '\n'); if (fi.fail()) break; line++; } fi.clear(); fi.seekg(oripos); return line; } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/FileTools.cpp
C++
gpl3
14,069
#define ZCORE_SOURCE #include "TextProgressBar.hpp" #include "Log.hpp" #include "StringPrintf.hpp" #include "../Math/Math.hpp" // Mimic Google progress bar behavior namespace zzz { TextProgressBar::TextProgressBar(const string &msg, bool active_mode, Style style) :msg_(msg), active_mode_(active_mode), max_(0), min_(0), value_(0), running_char_count_(0), style_(style), update_rate_(1), started_(false), delay_start_(0) { SetNormalChar('.', 'Z'); SetZChar(".zZ"); console_width_ = 79; } void TextProgressBar::SetActiveMode(bool mode) { active_mode_ = mode; } void TextProgressBar::SetMaximum(int x) { max_ = x; } void TextProgressBar::SetMinimum(int x) { min_ = x; } void TextProgressBar::SetValue(int x) { value_ = x; } void TextProgressBar::SetNormalChar(char blank, char fill) { blank_=blank; fill_=fill; } void TextProgressBar::Start() { if (!CheckDelayStart()) return; ZCHECK_FALSE(started_)<<"The progress bar is already started!"; static int ETA_length = strlen(" ETA 00:00:00"); static int percent_length = strlen(" 100%"); static int PST_length = strlen(" PST 00:00:00"); running_char_count_=0; if (!active_mode_) { int msg_length = msg_.size() + 1; if (console_width_ - ETA_length - msg_length - percent_length < 7) { msg_length = console_width_ - ETA_length - percent_length - 7; msg_.assign(msg_.begin(), msg_.begin()+msg_length-3); msg_+="..."; } bar_length_ = console_width_ - ETA_length - msg_length - percent_length - 2; value_ = min_; last_timer_.Restart(); last_timer_count_=1; percentage_ = 0; if (style_ == STYLE_NORMAL) { // msg %XX [ZZZZZZZZZ/__________] ETA 00:00:00 // msg %100 [ZZZZZZZZZZZZZZZZZZZZ] ALL 01:01:01 bar_.assign(bar_length_, blank_); ZLOG(ZVERBOSE_PROGRESS_BAR)<<StringPrintf("%s %2d%% [%s] ETA %s", msg_.c_str(), 0, bar_.c_str(), SecondsToTime(0).c_str()); } else if (style_ == STYLE_Z) { // msg %XX [z__ZzZ_zzz_____zZ] ETA 00:00:00 // msg %100 [ZZZZZZZZZZZZZZZZZ] ETA 01:23:45 update_order_.reserve(bar_length_*(zstyle_char_.length()-1)); for (zuint j=0; j<zstyle_char_.length()-1; j++) for (int i=0; i<bar_length_; i++) update_order_.push_back(i); random_shuffle(update_order_.begin(), update_order_.end()); next_update_=0; bar_char_count_.assign(bar_length_, 0); bar_.assign(bar_length_, zstyle_char_[0]); ZLOG(ZVERBOSE_PROGRESS_BAR)<<StringPrintf("%s %2d%% [%s] ETA %s", msg_.c_str(), 0, bar_.c_str(), SecondsToTime(0).c_str()); } } else { // msg [_____ZZZZZZZ__________] PST 00:00:00 int msg_length = msg_.size() + 1; if (console_width_ - PST_length - msg_length < 7) { msg_length = console_width_ - PST_length - 7; msg_.assign(msg_.begin(), msg_.begin()+msg_length-3); msg_+="..."; } bar_length_ = console_width_ - PST_length - msg_length - 2; actbar_length_ = Min(bar_length_ / 3, 20); actbar_pos_ = 0; bar_.assign(actbar_length_, fill_); bar_.append(bar_length_ - actbar_length_, blank_); ZLOG(ZVERBOSE_PROGRESS_BAR)<<msg_<<" ["<<bar_<<"] PST "<<SecondsToTime(0); } started_=true; } void TextProgressBar::End(bool clear) { if (!started_) return; timer_.Pause(); if (clear) { Clear(); } else { if (!active_mode_) Show(true); else ShowActive(true); ZLOG(ZVERBOSE_PROGRESS_BAR)<<"\n"; } } void TextProgressBar::Update(int value) { ZCHECK_FALSE(active_mode_)<<"Update() CANNOT be only called in Active Mode"; if (!CheckDelayStart()) return; if (!started_) Start(); value_ = Clamp(min_, value, max_); Show(false); } void TextProgressBar::Pulse() { ZCHECK(active_mode_)<<"Pulse() can be only called in Active Mode"; if (!CheckDelayStart()) return; if (!started_) Start(); ShowActive(false); } void TextProgressBar::Show(bool end) { double per = Clamp<double>(0.0, double(value_ - min_) / (max_ - min_), 1.0); // Only update when 1 sec past or percentage increased by 1 if (!end && int(per) <= percentage_ && last_timer_.Elapsed() < update_rate_) { last_timer_count_++; return; } percentage_ = static_cast<int>(per * 100); running_char_count_++; Clear(); // Prepare bar if (!end && per != 1.0) { // Running char. static char running_char[]="|/-\\"; running_char_count_%=4; // Estimate time after double est = timer_.Elapsed() / value_ * (max_ - value_); if (style_ == STYLE_NORMAL) { int fill_length = per * bar_length_; bar_.assign(fill_length, fill_); if (fill_length < bar_length_) { bar_+=running_char[running_char_count_]; bar_.append(bar_length_ - fill_length - 1, blank_); } ZLOG(ZVERBOSE_PROGRESS_BAR)<<StringPrintf("%s %3d%% [%s] ETA %s", msg_.c_str(), percentage_, bar_.c_str(), SecondsToTime(est).c_str()); } else if (style_ == STYLE_Z) { running_char_count_%=2; int l = per * bar_length_ * (zstyle_char_.length()-1); // Fixed part for (int i=next_update_; i<l; i++) { int update_pos = update_order_[i]; bar_char_count_[update_pos]++; bar_[update_pos]= zstyle_char_[bar_char_count_[update_pos]]; } next_update_ = l; // Running part if (next_update_ < bar_length_ * (zstyle_char_.length()-1)) { int update_pos = update_order_[next_update_]; bar_[update_pos]= zstyle_char_[bar_char_count_[update_pos]+running_char_count_]; } ZLOG(ZVERBOSE_PROGRESS_BAR)<<StringPrintf("%s %3d%% [%s] ETA %s", msg_.c_str(), percentage_, bar_.c_str(), SecondsToTime(est).c_str()); } } else { // All time double all = timer_.Elapsed(); if (style_ == STYLE_NORMAL) bar_.assign(bar_length_, fill_); else if (style_ == STYLE_Z) bar_.assign(bar_length_, zstyle_char_.back()); // Draw. ZLOG(ZVERBOSE_PROGRESS_BAR)<<msg_<<" 100% ["<<bar_<<"] ALL "<<SecondsToTime(all); } last_timer_.Restart(); last_timer_count_ = 1; } void TextProgressBar::ShowActive(bool end) { // Only update when 1 sec past if (!end && last_timer_.Elapsed() < update_rate_) return; else last_timer_.Restart(); Clear(); // Prepare bar if (!end) { actbar_pos_++; actbar_pos_ %= bar_length_; if (bar_length_ - actbar_pos_ > actbar_length_) { bar_.assign(actbar_pos_, blank_); bar_.append(actbar_length_, fill_); bar_.append(bar_length_ - actbar_pos_ - actbar_length_, blank_); } else { bar_.assign(actbar_length_ - (bar_length_ - actbar_pos_), fill_); bar_.append(bar_length_ - actbar_length_, blank_); bar_.append(bar_length_ - actbar_pos_, fill_); } // Draw. ZLOG(ZVERBOSE_PROGRESS_BAR)<<msg_<<" ["<<bar_<<"] PST "<<SecondsToTime(timer_.Elapsed()); } else { // All time double all = timer_.Elapsed(); bar_.assign(bar_length_, fill_); // Draw. ZLOG(ZVERBOSE_PROGRESS_BAR)<<msg_<<" ["<<bar_<<"] ALL "<<SecondsToTime(timer_.Elapsed()); } } void TextProgressBar::Clear() { ZLOG(ZVERBOSE_PROGRESS_BAR)<<'\r'; } string TextProgressBar::SecondsToTime(double sec) { int seconds = static_cast<int>(sec); int s = seconds % 60; seconds = (seconds - s) / 60; int m = seconds % 60; seconds = (seconds - m) / 60; int h = seconds; if (h>99) return StringPrintf("**:**:**", h, m, s); else return StringPrintf("%02d:%02d:%02d", h, m, s); } void TextProgressBar::DeltaUpdate(int x/*=1*/) { if (!CheckDelayStart()) return; if (!started_) Start(); Update(value_+x); } void TextProgressBar::SetZChar(const string &zstyle_char) { zstyle_char_=zstyle_char; } void TextProgressBar::SetUpdateRate(double rate) { update_rate_ = rate; } void TextProgressBar::SetDelayStart(double sec) { delay_start_ = sec; } bool TextProgressBar::CheckDelayStart() { static bool firstrun = true; if (firstrun) { timer_.Restart(); firstrun = false; } if (delay_start_ > 0 && timer_.Elapsed() < delay_start_) return false; return true; } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/TextProgressBar.cpp
C++
gpl3
8,360
#pragma once #include <common.hpp> //it is the base class of a kind of set //it will take a integer and return a value //for example, filename set can return filename //and image set can return an image namespace zzz{ template<typename T, typename IDX=zuint> class IndexSet { public: virtual T Get(const IDX &i)=0; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/IndexSet.hpp
C++
gpl3
338
#pragma once //a generalized tree //every node connect to father, siblings and sons namespace zzz{ template<typename T> struct TreeNode { public: T v; TreeNode<T> *father; vector<TreeNode<T> *> sons; int height; TreeNode(); ~TreeNode(); void AddSon(TreeNode<T> *son); bool DeleteSon(TreeNode<T> *son); bool DeleteSon(int ison); TreeNode<T> *GetFather(); TreeNode<T> *GetNextSon(TreeNode<T> *son=NULL); vector<TreeNode<T> *> GetSons(); vector<TreeNode<T> *> GetSiblings(); vector<TreeNode<T> *> GetSameHeight(); vector<TreeNode<T> *> GetSameHeightSons(int h); void GetSiblingsHelperUp(vector<TreeNode<T> *> &result, int h); void GetSiblingsHelperDown(vector<TreeNode<T> *> &result, int h); }; template<typename T> vector<TreeNode<T> *> zzz::TreeNode<T>::GetSameHeightSons(int h) { vector<TreeNode<T> *> ret; GetSiblingsHelperDown(ret, h); return ret; } template<typename T> void zzz::TreeNode<T>::GetSiblingsHelperDown(vector<TreeNode<T> *> &result, int h) { if (height==h-1) result.insert(result.end(),sons.begin(),sons.end()); else { for (size_t i=0; i<sons.size(); i++) sons[i]->GetSiblingsHelperDown(result, h); } } template<typename T> void zzz::TreeNode<T>::GetSiblingsHelperUp(vector<TreeNode<T> *> &result, int h) { if (father) father->GetSiblingsHelperUp(result, h); vector<TreeNode<T> *> mysiblings=GetSiblings(); for (size_t i=0; i<mysiblings.size(); i++) mysiblings[i]->GetSiblingsHelperDown(result, h); } template<typename T> vector<TreeNode<T> *> zzz::TreeNode<T>::GetSameHeight() { vector<TreeNode<T> *> ret=GetSiblings(); if (father!=NULL) father->GetSiblingsHelperUp(ret,height); return ret; } template<typename T> vector<TreeNode<T> *> zzz::TreeNode<T>::GetSiblings() { vector<TreeNode<T> *> ret; if (father==NULL) return ret; else { ret=father->GetSons(); for (size_t i=0; i<ret.size(); i++) if (ret[i]==this) { ret.erase(ret.begin()+i); break; } return ret; } } template<typename T> vector<TreeNode<T> *> zzz::TreeNode<T>::GetSons() { return sons; } template<typename T> TreeNode<T> * zzz::TreeNode<T>::GetNextSon(TreeNode<T> *son/*=NULL*/) { if (son==NULL) { if (!sons.empty()) return sons[0]; else return NULL; } else { for (size_t i=0; i<sons.size(); i++) if (sons[i]==son) { if (i!=sons.size()-1) return sons[i+1]; else return NULL; } } } template<typename T> TreeNode<T> * zzz::TreeNode<T>::GetFather() { return father; } template<typename T> zzz::TreeNode<T>::~TreeNode() { for (size_t i=0; i<sons.size(); i++) delete sons[i]; sons.clear(); } template<typename T> zzz::TreeNode<T>::TreeNode() :father(NULL),height(-1) {} template<typename T> bool zzz::TreeNode<T>::DeleteSon(int ison) { if (i<=(int)sons.size()-1) { delete sons[i]; return true; } return false; } template<typename T> bool zzz::TreeNode<T>::DeleteSon(TreeNode<T> *son) { for (size_t i=0; i<sons.size(); i++) if (sons[i]==son) { delete sons[i]; return true; } return false; } template<typename T> void zzz::TreeNode<T>::AddSon(TreeNode<T> *son) { sons.push_back(son); son->father=this; son->height=height+1; } template<typename T> class Tree { public: Tree(){head_.height=0;} TreeNode<T> *GetHead(){return &head_;} TreeNode<T> head_; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/Tree.hpp
C++
gpl3
3,562