一个计算glRotato后的坐标的示例代码

使用OpenGL显示简单的视频,对于一些纹理需要旋转并水平翻转,找到一个示例代码,做少量修改

// RotateByVector.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <math.h>

using namespace std;
#define CV_PI 3.1415926

//定义返回结构体
struct Point3f
{
    Point3f()
    {
        x = 0.0f;
        y = 0.0f;
        z = 0.0f;
    }

    Point3f(double _x, double _y, double _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }
    double x;
    double y;
    double z;
};

//点绕任意向量旋转,右手系
//输入参数old_x,old_y,old_z为旋转前空间点的坐标
//vx,vy,vz为旋转轴向量
//theta为旋转角度角度制,范围在-180到180
//返回值为旋转后坐标点
Point3f RotateByVector(double old_x, double old_y, double old_z, double vx, double vy, double vz, double theta)
{
    double r = theta * CV_PI / 180;
    double c = cos(r);
    double s = sin(r);
    double new_x = (vx*vx*(1 - c) + c) * old_x + (vx*vy*(1 - c) - vz * s) * old_y + (vx*vz*(1 - c) + vy * s) * old_z;
    double new_y = (vy*vx*(1 - c) + vz * s) * old_x + (vy*vy*(1 - c) + c) * old_y + (vy*vz*(1 - c) - vx * s) * old_z;
    double new_z = (vx*vz*(1 - c) - vy * s) * old_x + (vy*vz*(1 - c) + vx * s) * old_y + (vz*vz*(1 - c) + c) * old_z;
    return Point3f(new_x, new_y, new_z);
}

// 可类比glRotate
Point3f RotateByVector(Point3f in_, double vx, double vy, double vz, double theta)
{
    double r = theta * CV_PI / 180;
    double c = cos(r);
    double s = sin(r);
    double new_x = (vx*vx*(1 - c) + c) * in_.x + (vx*vy*(1 - c) - vz * s) * in_.y + (vx*vz*(1 - c) + vy * s) * in_.z;
    double new_y = (vy*vx*(1 - c) + vz * s) * in_.x + (vy*vy*(1 - c) + c) * in_.y + (vy*vz*(1 - c) - vx * s) * in_.z;
    double new_z = (vx*vz*(1 - c) - vy * s) * in_.x + (vy*vz*(1 - c) + vx * s) * in_.y + (vz*vz*(1 - c) + c) * in_.z;
    return Point3f(new_x, new_y, new_z);
}

int main()
{
    // 原始
    Point3f A[] = {
        Point3f(1.0f,  1.0f, 0.0f),
        Point3f(1.0f,  -1.0f, 0.0f),
        Point3f(-1.0f, -1.0f, 0.0f),
        Point3f(-1.0f,  1.0f, 0.0f)
    };
    Point3f B[sizeof(A)/sizeof(Point3f)];
    Point3f C[sizeof(A)/sizeof(Point3f)];

    memset(&B, 0, sizeof(B));
    memset(&C, 0, sizeof(B));

    for(unsigned int idx = 0; idx < sizeof(A)/sizeof(Point3f); idx ++){
        // 围绕Z轴,旋转90度
        B[idx] = RotateByVector(A[idx], 0, 0, -1, 90);
        printf("idx: %d, x: %.05f, y: %.05f, z: %.05f\n", idx, B[idx].x, B[idx].y, B[idx].z);
    }
    printf("\n\n");
    for(unsigned int idx = 0; idx < sizeof(A)/sizeof(Point3f); idx ++){
        // 再水平翻转
        C[idx] = RotateByVector(B[idx], 0, 1, 0, 180);
        printf("idx: %d, x: %.05f, y: %.05f, z: %.05f\n", idx, C[idx].x, C[idx].y, C[idx].z);
    }

    system("pause");
    return 0;
}

 

posted @ 2022-01-04 16:39  日月王  阅读(37)  评论(0编辑  收藏  举报