This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
void mydisplay() //diregistrasi oleh glutDisplayFunc() sebagai fungsi yang dilaksanakan saat // window digambar { glClear(GL_COLOR_BUFFER_BIT); // Menghapus layar glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); // koordinat titik kiri bawah glVertex2f(-0.5, 0.5); // koordinat titik kiri atas glVertex2f(0.5, 0.5); // koordinat titik kanan atas glVertex2f(0.5, -0.5); // koordinat titik kanan bawah glEnd(); glFlush(); } int main(int argc, char** argv) { printf("Hello World… this is 2D Rectangle"); glutCreateWindow("Simple Window"); glutDisplayFunc(mydisplay); glutMainLoop(); }
//mode display menggunakan tipe GLUT_DOUBLE } void init( void ) { glClearColor( 1.0, 0.0, 0.0, 1.0 ); // A Background Clear Color glMatrixMode(GL_PROJECTION);
glLoadIdentity(); gluPerspective(45, (GLdouble)500.0/(GLdouble)500.0, 0, 100); glMatrixMode(GL_MODELVIEW); } void resize( int w, int h ) { glViewport( 0, 0, (GLsizei) w, (GLsizei) h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(45, (GLdouble)w/(GLdouble)h, 0, 100); glMatrixMode( GL_MODELVIEW ); } void myTimeOut(int id) { // called if timer event // ...advance the state of animation incrementally... rot+=5; //speed rotation glutPostRedisplay(); // request redisplay glutTimerFunc(100, myTimeOut, 0); // request next timer event } void myKeyboard(unsigned char key,int x, int y) { // key untuk translasi objek Zoom in(memperbesar) if((key=='<')||(key==',')) z_pos-=0.1f; // key untuk translasi objek Zoom out (memperkecil) if((key=='>')||(key=='.')) z_pos+=0.1f; } int main(int argc, char** argv) { glutInit(&argc,argv); //glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("Persfektif"); // callbacks glutDisplayFunc(mydisplay); glutKeyboardFunc(myKeyboard); glutTimerFunc(100, myTimeOut, 0); glutReshapeFunc(resize); init(); glutMainLoop(); }
Program 8. Urutan Transformasi
// OpenGL // - Complex Object // - Notice: // 1. There are surfaces that are not correctly rendered in order. // uncommented the GL_DEPTH // 2. Flicker can be eliminated by using GL_DOUBLE
// // Rubah rendering algoritma dengan menggunakan data struktur // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <GL/glut.h> float z_pos=-10.0f; float rot=0.0f; void resize(int width, int height) { glViewport(0,0, width, height); glMatrixMode (GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (float)width / (float)height, 1.0, 300.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void myTimeOut (int id) { rot+=10; glutPostRedisplay();// request redisplay glutTimerFunc(100, myTimeOut, 0); // request next timer event } void myKeyboard(unsigned char key, int x, int y) { if((key=='<')||(key==',')) z_pos-=0.1f; if((key=='>')||(key=='.')) z_pos+=0.1f; } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); //fungsi transformasi glTranslatef (0.0, 0.0f, z_pos); // Objek melakukan translasi glRotatef(rot, 0, 1, 0); // Objek melakukan rotasi glBegin(GL_QUADS); // Front Face, red glColor3f(1.0,0.0,0.0); glVertex3f(-1.0f, -1.0f, 1.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face, green glColor3f(0.0,1.0,0.0); glVertex3f( 1.0f, -1.0f, -1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Top Face, blue glColor3f(0.0,0.0,1.0); glVertex3f(-1.0f, 1.0f, -1.0f);
// file bmp.cpp #include <windows.h> #include <stdio.h> // Header File For Standard Input/Output #include <GL\GL.H> // Header File For The OpenGL32 Library #include <GL\GLU.H> // Header File For The GLu32 Library #include <GL\GLAUX.H> // Header File For The Glaux Library #include "bmp.h" AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image { FILE *File=NULL; //File Handle if (!Filename)// Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); //Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle //return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer return auxDIBImageLoadA(Filename); // load The Bitmap and Return A pointer for Multicode type character } return NULL; // If Load Failed Return NULL }
Program 10. Ubah warna blending pada tiap surface box
// Source code diambil dari Program 9 , diubah di fungsi mydisplay void mydisplay(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glLoadIdentity(); glTranslatef(0.0,0.0f,z_pos); glRotatef(rot, 0, 1, 0); glEnable (GL_BLEND); // blending texture on glColor3f (1.0, 0.0, 0.0); // blending color glBindTexture(GL_TEXTURE_2D, texture[filter]); glBegin(GL_QUADS); // Front Face glColor3f (1.0, 1.0, 0.0); // setting warna untuk sisi depan
glNormal3f( 0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glColor3f (1.0, 0.0, 0.0); // setting warna untuk sisi belakang glNormal3f( 0.0f, 0.0f,-1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Face glColor3f (0.0, 1.0, 1.0); // setting warna untuk sisi atas
glNormal3f( 0.0f, 1.0f, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Bottom Face glColor3f (0.0, 0.0, 1.0); // setting warna untuk sisi bawah glNormal3f( 0.0f,-1.0f, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face glColor3f (1.0, 0.0, 1.0); // setting warna untuk sisi kanan glNormal3f( 1.0f, 0.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Left Face glColor3f (1.0, 1.0, 0.0); // setting warna untuk sisi kiri glNormal3f(-1.0f, 0.0f, 0.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); glFlush(); glutSwapBuffers(); }
Program 11. Transparency
// Source code program 11 diambil dari Program 10, di ubah di fungsi mydisplay dan init
// FOG glClearColor(0.5f,0.5f,0.5f,1.0f); // We'll Clear To The Color Of The Fog glFogi(GL_FOG_MODE, fogMode[GL_EXP2]); // Fog Mode , diinisiasi dg 3 nilai glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color glFogf(GL_FOG_DENSITY, 0.20f); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_NICEST); // Fog Hint Value glFogf(GL_FOG_START, 100.0f); // Fog Start Depth glFogf(GL_FOG_END, 500.0f); // Fog End Depth glEnable(GL_FOG); glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); //Enables Depth Testing glDepthFunc(GL_LEQUAL); //The Type Of Depth Testing To Do glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); return; } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("Fog Window"); // callbacks glutDisplayFunc(mydisplay); glutKeyboardFunc(myKeyboard); glutTimerFunc(100, myTimeOut, 0); glutReshapeFunc(resize); init(); glutMainLoop(); return 0; } Program 13. Objek Komplek
#include<GL/GLAUX.H> # pragma comment ( lib, "GLAUX.LIB") const float piover180 = 0.0174532925f; float heading; float xpos; float zpos; GLfloat yrot; // Y Rotation GLfloat walkbias = 0; GLfloat walkbiasangle = 0; GLfloat lookupdown = 0.0f; GLfloat z=0.0f; // Depth Into The Screen GLuint filter; // Which Filter To Use GLuint texture[3]; // Storage For 3 Textures typedef struct tagVERTEX { float x, y, z; float u, v; } VERTEX; typedef struct tagTRIANGLE { VERTEX vertex[3]; } TRIANGLE; typedef struct tagSECTOR { int numtriangles; TRIANGLE* triangle; } SECTOR; SECTOR sector1; // Our Model Goes Here: void readstr(FILE *f,char *string) { do { fgets(string, 255, f); } while ((string[0] == '/') || (string[0] == '\n')); return; } void SetupWorld() { float x, y, z, u, v; int numtriangles; FILE *filein; char oneline[255]; filein = fopen("test_world.txt", "rt"); // File To Load World Data From readstr(filein,oneline); sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles); sector1.triangle = new TRIANGLE[numtriangles]; sector1.numtriangles = numtriangles; for (int loop = 0; loop < numtriangles; loop++) {
for (int vert = 0; vert < 3; vert++) { readstr(filein,oneline); sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v); sector1.triangle[loop].vertex[vert].x = x; sector1.triangle[loop].vertex[vert].y = y; sector1.triangle[loop].vertex[vert].z = z; sector1.triangle[loop].vertex[vert].u = u; sector1.triangle[loop].vertex[vert].v = v; } } fclose(filein); return; } AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image { FILE *File=NULL; // File Handle if (!Filename) // Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); // Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle //return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer return auxDIBImageLoadA(Filename); // Load The Bitmap And Return A Pointer } return NULL; // If Load Failed Return NULL } int LoadGLTextures() // Load Bitmaps And Convert To Textures { int Status=FALSE; // Status Indicator AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL // Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit if (TextureImage[0]=LoadBMP("aila.bmp")) { Status=TRUE; // Set The Status To TRUE glGenTextures(3, &texture[0]); // Create ThreeTextures // Create Nearest Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX,TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); // Create Linear Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX,TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); // Create MipMapped Texture glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX,TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); // Free The Texture Image Memory } free(TextureImage[0]); // Free The Image Structure } return Status; // Return The Status } void resize(int width, int height) // Resize And Initialize The GL Window { if (height==0) // Prevent A Divide By Zero By { height=1; // Making Height Equal One } glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } void init() // All Setup For OpenGL Goes Here { if (!LoadGLTextures()) // Jump To Texture Loading Routine { return; // If Texture Didn't Load Return FALSE } glEnable(GL_TEXTURE_2D); //Enable Texture Mapping glBlendFunc(GL_SRC_ALPHA,GL_ONE); // SetThe Blending Function For Translucency glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This Will Clear The Background Color To Black glClearDepth(1.0);// Enables Clearing Of The Depth Buffer glDepthFunc(GL_LESS); // The Type Of Depth Test To Do glEnable(GL_DEPTH_TEST); //Enables Depth Testing glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
// Tutorial14h /********************************************************** * * TYPES DECLARATION * *********************************************************/ #define MAX_VERTICES 8000 // Max number of vertices (for each object) #define MAX_POLYGONS 8000 // Max number of polygons (for each object) // Our vertex type typedef struct{ float x,y,z; }vertex_type; // The polygon (triangle), 3 numbers that aim 3 vertices typedef struct{ int a,b,c; }polygon_type; // The mapcoord type, 2 texture coordinates for each vertex typedef struct{ float u,v; }mapcoord_type; // The object type typedef struct { char name[20]; int vertices_qty;
int polygons_qty; vertex_type vertex[MAX_VERTICES]; polygon_type polygon[MAX_POLYGONS]; mapcoord_type mapcoord[MAX_VERTICES]; int id_texture; } obj_type, *obj_type_ptr;
// Texture.h extern int num_texture; extern int LoadBitmap(char *filename); // Texture.cpp #include <stdio.h> #include <windows.h> #include <GL/glut.h> #include "texture.h" /********************************************************** * * VARIABLES DECLARATION * *********************************************************/ int num_texture=-1; //Counter to keep track of the last loaded texture /********************************************************** * * FUNCTION LoadBitmap(char *) * * This function loads a bitmap file and return the OpenGL reference ID to use that texture * *********************************************************/ int LoadBitmap(char *filename) { int i, j=0; //Index variables FILE *l_file; //File pointer unsigned char *l_texture; //The pointer to the memory zone in which we will load the texture // windows.h gives us these types to work with the Bitmap files BITMAPFILEHEADER fileheader; BITMAPINFOHEADER infoheader; RGBTRIPLE rgb; num_texture++; // The counter of the current texture is increased if( (l_file = fopen(filename, "rb"))==NULL) return (-1); // Open the file for reading fread(&fileheader, sizeof(fileheader), 1, l_file); // Read the fileheader fseek(l_file, sizeof(fileheader), SEEK_SET); // Jump the fileheader fread(&infoheader, sizeof(infoheader), 1, l_file); // and read the infoheader // Now we need to allocate the memory for our image (width * height * color deep) l_texture = (byte *) malloc(infoheader.biWidth * infoheader.biHeight* 4); // And fill it with zeros memset(l_texture, 0, infoheader.biWidth * infoheader.biHeight * 4);
// At this point we can read every pixel of the image for (i=0; i < infoheader.biWidth*infoheader.biHeight; i++) { // We load an RGB value from the file fread(&rgb, sizeof(rgb), 1, l_file); // And store it l_texture[j+0] = rgb.rgbtRed; // Red component l_texture[j+1] = rgb.rgbtGreen; // Green component l_texture[j+2] = rgb.rgbtBlue; // Blue component l_texture[j+3] = 255; // Alpha value j += 4; // Go to the next position } fclose(l_file); // Closes the file stream glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter // The next commands sets the texture parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // If the u,v coordinates overflow the range 0,1 the image is repeated glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //The minifying function glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // We don't combine the color with the original surface color, use only the texture map. // Finally we define the 2d texture glTexImage2D(GL_TEXTURE_2D, 0, 4, infoheader.biWidth,infoheader.biHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, l_texture); // And create 2d mipmaps for the minifying function gluBuild2DMipmaps(GL_TEXTURE_2D, 4, infoheader.biWidth, infoheader.biHeight, GL_RGBA, GL_UNSIGNED_BYTE, l_texture); free(l_texture); // Free the memory we used to load the texture return (num_texture); // Returns the current texture OpenGL ID }
// 3dsloader.h /********************************************************** * * FUNCTION Load3DS (obj_type_ptr, char *) * * This function loads a mesh from a 3ds file. * Please note that we are loading only the vertices, polygons and mapping lists. * If you need to load meshes with advanced features as for example: * multi objects, materials, lights and so on, you must insert other chunk parsers. * *********************************************************/ extern char Load3DS (obj_type_ptr ogg, char *filename);
// 3dsloader.cpp #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <io.h> #include "Tutorial14.h" #include "3dsloader.h" /********************************************************** * * FUNCTION Load3DS (obj_type_ptr, char *) * * This function loads a mesh from a 3ds file. * Please note that we are loading only the vertices, polygons and mapping lists. * If you need to load meshes with advanced features as for example: * multi objects, materials, lights and so on, you must insert other chunk parsers. * *********************************************************/ char Load3DS (obj_type_ptr p_object, char *p_filename) { int i; //Index variable FILE *l_file; //File pointer unsigned short l_chunk_id; //Chunk identifier unsigned int l_chunk_lenght; //Chunk lenght unsigned char l_char; //Char variable unsigned short l_qty; //Number of elements in each chunk unsigned short l_face_flags; //Flag that stores some face information if ((l_file=fopen (p_filename, "rb"))== NULL) return 0; //Open the file while (ftell (l_file) < filelength (fileno (l_file))) //Loop to scan the whole file { getche(); //Insert this command for debug (to wait for keypress for each chuck reading) fread (&l_chunk_id, 2, 1, l_file); //Read the chunk header printf("ChunkID: %x\n",l_chunk_id); fread (&l_chunk_lenght, 4, 1, l_file); //Read the lenght of the chunk printf("ChunkLenght: %x\n",l_chunk_lenght); switch (l_chunk_id) { //----------------- MAIN3DS ----------------- // Description: Main chunk, contains all the other chunks // Chunk ID: 4d4d // Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x4d4d: break; //----------------- EDIT3DS ----------------- // Description: 3D Editor chunk, objects layout info // Chunk ID: 3d3d (hex)
// Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x3d3d: break; //--------------- EDIT_OBJECT --------------- // Description: Object block, info for each object // Chunk ID: 4000 (hex) // Chunk Lenght: len(object name) + sub chunks //------------------------------------------- case 0x4000: i=0; do { fread (&l_char, 1, 1, l_file); p_object->name[i]=l_char; i++; } while(l_char != '\0' && i<20); break; //--------------- OBJ_TRIMESH --------------- // Description: Triangular mesh, contains chunks for 3d mesh info // Chunk ID: 4100 (hex) // Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x4100: break; //--------------- TRI_VERTEXL --------------- // Description: Vertices list // Chunk ID: 4110 (hex) // Chunk Lenght: 1 x unsigned short (number of vertices) // + 3 x float (vertex coordinates) x(number of vertices) // + sub chunks //------------------------------------------- case 0x4110: fread (&l_qty, sizeof (unsigned short), 1, l_file); p_object->vertices_qty = l_qty; printf("Number of vertices: %d\n",l_qty); for (i=0; i<l_qty; i++) { fread (&p_object->vertex[i].x, sizeof(float), 1, l_file); printf("Vertices list x: %f\n",p_object->vertex[i].x); fread (&p_object->vertex[i].y, sizeof(float), 1,l_file); printf("Vertices list y: %f\n",p_object->vertex[i].y); fread (&p_object->vertex[i].z, sizeof(float), 1, l_file); printf("Vertices list z: %f\n",p_object->vertex[i].z); } break; //--------------- TRI_FACEL1 ---------------- // Description: Polygons (faces) list // Chunk ID: 4120 (hex) // Chunk Lenght: 1 x unsigned short (number of polygons)
// + 3 x unsigned short (polygon points) x (number of polygons) // + sub chunks //------------------------------------------- case 0x4120: fread (&l_qty, sizeof (unsigned short), 1,l_file); p_object->polygons_qty = l_qty; printf("Number of polygons: %d\n",l_qty); for (i=0; i<l_qty; i++) { fread (&p_object->polygon[i].a, sizeof(unsigned short), 1, l_file); printf("Polygon point a: %d\n",p_object->polygon[i].a); fread (&p_object->polygon[i].b, sizeof(unsigned short), 1, l_file); printf("Polygon point b: %d\n",p_object->polygon[i].b); fread (&p_object->polygon[i].c, sizeof(unsigned short), 1, l_file); printf("Polygon point c: %d\n",p_object->polygon[i].c); fread (&l_face_flags, sizeof (unsigned short), 1, l_file); printf("Face flags: %x\n",l_face_flags); } break; //------------- TRI_MAPPINGCOORS ------------ // Description: Vertices list // Chunk ID: 4140 (hex) // Chunk Lenght: 1 x unsigned short (number of mapping points) // + 2 x float (mapping coordinates) x(number of mapping points) // + sub chunks //------------------------------------------- case 0x4140: fread (&l_qty, sizeof (unsigned short), 1,l_file); for (i=0; i<l_qty; i++) { fread (&p_object->mapcoord[i].u, sizeof(float), 1, l_file); printf("Mapping list u: %f\n",p_object->mapcoord[i].u); fread (&p_object->mapcoord[i].v, sizeof (float), 1,l_file); printf("Mapping list v: %f\n",p_object->mapcoord[i].v); } break; //----------- Skip unknow chunks ------------ //We need to skip all the chunks that currently we don't use //We use the chunk lenght information to set the file pointer //to the same level next chunk //------------------------------------------- default: fseek(l_file, l_chunk_lenght-6, SEEK_CUR); } } fclose (l_file); // Closes the file stream return (1); // Returns ok }
// Main.h #define MAX_VERTICES 8000 // Max number of vertices (for each object) #define MAX_POLYGONS 8000 // Max number of polygons (for each object) // Our vertex type typedef struct{ float x,y,z; }vertex_type; // The polygon (triangle), 3 numbers that aim 3 vertices typedef struct{ int a,b,c; }polygon_type; // The mapcoord type, 2 texture coordinates for each vertex typedef struct{ float u,v; }mapcoord_type; // The object type typedef struct { char name[20]; int vertices_qty; int polygons_qty; vertex_type vertex[MAX_VERTICES]; polygon_type polygon[MAX_POLYGONS]; mapcoord_type mapcoord[MAX_VERTICES]; int id_texture; } obj_type, *obj_type_ptr;
// Main.cpp #include <windows.h> #include <GL/glut.h> #include "Tutorial14.h" #include "Texture.h" #include "3dsloader.h" // The width and height of your window, change them as you like int screen_width=640; int screen_height=480; // Absolute rotation values (0-359 degrees) and rotation increments foreach frame double rotation_x=0, rotation_x_increment=0.1; double rotation_y=0, rotation_y_increment=0.05; double rotation_z=0, rotation_z_increment=0.03; // Flag for rendering as lines or filled polygons int filling=1; //0=OFF 1=ON //Now the object is generic, the cube has annoyed us a little bit, or not? obj_type object; void init(void) { glClearColor(0.0, 0.0, 0.0, 0.0); // This clear the background color to black glShadeModel(GL_SMOOTH); // Type of shading for the polygons
// Viewport transformation glViewport(0,0,screen_width,screen_height); // Projection transformation glMatrixMode(GL_PROJECTION); // Specifies which matrix stack is the target for matrix operations glLoadIdentity(); // We initialize the projection matrix as identity gluPerspective(45.0f,(GLfloat)screen_width/(GLfloat)screen_height,10.0f,10000.0f); // We define the "viewing volume" glEnable(GL_DEPTH_TEST); // We enable the depth test (also called z buffer) glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); // Polygon rasterization mode (polygon filled) glEnable(GL_TEXTURE_2D); // This Enable the Texture mapping Load3DS (&object,"spaceship.3ds"); object.id_texture=LoadBitmap("spaceshiptexture.bmp"); // The Function LoadBitmap() return the current texture ID // If the last function returns -1 it means the file was not found so we exit from the program if (object.id_texture==-1) { MessageBox(NULL,"Image file: spaceshiptexture.bmp not found", "Zetadeck",MB_OK | MB_ICONERROR); exit (0); } } void resize (int width, int height) { screen_width=width; // We obtain the new screen width values and store it screen_height=height; // Height value glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // We clear both the color and the depth buffer so to draw the next frame glViewport(0,0,screen_width,screen_height); // Viewport transformation glMatrixMode(GL_PROJECTION); // Projection transformation glLoadIdentity(); // We initialize the projection matrix as identity gluPerspective(45.0f,(GLfloat)screen_width/(GLfloat)screen_height,10.0f,10000.0f); glutPostRedisplay (); // This command redraw the scene (it calls the same routine of glutDisplayFunc) } void keyboard (unsigned char key, int x, int y) { switch (key) { case' ': rotation_x_increment=0; rotation_y_increment=0; rotation_z_increment=0; break; case'r': case'R': if (filling==0) { glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); // Polygon rasterization mode (polygon filled) filling=1; } else { glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); // Polygon rasterization mode (polygon outlined) filling=0;
} break; } } void keyboard_s (int key, int x, int y) { switch (key) { case GLUT_KEY_UP: rotation_x_increment = rotation_x_increment +0.005; break; case GLUT_KEY_DOWN: rotation_x_increment = rotation_x_increment -0.005; break; case GLUT_KEY_LEFT: rotation_y_increment = rotation_y_increment +0.005; break; case GLUT_KEY_RIGHT: rotation_y_increment = rotation_y_increment -0.005; break; } } void display(void) { int l_index; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); // Modeling transformation glLoadIdentity(); // Initialize the model matrix as identity glTranslatef(0.0,0.0,-300); // We move the object forward (the model matrix is multiplied by the translation matrix) rotation_x = rotation_x + rotation_x_increment; rotation_y = rotation_y + rotation_y_increment; rotation_z = rotation_z + rotation_z_increment; if (rotation_x > 359) rotation_x = 0; if (rotation_y > 359) rotation_y = 0; if (rotation_z > 359) rotation_z = 0; glRotatef(rotation_x,1.0,0.0,0.0); // Rotations of the object (the model matrix is multiplied by the rotation matrices) glRotatef(rotation_y,0.0,1.0,0.0); glRotatef(rotation_z,0.0,0.0,1.0); glBindTexture(GL_TEXTURE_2D, object.id_texture); // We set the active texture glBegin(GL_TRIANGLES); // glBegin and glEnd delimit the vertices that define a primitive (in our case triangles) for (l_index=0;l_index<object.polygons_qty;l_index++) { //----------------- FIRST VERTEX ----------------- // Texture coordinates of the first vertex glTexCoord2f( object.mapcoord[ object.polygon[l_index].a ].u,object.mapcoord[ object.polygon[l_index].a ].v); // Coordinates of the first vertex glVertex3f( object.vertex[ object.polygon[l_index].a ].x,object.vertex[ object.polygon[l_index].a ].y,object.vertex[ object.polygon[l_index].a ].z); //Vertex definition //----------------- SECOND VERTEX ----------------- // Texture coordinates of the second vertex glTexCoord2f( object.mapcoord[ object.polygon[l_index].b ].u,object.mapcoord[
object.polygon[l_index].b ].v); // Coordinates of the second vertex glVertex3f( object.vertex[ object.polygon[l_index].b ].x,object.vertex[ object.polygon[l_index].b ].y,object.vertex[ object.polygon[l_index].b ].z); //----------------- THIRD VERTEX ----------------- // Texture coordinates of the third vertex glTexCoord2f( object.mapcoord[ object.polygon[l_index].c ].u,object.mapcoord[ object.polygon[l_index].c ].v); // Coordinates of the Third vertex glVertex3f( object.vertex[ object.polygon[l_index].c ].x,object.vertex[ object.polygon[l_index].c ].y,object.vertex[ object.polygon[l_index].c ].z); } glEnd(); glFlush(); // This force the execution of OpenGL commands glutSwapBuffers(); // In double buffered mode we invert the positions of the visible buffer and the writing buffer } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(screen_width,screen_height); glutInitWindowPosition(0,0); glutCreateWindow("Animasi Pesawat Objek 3ds"); glutDisplayFunc(display); glutIdleFunc(display); glutReshapeFunc (resize); glutKeyboardFunc (keyboard); glutSpecialFunc (keyboard_s); init(); glutMainLoop(); return(0); }
Program 16. Particle
// Particle.h #ifndef PARTICLE_H_ typedef struct { float lifetime; // total lifetime of the particle float decay; // decay speed of the particle float r,g,b; // color values of the particle float xpos,ypos,zpos; // position of the particle float xspeed,yspeed,zspeed; // speed of the particle boolean active; // is particle active or not? } PARTICLE; void CreateParticle(int i); void InitParticle(); void EvolveParticle();
void world_menu(int value) { switch (value) { case 1: new_material(Brass); break; case 2: new_material(Bronze); break; case 3: new_material(Polished_Bronze); break; case 4: new_material(Chrome); break; case 5: new_material(Copper); break; case 6: new_material(Polished_Copper); break; case 7: new_material(Gold); break; case 8: new_material(Polished_Gold); break; case 9: new_material(Pewter); break; case 10: new_material(Silver); break; case 11: new_material(Polished_Silver); break; case 12: new_material(Emerald); break; case 13: new_material(Jade); break; case 14: new_material(Obsidian); break; case 15: new_material(Pearl); break; case 16: new_material(Ruby); break; case 17: new_material(Turquoise); break; case 18: new_material(Black_Plastic); break; case 19:
//Program 19 Vertex Animation #include<windows.h> #include<math.h>// Math Library Header File #include<stdio.h> #include<stdlib.h> #include<string.h> #include<stdarg.h> #include<GL/glut.h> #include<GL/GLAUX.H> float points[45][45][3]; // The Array For The Points On The Grid Of Our "Wave" int wiggle_count = 0; // Counter Used To Control How Fast Flag Waves GLfloat xrot; // X Rotation ( NEW ) GLfloat yrot; // Y Rotation ( NEW ) GLfloat zrot; // Z Rotation ( NEW ) GLfloat hold; // Temporarily Holds A Floating Point Value GLuint texture[1]; // Storage For One Texture ( NEW ) AUX_RGBImageRec *LoadBMP( char *Filename) // Loads A Bitmap Image { FILE *File=NULL; // File Handle if (!Filename) // Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); // Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle return auxDIBImageLoadA(Filename); // Load The Bitmap And Return A Pointer } return NULL; } int LoadGLTextures() // Load Bitmaps And Convert To Textures { int Status=FALSE; // Status Indicator AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture memset(TextureImage,0,sizeof ( void *)*1); // Set The Pointer To NULL // Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if (TextureImage[0]=LoadBMP("aila.bmp")) { Status=TRUE; // Set The Status To TRUE glGenTextures(1, &texture[0]); // Create The Texture // Typical Texture Generation Using Data From The Bitmap glBindTexture(GL_TEXTURE_2D, texture[0]); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); // Free The Texture Image Memory } free(TextureImage[0]); // Free The Image Structure } return Status; // Return The Status } void resize(GLsizei width, GLsizei height) // Resize And Initialize The GL Window { if (height==0) // Prevent A Divide By Zero By { height=5; // Making Height Equal One } glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } int init(GLvoid) // All Setup For OpenGL Goes Here
{ if (!LoadGLTextures()) // Jump To Texture Loading Routine ( NEW ) { return FALSE; // If Texture Didn't Load Return FALSE } glEnable(GL_TEXTURE_2D); // Enable Texture Mapping ( NEW ) glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glPolygonMode( GL_BACK, GL_FILL ); // Back Face Is Solid glPolygonMode( GL_FRONT, GL_LINE ); // Front Face Is Made Of Lines for (int x=0; x<45; x++) { for ( int y=0; y<45; y++) { points[x][y][0]=float ((x/5.0f)-4.5f); points[x][y][1]=float ((y/5.0f)-4.5f); points[x][y][2]=float (sin((((x/5.0f)*40.0f)/360.0f)*3.141592654*2.0f)); } } return TRUE; // Initialization Went OK } void mydisplay(GLvoid) // Here's Where We Do All The Drawing { int x, y; float float_x, float_y, float_xb, float_yb; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer glLoadIdentity(); // Reset The View glTranslatef(0.0f,0.0f,-12.0f); glRotatef(xrot,1.0f,0.0f,0.0f); glRotatef(yrot,0.0f,1.0f,0.0f); glRotatef(zrot,0.0f,0.0f,1.0f); glBindTexture(GL_TEXTURE_2D, texture[0]); glBegin(GL_QUADS); for ( x = 0; x < 44; x++ ) { for ( y = 0; y < 44; y++ )
{ float_x = float (x)/44.0f; float_y = float (y)/44.0f; float_xb = float (x+1)/44.0f; float_yb = float (y+1)/44.0f; glTexCoord2f( float_x, float_y); glVertex3f( points[x][y][0], points[x][y][1], points[x][y][2] ); glTexCoord2f( float_x, float_yb ); glVertex3f( points[x][y+1][0], points[x][y+1][1], points[x][y+1][2] ); glTexCoord2f( float_xb, float_yb ); glVertex3f( points[x+1][y+1][0], points[x+1][y+1][1], points[x+1][y+1][2] ); glTexCoord2f( float_xb, float_y ); glVertex3f( points[x+1][y][0], points[x+1][y][1], points[x+1][y][2] ); } } glEnd(); if( wiggle_count == 2 ) { for ( y = 0; y < 45; y++ ) { hold=points[0][y][2]; for ( x = 0; x < 44; x++) { points[x][y][2] = points[x+1][y][2]; } points[44][y][2]=hold; } wiggle_count = 0; } wiggle_count++; xrot+=0.3f; yrot+=0.2f; zrot+=0.4f; glFlush(); glutSwapBuffers(); } void myTimeOut( int id) { // called if timer event // ...advance the state of animation incrementally... //rot+=1; glutPostRedisplay(); // request redisplay glutTimerFunc(15, myTimeOut, 0); // request next timer event } void myKeyboard(unsigned char key, int x, int y) { }