这是一个简单的程序,它在鼠标光标的位置之后绘制一个三角形。
我(希望你)能注意到的是,三角形滞后于光标,它不像拖动整个窗口时那样紧。
所以我的问题是:我做错了什么?是什么导致了这种滞后?
我意识到的一件事是移动三角形的实际像素值就足够了,而不是一次又一次地光栅化它。但是光栅化这个三角形真的那么昂贵吗?我也尝试使用glTranslate
而不是在不同的坐标处绘图,但没有改善滞后。所以我希望你能启发我如何有效地绘制这个。
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
float x = 0.0f;
float y = 0.0f;
static void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
static void cursor_callback(GLFWwindow *window, double xpos, double ypos)
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float ratio = width / (float) height;
x = ratio*(2*xpos/(float)width - 1);
y = 2*-ypos/(float)height + 1;
}
int main(void)
{
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Following Triangle", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
// Callbacks
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_callback);
// geometry for the equal sided triangle
float r = 0.1f; // outer circle radius
float u = r * sin(M_PI_2/3.0f);
float l = 2.0f * r * cos(M_PI_2/3.0f);
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.0f, 1.0f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBegin(GL_TRIANGLES);
glColor3f(1.f, 0.f, 0.f);
glVertex3f(x+0, y+r, 0.f);
glColor3f(0.f, 1.f, 0.f);
glVertex3f(x-l/2.0f, y-u, 0.f);
glColor3f(0.f, 0.f, 1.f);
glVertex3f(x+l/2.0f, y-u, 0.f);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}