# opengl学习笔记Ⅴ——磨人的轨迹球真可爱

xiaoxiao2021-02-28  5

glMatrixMode(GL_PROJECTION);//设置投影矩阵 glLoadIdentity(); glOrtho(-1500, 1500, -1500, 1500, 1, 10000);这样，我们可以简单地算出球在窗口中的大小。（这里我的窗口大小为250，1500为正交投影规定的视景体的一半） work_size = a*(R/1500.0)*250;//a为缩放比例，初始为1

x -= 250; y -= 250; y = -y;

r_x1 = x; r_y1 = y; r_z1 = sqrt(work_size*work_size - x*x - y*y);

rx = r_y1*r_z2-r_z1*r_y2; ry = r_z1*r_x2 - r_x1*r_z2; rz = r_x1*r_y2 - r_y1*r_x2; mod = sqrt(rx*rx + ry*ry + rz*rz); rx /= mod; ry /= mod; rz /= mod;

l = sqrt((r_x1 - r_x2)*(r_x1 - r_x2) + (r_y1 - r_y2)*(r_y1 - r_y2) + (r_z1 - r_z2)*(r_z1 - r_z2)); theta =-2*asin(l/(2.0*work_size));

m2[0] = rx*rx + (1 - rx*rx)*cos(theta); m2[1] = rx*ry*(1 - cos(theta)) - rz*sin(theta); m2[2]= rx*rz*(1 - cos(theta)) + ry*sin(theta); m2[4] = rx*ry*(1 - cos(theta)) + rz*sin(theta); m2[5] = ry*ry + (1 - ry*ry)*cos(theta); m2[6] = ry*rz*(1 - cos(theta)) - rx*sin(theta); m2[8] = rx*rz*(1 - cos(theta)) - ry*sin(theta); m2[9] = ry*rz*(1 - cos(theta)) + rx*sin(theta); m2[10] = rz*rz + (1 - rz*rz)*cos(theta); m2[15] = 1;

glMultMatrixd(m2); glMultMatrixd(m1);

glMaterialfv(GL_FRONT, GL_EMISSION, ball);

GLfloat theta,la,lb,lc; r_x2 = x; r_y2 = y; la = sqrt(r_x1*r_x1 + r_y1*r_y1); lb = sqrt(r_x2*r_x2 + r_y2*r_y2); lc = sqrt((r_x1 - r_x2)*(r_x1 - r_x2) + (r_y1 - r_y2)*(r_y1 - r_y2)); theta = 180/PI*acos((la*la + lb*lb - lc*lc) / (2 * la*lb)); //if (theta > 0.1) //{ // cout << endl; //} glLoadIdentity(); if (r_x1*r_y2 - r_y1*r_x2>0) glRotated(theta, 0, 0, 1); else glRotated(theta, 0, 0, -1); glGetDoublev(GL_MODELVIEW_MATRIX, m2);