Translating between cartesian and screen coordinates

前端 未结 5 575
清歌不尽
清歌不尽 2020-12-28 18:42

For my game I need functions to translate between two coordinate systems. Well it\'s mainly math question but what I need is the C++ code to do it and a bit of explanation h

5条回答
  •  情歌与酒
    2020-12-28 19:22

    I've got some boost c++ for you, based on microsoft article: https://msdn.microsoft.com/en-us/library/jj635757(v=vs.85).aspx

    You just need to know two screen points and two points in your coordinate system. Then you can convert point from one system to another.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
     /* Matrix inversion routine.
     Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */
    template
    bool InvertMatrix(const boost::numeric::ublas::matrix& input, boost::numeric::ublas::matrix& inverse)
    {
        typedef boost::numeric::ublas::permutation_matrix pmatrix;
    
        // create a working copy of the input
        boost::numeric::ublas::matrix A(input);
    
        // create a permutation matrix for the LU-factorization
        pmatrix pm(A.size1());
    
        // perform LU-factorization
        int res = lu_factorize(A, pm);
        if (res != 0)
            return false;
    
        // create identity matrix of "inverse"
        inverse.assign(boost::numeric::ublas::identity_matrix (A.size1()));
    
        // backsubstitute to get the inverse
        lu_substitute(A, pm, inverse);
    
        return true;
    }
    
    PointF ConvertCoordinates(PointF pt_in,
        PointF pt1, PointF pt2, PointF pt1_, PointF pt2_)
    {
    
        float matrix1[]={
             pt1.X,           pt1.Y,           1.0f,           0.0f,
            -pt1.Y,           pt1.X,           0.0f,           1.0f,
             pt2.X,           pt2.Y,           1.0f,           0.0f,
            -pt2.Y,           pt2.X,           0.0f,           1.0f
        };
    
        boost::numeric::ublas::matrix M(4, 4);
        CopyMemory(&M.data()[0], matrix1, sizeof(matrix1));
    
        boost::numeric::ublas::matrix M_1(4, 4);
        InvertMatrix(M, M_1);
    
        double vector[] = {
            pt1_.X,
            pt1_.Y,
            pt2_.X,
            pt2_.Y
        };
    
        boost::numeric::ublas::vector u(4);
        boost::numeric::ublas::vector u1(4);
        u(0) = pt1_.X;
        u(1) = pt1_.Y;
        u(2) = pt2_.X;
        u(3) = pt2_.Y;
    
        u1 = boost::numeric::ublas::prod(M_1, u);
    
        PointF pt;
        pt.X = u1(0)*pt_in.X + u1(1)*pt_in.Y + u1(2);
        pt.Y = u1(1)*pt_in.X - u1(0)*pt_in.Y + u1(3);
        return pt;
    }
    

提交回复
热议问题