簡體   English   中英

使用C ++中的OpenGL將坐標從3D透視投影映射到2D正交投影

[英]Mapping coordinates from 3D perspective projection to 2D orthographic projection in OpenGL in C++

我用C ++編寫了一個簡單的openGL程序。 該程序在3D透視投影中繪制球體,並嘗試在2D正交投影中繪制將球體中心連接到當前光標位置的線。 現在為了畫線,我無法弄清楚球體中心的坐標。

這是我的代碼:

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

void passive(int,int);
void reshape(int,int);
void init(void);
void display(void);
void camera(void);

int cursorX,cursorY,width,height;

int main (int argc,char **argv) {
    glutInit (&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA);
    glutInitWindowSize(1364,689);
    glutInitWindowPosition(0,0);
    glutCreateWindow("Sample");
    init();
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutPassiveMotionFunc(passive);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}    

void display() {
    glClearColor (0.0,0.0,0.0,1.0);
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //  Render 3D content
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60,(GLfloat)width/(GLfloat)height,1.0,100.0);    // create 3D perspective projection matrix
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    camera();
    glTranslatef(-6,-2,0);
    glColor3f(1,0,0);
    glutSolidSphere(5,50,50);
    glPopMatrix();

    // Render 2D content
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, width,height, 0);                 // create 2D orthographic projection matrix
    glMatrixMode(GL_MODELVIEW);
    glColor3f(1,1,1);
    glBegin(GL_LINES);
        glVertex2f( centreX,centreY );          // coordinate of center of the sphere in orthographic projection
        glVertex2f( cursorX,cursorY );
    glEnd();

    glutSwapBuffers();
}    

void camera(void) {
    glRotatef(0.0,1.0,0.0,0.0);
    glRotatef(0.0,0.0,1.0,0.0);
    glTranslated(0,0,-20);
}    

void init(void) {
    glEnable (GL_DEPTH_TEST);
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_COLOR_MATERIAL);
}    

void reshape(int w, int h) {
    width=w; height=h;
}    

void passive(int x1,int y1) {
    cursorX=x1; cursorY=y1;
}

我可以找出centreX和centreY的值。 無論如何,我可以得到正確的值來畫線?

您可能有興趣使用像gluProject這樣的東西從您的對象坐標到屏幕上的實際(投影)位置。 獲得對象的屏幕坐標后,可以輕松地從一個點到另一個點繪制一條線。

在這種情況下,您需要投影球體的中心點。 對於更復雜的對象,我發現投影對象邊界框的所有角是有意義的,然后獲取這些角的屏幕空間位置的范圍。

切換到正交投影(2D模式) 之前 ,您應該獲得模型視圖,視口和投影矩陣。

顯然,為了從屏幕位置(例如,您在窗口中單擊的位置)轉到世界位置,您將需要使用其伴隨功能gluUnProject

請注意,從gluProject出來的坐標不一定直接對應於窗口位置; 你可能不得不翻轉“Y”坐標。

看一下這個GDSE討論,了解一些關於如何解決問題的其他想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM