Social Icons

Sabtu, 08 Juni 2013

Cara Membuat Kubus 3D dengn OpenGL

Syntax :
#include <GL/glut.h>

//GLfloat light_diffuse[] = {1.0/*pengaturan cahaya*/, 0.0/*pengaturan warna*/, 0.0, 1.0};          /* warna merah terang. */
GLfloat light_diffuse[] = {1.0, 0.0, 0.0, 1.0};          /* warna merah terang. */

GLfloat light_position[] = {0.0, 1.0, 1.0, 0.0};
       
GLfloat n[6][3] = {                                          /* secara normal kubus ada 6 muka. */
  {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} };


GLint faces[6][4] = {                                        
  {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} };

GLfloat v[8][3];                                             

void drawBox(void)
{
  int i;
  for (i = 0; i < 6; i++) {
    glBegin(GL_QUADS);
    glNormal3fv(&n[i][0]);
    glVertex3fv(&v[faces[i][0]][0]);
    glVertex3fv(&v[faces[i][1]][0]);
    glVertex3fv(&v[faces[i][2]][0]);
    glVertex3fv(&v[faces[i][3]][0]);
    glEnd();
  }
}

void display(void)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  drawBox();
  glutSwapBuffers();
}

void init(void)
{
  /* pengaturan data vertek kubus. */
  v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1;
  v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1;
  v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1;
  v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1;
  v[0][2] = v[3][2] = v[4][2] = v[7][2] = 1;
  v[1][2] = v[2][2] = v[5][2] = v[6][2] = -1;

  /* meng-Enable-kan pencahayaan OpenGL single. */
  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, light_position);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHTING);
  glEnable(GL_DEPTH_TEST);

  /* mengatur penglihatan kubus. */
  glMatrixMode(GL_PROJECTION);
/* sudut pandangan, aspek ratio,  kedekatan Z, jauh Z */
  gluPerspective(40.0,1.0, 1.0, 10.0);
   glMatrixMode(GL_MODELVIEW);
  gluLookAt(0.0, 0.0, 5.0,  0.0, 0.0, 0.0,  0.0, 1.0, 0.);     
  /* mengatur posisi kubus */
  glTranslatef(0.0, 0.0, -1.0);
  glRotatef(60, 1.0, 0.0, 0.0);
  glRotatef(-20, 0.0, 0.0, 1.0);
}

int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutCreateWindow("Kubus 3D-Pengaturan Cahaya");
  glutDisplayFunc(display);
  init();
  glutMainLoop();
  return 0; 
}          


Run :

1 komentar:

  1. Bagus banget mas artikelnya sangat membantu saya yang baru akan mempelajari opengl mau tanya kalo merubah2 sudut pandang kita melihat kotaknya gimana ya? Maksudnya supaya kotaknya bisa digeser2..pakai mouse..... kunjungin balik https://kodeerror.blogspot.com

    BalasHapus

 
 
Blogger Templates