Skip to content

Instantly share code, notes, and snippets.

@yoggy
Created December 30, 2011 08:46
Show Gist options
  • Save yoggy/1538809 to your computer and use it in GitHub Desktop.
Save yoggy/1538809 to your computer and use it in GitHub Desktop.
glTranslatef()を使う場合と等価なglMultMatrixf()の使い方サンプル
#ifdef WIN32
#include <SDKDDKVer.h>
#include <Windows.h>
#ifdef _DEBUG
#pragma comment(lib, "freeglutD.lib")
#else
#pragma comment(lib, "freeglut.lib")
#endif
#endif
#include <GL/GL.h>
#include <GL/freeglut.h>
void key_cb(unsigned char key, int x, int y)
{
if (key == 27 || key == 'q') {
glutLeaveMainLoop();
}
}
void reshape_cb(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w > h) {
glOrtho(-(float)w/h, (float)w/h, -1.0f, 1.0f, -1.0f, 1.0f);
}
else {
glOrtho(-1.0f, 1.0f, -(float)h/w, (float)h/w, -1.0f, 1.0f);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void timer_cb (int value)
{
glutTimerFunc(30, timer_cb, 0);
glutPostRedisplay();
}
#define SET_IDENTITY_MATRIX(m) { \
m[ 0]=1.0f; m[ 1]=0.0f; m[ 2]=0.0f; m[ 3]=0.0f; \
m[ 4]=0.0f; m[ 5]=1.0f; m[ 6]=0.0f; m[ 7]=0.0f; \
m[ 8]=0.0f; m[ 9]=0.0f; m[10]=1.0f; m[11]=0.0f; \
m[12]=0.0f; m[13]=0.0f; m[14]=0.0f; m[15]=1.0f; \
}
void display_cb (void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
// using glTranslatef()
glPushMatrix();
{
glTranslatef(-0.6f, 0.0f, 0.0f);
glutSolidTeapot(0.4);
}
glPopMatrix();
//
// glTranslatef(x, y, z) = | 1 0 0 0 |
// | 0 1 0 0 |
// | 0 0 1 0 |
// | x y z 1 |
glPushMatrix();
{
GLfloat mat[16];
SET_IDENTITY_MATRIX(mat);
mat[12] = 0.6f; // x->mat[12], y->mat[13], z->mat[14]
glMultMatrixf(mat);
glutSolidTeapot(0.4);
}
glPopMatrix();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
// GLUT settings
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow(argv[0]);
glutKeyboardFunc(key_cb);
glutDisplayFunc(display_cb);
glutReshapeFunc(reshape_cb);
glutTimerFunc(30, timer_cb, 0);
// OpenGL settings
glClearColor(0.0f, 0.0f, 0.3f, 1.0f);
GLfloat light_diffuse[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloat light_position[] = {2.0f, 2.0f, 10.0f, 1.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0 , GL_POSITION , light_position);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glutMainLoop();
return 0;
}
@yoggy
Copy link
Author

yoggy commented Dec 30, 2011

マトリックスを使うと平行移動・回転・スケールを一度に保持できる点がうれしいかも?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment