PDA

توجه ! این یک نسخه آرشیو شده میباشد و در این حالت شما عکسی را مشاهده نمیکنید برای مشاهده کامل متن و عکسها بر روی لینک مقابل کلیک کنید : برنامه هایی گرافیكی ( OpenGL )



Admin
15th September 2008, 08:08 PM
با سلام خدمت تمامی دوستان.
از این به بعد می خوام سورس و اجرا شده ی برنامه های گرافیکی رو با نام برنامه نویسی OpenGl برای عزیزان دانشجو بذارم.
امیدوارم مفید واقع بشه.

ابتدا از برنامه های خیلی ساده شروع می کنیم.

پس منتظر باشید

یا حق

Admin
15th September 2008, 08:09 PM
خب ما از برنامه ی ساده ی نمایش سه نقطه در صفحه سفید شروع می کنیم.


#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);
glVertex2i(100, 50); // draw three points
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd();
glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه:
http://alladin.persiangig.com/image/GraPhic/3%20point.JPG

Admin
15th September 2008, 08:22 PM
برنامه ی بعدی برنامه ی ساخت آدمك با استفاده از الگوریتم خاص خودش و همچنین با استفاده از یك میلیون نقطه در یك صفحه ..!


#include "stdafx.h"
#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
int px=121;
int py=115;
int qx=0;
int qy=0;

glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);

for (int i=0;i<1000000;i++){
if((px-120)>0)
qx=40*(1+6)- py + (px-120);
else
qx=40*(1+6)- py - (px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx,qy);
} //for

glEnd();
glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

اجرا شده ی برنامه :

http://alladin.persiangig.com/image/GraPhic/hadi%20khalili2.JPG

Admin
15th September 2008, 08:24 PM
برنامه ای كه برای دوستم هادی نوشتم رو هم اینجا می ذارم.
البته این برنامه فقط با نقطه نوشته شده:


#include "stdafx.h"
#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(0.0,0.0,0.0,1.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(5.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
int px=5;
int py=6;
int qx=50;
int qy=50;

glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){

qx++;
qy++;
glVertex2f(qx,qy);

} //for
for (int i=0;i<30;i++){
glVertex2f(qx++,qy--);

}//for
qx=150;
qy=150;
for (int i=0;i<30;i++){
glVertex2f(qx--,qy++);

}//for

for (int i=0;i<50;i++){
glVertex2f(qx++,qy++);

}//for

for (int i=0;i<60;i++){
glVertex2f(qx++,qy--);

}//for

for (int i=0;i<50;i++){
glVertex2f(qx--,qy--);

}//for
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(170,190);
glVertex2f(171,191);
glVertex2f(169,189);
glVertex2f(172,192);


glVertex2f(200,165);
glVertex2f(199,164);
glVertex2f(201,166);
glVertex2f(198,163);

qx=180;
qy=150;

for ( int i=0;i<25;i++){

glVertex2f(qx--,qy++);

}
glColor3f(1.0f, 1.0f, 1.0f);

qx=300;
qy=300;

for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}
qy=250;

for ( int i=0;i<50;i++){

glVertex2f(qx++,qy);

}

qx=350;
qy=300;

for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}

qx=400;
qy=300;

for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}

qx=400;
qy=300;

for ( int i=0;i<50;i++){

glVertex2f(qx++,qy);

}

for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}
qx=500;
qy=300;

for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}

for ( int i=0;i<50;i++){

glVertex2f(qx++,qy++);

}

for ( int i=0;i<50;i++){

glVertex2f(qx--,qy++);

}

qx=450;
qy=250;

for ( int i=0;i<50;i++){

glVertex2f(qx++,qy);

}

glVertex2f(405,250);
glVertex2f(415,250);
glVertex2f(425,250);
glVertex2f(435,250);
glVertex2f(445,250);

qx=600;
qy=300;

for ( int i=0;i<20;i++){

glVertex2f(qx--,qy);

}
for ( int i=0;i<40;i++){

glVertex2f(qx++,qy);

}

qx=600;
for ( int i=0;i<100;i++){

glVertex2f(qx,qy--);

}

for ( int i=0;i<20;i++){

glVertex2f(qx--,qy);

}
for ( int i=0;i<40;i++){

glVertex2f(qx++,qy);

}


glEnd();
glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه:


http://alladin.persiangig.com/image/GraPhic/hadi%20khalili%20---2.JPG

Admin
17th September 2008, 04:05 PM
نكته:

توجه داشته باشید كه برای برنامه ی آدمك می تونید رنگ آدمك رو با دستور glColor3f(0.0f, 0.0f, 0.0f); می تونید رنگ نقاط و با دستور glClearColor(1.0,1.0,1.0,0.0); می تونید رنگ زمینه رو تغییر بدید ...!

نمونه:

http://alladin.persiangig.com/image/GraPhic/mostafa%20kaveh2.JPG

Admin
17th September 2008, 04:07 PM
برنامه ای كه در اون سعی كردم تصویری شبیه به كندوی زنبور عسل رو در بیارم.


// mostafa kaveh2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
int abs(int a){
return ( a>0 ? a:-a);
}
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(0.0,0.0,0.0,1.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(3.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
int px=120;
int py=115;
int qx=0;
int qy=0;

glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);


glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-110,qy-110);
} //for
glColor3f(0.78f, 0.6f, 0.1f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-20,qy-20);
} //for
glColor3f(0.0f, 0.0f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+70,qy+70);
} //for
glColor3f(0.9f, 0.0f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+160,qy+160);
} //for


// --------------------------------------
glColor3f(0.7f, 0.16f, 0.6f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-65,qy+30);
} //for
glColor3f(0.9f, 0.9f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-155,qy-60);
} //for
glColor3f(0.9f, 0.5f, 0.5f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+25,qy+120);
} //for
glColor3f(1.0f, 1.0f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+115,qy+210);
} //for


// ---------------------------------
glColor3f(1.0f, 1.0f, 1.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-20,qy+170);
} //for

glColor3f(1.0f, 1.0f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-110,qy+80);
} //for
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+70,qy+260);
} //for
//-----------------------------------------
glColor3f(0.0f, 0.0f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx-70,qy-160);
} //for
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+25,qy-70);
} //for

glColor3f(0.0f, 0.0f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+115,qy+20);
} //for
glColor3f(1.0f, 1.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+205,qy+110);
} //for

//------------------------------------
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+250,qy+60);
} //for
glColor3f(1.0f, 1.0f, 1.0f);

for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+160,qy-30);
} //for
glColor3f(1.0f, 1.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+70,qy-120);
} //for
//------------------------------------
glColor3f(0.0f, 0.0f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+115,qy-170);
} //for
glColor3f(1.0f, 1.0f, 1.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+205,qy-80);
} //for

glColor3f(0.0f, 0.0f, 0.9f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+295,qy+10);
} //for

//------------------------------------------
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+250,qy-130);
} //for
glColor3f(1.0f, 1.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+340,qy-40);
} //for

//-----------------------------------------
glColor3f(0.0f, 0.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+295,qy-180);
} //for

glColor3f(1.0f, 1.0f, 1.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+385,qy-90);
} //for
//------------------------------------------
glColor3f(1.0f, 1.9f, 0.0f);
for (int i=0;i<100;i++){
qx=40*(1+6)- py + abs(px-120);
qy=px;
px=qx;
py=qy;
glVertex2f(qx+430,qy-140);
} //for

glEnd();
glFlush(); // send all output to display
}





//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه :

http://alladin.persiangig.com/image/GraPhic/mostafa%20kaveh-3.JPG

Admin
17th September 2008, 04:08 PM
شرح:
ابتدا روز هست و خورشيد از سمت چپ ميياد و آسمون روشن ميشه ، سپس خورشيد به سمت راست ميره و آسمون تيره ميشه و بعد از ناپديد شدن خورشيد آسمون تاريك و ستاره ها نمايان ميشند.





#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax,maxx,maxy;
int poly[16];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "f:\\borlandc\\bgi");
/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
cleardevice();
setbkcolor(9);
rectangle(0, 0, getmaxx(), getmaxy());

/************************** draw (chaman)********************************/
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
/* putpixel(200,420,6);
setfillstyle(1,6);
fillellipse(200, 400,10 , 50);
/************************** draw (khorshid) ***********************/
/******** step 1 **************/
setfillstyle(1,14);
fillellipse(20, 200,20,20);
/*********** step 2 *************/
delay(3500);
cleardevice();
setbkcolor(9);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,10);
fillpoly(8, poly);
setfillstyle(1,14);
fillellipse(300,50,20,20);
/****************************** step 3 *********************************/
delay(3500);
cleardevice();
setbkcolor(1);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
setfillstyle(1,14);
fillellipse(620, 200,20 , 20);
/***************** step 4 *************/
delay(3500);
cleardevice();
setbkcolor(0);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
/*********************** star ************************/
putpixel(100,100,15);
putpixel(150,180,15);
putpixel(250,180,15);
putpixel(150,280,15);
putpixel(350,280,15);
putpixel(350,80,15);
putpixel(150,80,15);
putpixel(500,280,15);
putpixel(350,280,15);
putpixel(550,280,15);
putpixel(600,180,15);
setfillstyle(1,15);
fillellipse(300, 50,5 , 25);
// arc(300, 100, 290, 140, 30);
/****************************** clean up *****************************/
getch();
closegraph();
return 0;
}

Admin
17th September 2008, 04:08 PM
شرح پروژه:

ابتدا ديوار رسم مي شود بعد از اتمام، سربازي با نيزه لبخند زنان بر روي ديوار قدم ميزند بعد از يك دور قدم زدن مي ايستد و كبوتري به پرواز مي پردازد.. .
گفتني است كه اين ديوار معروف چين مي باشد!


#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<stdio.h>
void parande(f) {
arc(550,f,110,180,20); arc(510,f,0,70,20);delay(600);
setcolor(0); arc(550,f,110,180,20); arc(510,f,0,70,20); setcolor(63);
arc(550,f+20,80,150,20); arc(516,f+20,30,110,20);delay(600);
setcolor(0); arc(550,f+20,80,150,20); arc(516,f+20,30,110,20); setcolor(63);
}
void sar(l,k,z) {
arc(l,260,190,290,10); line(k,261,k+3,260);
ellipse(l,245,0,360,4,6);ellipse(l+7,245,0,360,3,5 );
arc(l,260,100,410,15); circle(l,245,.5);circle(l+7,245,.5);
//neyze
line(z,240,z+6,240); line(z+1,240,z+3,220);line(z+2,240,z+3,220);
line(z+3,240,z+3,220);line(z+4,240,z+3,220);line(z +5,240,z+3,220);
line(z+6,240,z+3,220);line(z+3,240,z+3,280);
}
void badan(f,l,k,z) {
sar(l,k,z); arc(f,280,330,0,25);
line(f+20,292,72,340); arc(f-9,320,340,40,39);
line(f+25,335,f+35,339); arc(f+38,258,240,320,25);
line(f+57,240,f+57,340); ellipse(f+57,275,0,360,2,1);
}
void badan1(f,l,k,z) {
sar(l,k,z); arc(f,280,330,0,25);
line(f+20,292,f+20,340); arc(f-9,320,340,40,39);
line(f+25,335,f+35,339); arc(f+38,258,240,320,25);
line(f+57,240,f+57,340); ellipse(f+57,275,0,360,2,1);
}
void badan2(m,l,k,z){
sar(l,k,z);
arc(m,290,140,210,14); arc(m-56,322,340,30,50);
line(m-12,296,m+16,308);line(m+16,316,m-14,322); line(m-14,322,m-2,328);
arc(m+14,312,310,410,4);arc(m+18,282,180,290,30); ellipse(m+26,311,0,360,2,1);
line(m+26,240,m+26,340);ellipse(m-12,292,90,260,30,10);ellipse(m-16,302,0,360,2,1);
}
void badan3(p,l,k,z) {
sar(l,k,z); arc(p,280,330,0,25);
arc(p-28,320,340,30,55); arc(p-36,350,370,45,80);
arc(p+38,258,240,320,25); ellipse(p+56,277,0,360,2,1);
line(p+42,336,p+44,340); line(p+56,240,p+56,340);
}
//************************************************** *************************
void main()
{
int gdriver=DETECT,gmode=0,q,z, x1,x2,y1,y2,i,j,y,x,k,l,m,f;
char p[8]={10,20,30,40,50,60,70,80},ch;
initgraph(&gdriver,&gmode,"f:\\borlandc\\bgi");
//*******************
rectangle(0,0,639,479);
//mah****************
setcolor(62);
circle(100,100,30);
setfillpattern(p,63);
floodfill(120,100,62);
setcolor(63);
//derakht ************************************************** ******************
line(0,250,50,160); line(50,160,130,50); line(10,230,40,100);
arc(230,340,100,140,250); arc(-93,140,350,30,120); arc(0,150,350,30,50);
arc(70,136,320,350,50); arc(-118,-160,290,310,400); arc(150,454,98,110,270);
arc(230,414,120,130,300); arc(120,62,300,330,50); arc(140,300,90,110,170);
arc(30,158,300,330,50); arc(-14,140,320,350,50); arc(-30,180,350,30,50);
arc(130,404,110,130,200);
//row1********************************************** **************************
for(x1=0,y1=460,x2=40,y2=479,i=1;i<=16;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);} ;
/***star*/circle(20,60,1);delay(300);circle(320,120,1);delay (300);circle(400,50,1);
//row2*********
rectangle(0,440,20,460);
for(x1=20,y1=440,x2=60,y2=460,i=1;i<=15;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
rectangle(620,440,639,460);
/***star*/circle(120,180,1);delay(300);circle(190,64,1);dela y(300);circle(560,130,1);
//row3**********
for(x1=0,y1=420,x2=40,y2=440,i=1;i<=16;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
/***star*/ circle(20,170,1);delay(300);circle(420,130,1);dela y(300);circle(480,190,1);
//row4**********
rectangle(0,400,20,420);
for(x1=20,y1=400,x2=60,y2=420,i=1;i<=15;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
rectangle(620,400,639,420);
//row5**********
for(x1=0,y1=380,x2=40,y2=400,i=1;i<=16;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
/***star*/ circle(160,120,1);delay(300);circle(280,27,1);dela y(300);circle(480,65,1);
//row6**********
rectangle(0,360,20,380);
for(x1=20,y1=360,x2=60,y2=380,i=1;i<=15;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
rectangle(620,360,639,380);
/***star*/ circle(240,127,1);delay(300);circle(360,198,1);del ay(300);circle(580,25,1);
//row7**********
for(x1=0,y1=340,x2=40,y2=360,i=1;i<=16;x1+=40,x2+=40,i++)
{rectangle(x1,y1,x2,y2);delay(100);}
/***star*/circle(40,17,1);delay(320);circle(340,14,1);delay( 300);circle(620,197,1);
//halfrow8******
rectangle(0,320,20,340);delay(100);rectangle(20,32 0,60,340);delay(200);
for(x1=180,y1=320,x2=220,y2=340,i=1;i<=4;x1+=200,x2+=200,i++)
{rectangle(x1,y1,x2,y2);delay(100);rectangle(x1,y1 ,x2+40,y2);delay(200);}
/***star*/ for(x=40,y=83;x<630;x+=80) { circle(x,y,1);delay(300);}
circle(540,37,1);delay(300);circle(300,64,1);delay (300);circle(280,205,1);
//halfrow9******
rectangle(0,300,40,320);delay(100);rectangle(40,30 0,60,320);delay(100);
rectangle(180,300,200,320);delay(100);rectangle(20 0,300,240,320);delay(100); rectangle(240,300,260,320);delay(300);
rectangle(380,300,400,320);delay(100);rectangle(40 0,300,440,320); delay(100);rectangle(440,300,460,320);delay(300);
rectangle(580,300,600,320);delay(100);rectangle(60 0,300,640,320);
/***star*/ circle(220,170,1);delay(300);circle(500,50,1);dela y(300);circle(120,45,1);
for(x=80,y=150;x<630;x+=100) { circle(x,y,1);delay(200);}
//halfrow10******
rectangle(0,280,20,300);delay(100);rectangle(20,28 0,60,300);delay(100);
for(x1=180,y1=280,x2=220,y2=300,i=1;i<=4;x1+=200,x2+=200,i++)
{rectangle(x1,y1,x2,y2);delay(100);rectangle(x1,y1 ,x2+40,y2);delay(100);}
//sarbaz******************************************** *************************
badan(42,80,68,96); delay(1000);
setcolor(0), badan(42,80,68,96); setcolor(63);
badan2(118,120,108,141); delay(1000);
setcolor(0); badan2(118,120,108,141); setcolor(63);
badan3(122,160,148,175); delay(1000);
setcolor(0); badan3(122,160,148,175); setcolor(63);
//**************
sar(210,198,240,240); delay(1000);
setcolor(0); sar(210,198,240,240); setcolor(63);
badan1(242,280,268,296); delay(1000);
setcolor(0), badan1(242,280,268,296); setcolor(63);
badan2(318,320,308,341); delay(1000);
setcolor(0); badan2(318,320,308,341); setcolor(63);
badan3(322,360,348,375); delay(1000);
setcolor(0); badan3(322,360,348,375); setcolor(63);
//*********************
sar(410,398,440); delay(1000);
setcolor(0); sar(410,398,440); setcolor(63);
badan1(442,480,468,496); delay(1000);
setcolor(0), badan1(442,480,468,496); setcolor(63);
badan2(518,520,608,541); delay(1000);
setcolor(0); badan2(518,520,508,541); setcolor(63);
badan3(522,560,548,575); delay(1000);
setcolor(0); badan3(522,560,548,575); setcolor(63);
//*************
sar(610,598,630); delay(1000);
setcolor(0); sar(610,598,630);setcolor(63);
delay(1000); sar(30,18,58); delay(1000);
setcolor(0); sar(30,18,58); setcolor(63);
badan(42,80,68,96);delay(1000);
//***********************************************
outtextxy(220,220,"THE GREATEST CHINESE WALL");
//parande****************************************
for(f=0;f<320;f+=20) parande(f);
//***********************************************
ch=getch();
closegraph();
}

Admin
17th September 2008, 04:09 PM
خب دوستان چند برنامه ی گرافیكی دیگه كه كار خودمه رو براتون می ذارم.
امیدوارم مفید واقع بشه ...http://www.daneshju.ir/forum/images/smilies/2007/icon_arrow.gif


#include "stdafx.h"
#include <windows.h> // use proper includes for your system
#include <math.h>
#include <gl/Gl.h>
#include <gl/glut.h>
const int screenWidth = 640; // width of screen window in pixels
const int screenHeight = 480; // height of screen window in pixels
GLdouble A, B, C, D; // values used for scaling and shifting
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(0.0,0.0,0.0,1.0); // background color is white
glColor3f(1.0f, 1.0f, 1.0f); // drawing color is black
glPointSize(2.0); // a 'dot' is 2 by 2 pixels
glMatrixMode(GL_PROJECTION); // set "camera shape"
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenHeight);
A = 75.0; // set values used for scaling and shifting
B = 0.0;
C = D = screenHeight / 2.0;
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_LINES);
glColor3f(1.0f, 1.0f, 0.0f);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = exp(-x) * cos(2 * 3.14159265 * x);

glVertex2d(145 * x + B, C * func + D);
}
glEnd();

glBegin(GL_LINES);

glColor3f(1.0f, 0.0f, 0.0f);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = exp(-x) * cos(2 * 3.14159265 * x);

glVertex2d(150 * x + B, C * func + D);
}
glEnd();


glBegin(GL_LINES);

glColor3f(0.0f, 1.0f, 0.0f);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = exp(-x) * cos(2 * 3.14159265 * x);

glVertex2d(155 * x + B, C * func + D);
}
glEnd();


glBegin(GL_LINES);

glColor3f(0.0f, 0.0f, 1.0f);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = exp(-x) * cos(2 * 3.14159265 * x);

glVertex2d(160 * x + B, C * func + D);
}
glEnd();

glBegin(GL_LINES);

glColor3f(1.0f, 1.0f, 1.0f);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = exp(-x) * cos(2 * 3.14159265 * x);

glVertex2d(140 * x + B, C * func + D);
}
glEnd();

glFlush(); // send all output to display
}
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(screenWidth, screenHeight); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Dot Plot of a Function"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه:

http://alladin.persiangig.ir/image/GraPhic/Hadi%20Khalili%20-%204.JPG

Admin
17th September 2008, 04:10 PM
برنامه ای كه دو شی رو همانند خروجی می سازد ..!


#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POLYGON);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(100, 50);

glColor3f(0.0f, 1.0f, 0.0f);
glVertex2i(200, 130);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2i(50, 130);



glEnd();

glBegin(GL_POLYGON);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2i(100, 400);
glVertex2i(100, 130);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(50, 130);



glEnd();




glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2i(100, 400);
glVertex2i(200, 130);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(125, 130);

glEnd();

glBegin(GL_POLYGON);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(100, 400);
glVertex2i(125, 130);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(50, 130);

glEnd();

glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2i(640, 400);
glVertex2i(500, 400);
glVertex2i(640, 480);

glEnd();


glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2i(640, 300);
glVertex2i(400, 300);
glVertex2i(640, 400);

glEnd();


glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2i(640, 200);
glVertex2i(300, 200);
glVertex2i(640, 300);

glEnd();


glBegin(GL_POLYGON);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(640, 200);
glVertex2i(300, 200);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(100, 0);
glColor3f(1.0f, 0.5f, 0.0f);
glVertex2i(640, 0);
glEnd();


glBegin(GL_POLYGON);
glColor3f(0.5f, 0.5f, 0.0f);
glVertex2i(640, 200);
glVertex2i(600, 200);
glVertex2i(600, 0);
glVertex2i(640, 0);
glEnd();






glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه :

http://alladin.persiangig.com/image/GraPhic/Hadi%20-%20khalili%205.JPG

Admin
17th September 2008, 04:11 PM
اینم برنامه ای دیگه برای ساخت یك سری منحنی مانند خروجی ...


// mk.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h> // use proper includes for your system
#include <math.h>
#include <gl/Gl.h>
#include <gl/glut.h>
const int screenWidth = 640; // width of screen window in pixels
const int screenHeight = 480; // height of screen window in pixels
GLdouble A, B, C, D; // values used for scaling and shifting
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(0.0,0.0,0.0,1.0); // background color is white
glColor3f(0.0f, 0.0f, 0.0f); // drawing color is black
glPointSize(2.0); // a 'dot' is 2 by 2 pixels
glMatrixMode(GL_PROJECTION); // set "camera shape"
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenHeight);
A = screenWidth / 4.0; // set values used for scaling and shifting
B = 0.0;
C = D = screenHeight / 2.0;
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);
glColor3f(1.0,1.0,0.0);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = sin(5*x)* 0.5 /5*x;
glVertex2f(A * x / 2 + B , C * func + D+125);
}

/* for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = sin(5*x)* 0.5 /5*x;
glVertex2f(A * x / 1+B, C * func + 1.5*D);
} */
glColor3f(0.0,0.9,0.0);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = cos(5 * x)* 0.5 / 5 * x;
glVertex2f(A * x / 2 + B, C * func + D+125);
}
glColor3f(0.9,0.0,0.0);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = cos(5 * x)* 0.5 / 5 * x;
glVertex2f(A * x / 2 + B + 15, C * func + D+125);
}
glColor3f(0.0 , 0.0 , 0.9);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = sin(5*x)* 0.5 /5*x;
glVertex2f(A * x / 2 + B + 15, C * func + D+125);
}
//------------------------------------------------------

glColor3f(1.0,1.0,1.0);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = sin(5*x)* 0.5 /5*x;
glVertex2f(A * x / 2 + B , C * func + D-125);
}


glColor3f(0.0,0.9,0.5);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = cos(5 * x)* 0.5 / 5 * x;
glVertex2f(A * x / 2 + B, C * func + D-125);
}
glColor3f(0.5,0.0,0.9);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = cos(5 * x)* 0.5 / 5 * x;
glVertex2f(A * x / 2 + B + 15, C * func + D-125);
}
glColor3f(0.9 , 0.0 , 0.9);

for(GLdouble x = 0; x < 4.0 ; x += 0.005)
{
GLdouble func = sin(5*x)* 0.5 /5*x;
glVertex2f(A * x / 2 + B + 15, C * func + D-125);
}
glEnd();
glFlush(); // send all output to display
}
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(screenWidth, screenHeight); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Dot Plot of a Function"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه:

http://alladin.persiangig.ir/image/GraPhic/mostafa%20kaveh-4.JPG

Admin
17th September 2008, 04:12 PM
اینم یه برنامه ای پرچم ایران به همراه یه پاكت نامه درست می كنه ..!


// M3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen

// ---------------- back ground -------------------------

glBegin(GL_POLYGON);

glVertex2i(200, 600);
glVertex2i(205, 600);
glVertex2i(205, 0);
glVertex2i(200, 0);

glEnd();


glBegin(GL_POLYGON);
glColor3f(0.0f, 0.5f, 0.9f);
glVertex2i(205, 600);
glVertex2i(800, 600);
glVertex2i(800, 0);
glVertex2i(205, 0);

glEnd();



//----------------------------------------------------------




glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(50, 50);
glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 50);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

//--------------------------------------------------

glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(200, 200);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(200, 50);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

glEnd();
//---------------------------------------------------
//---------------------------------------------------
glBegin(GL_POLYGON);



//--------------------------------------------------

glColor3f(0.9f, 0.0f, 0.0f);

glVertex2i(50, 200);

glColor3f(0.0f, 0.0f, 0.9f);

glVertex2i(50, 350);

glColor3f(1.0f, 1.0f, 0.0f);


glVertex2i(200, 200);
glVertex2i(50, 200);


//-------------------------------------

glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(200, 350);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(200, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(50, 350);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(200, 350);


//-------------------------
glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(50, 350);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

glEnd();

// ****************************** parcham ******************************

glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);

int qx=227;
int qy=302;

for(int i=0; i <350 ; i++){
glVertex2i(qx, qy);

qx++;
qy;
}

for(int i=0; i <179 ; i++){
glVertex2i(qx, qy);

qx;
qy--;
}

for(int i=0; i <354 ; i++){
glVertex2i(qx, qy);

qx--;
qy;
}


for(int i=0; i <180 ; i++){
glVertex2i(qx, qy);

qx;
qy++;
}

glEnd();

//---------------------- plygon GREEN ----------------------------
glColor3f(0.0f, 0.9f, 0.0f);
glBegin(GL_POLYGON);

glVertex2i(225, 300);

glColor3f(0.5f, 0.9f, 0.5f);

glVertex2i(575, 300);
glVertex2i(575,245);

glColor3f(0.0f, 0.9f, 0.0f);

glVertex2i(225, 245);

glEnd();
//-------------------------polygon white -------------------------------
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POLYGON);
glVertex2i(225, 245);
glVertex2i(575,245);

glVertex2i(575, 180);
glVertex2i(225, 180);
glEnd();



//------------------------polygon red --------------------

glColor3f(0.9f, 0.0f, 0.0f);
glBegin(GL_POLYGON);

glVertex2i(225, 180);

glColor3f(0.9f, 0.5f, 0.5f);

glVertex2i(575, 180);
glVertex2i(575, 125);

glColor3f(0.9f, 0.0f, 0.0f);


glVertex2i(225, 125);
glEnd();
// ---------------------- mileye parcham ------------------
glBegin(GL_POLYGON);
glColor3f(0.5f, 0.25f, 0.25f);


glVertex2i(578, 308);
glColor3f(0.68f, 0.37f, 0.37f);

glVertex2i(587, 308);
glVertex2i(587,0);

glColor3f(0.5f, 0.25f, 0.25f);
glVertex2i(578,0);




glEnd();

//----------------------------- allah ---------------------------


glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);


qx= 412;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}



//****

qx= 398;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

for( int i=0; i<5 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}

glVertex2i(404, 191);
glVertex2i(403, 190);
glVertex2i(402, 190);
glVertex2i(401, 189);
glVertex2i(400, 189);
glVertex2i(399, 188);
glVertex2i(398, 188);
glVertex2i(397, 187);
glVertex2i(396, 187);
glVertex2i(395, 186);
glVertex2i(394, 186);
glVertex2i(393, 185);
glVertex2i(392, 185);
glVertex2i(391, 184);
glVertex2i(390, 184);

glVertex2i(389, 183);
glVertex2i(388, 183);


glVertex2i(387, 182);
glVertex2i(386, 182);
glVertex2i(385, 181);
glVertex2i(384, 181);

glVertex2i(383, 181);
glVertex2i(383, 181);

glVertex2i(382, 181);
glVertex2i(382, 181);


glVertex2i(381, 181);
glVertex2i(381, 181);

//--------------------------------------------

qx= 391;
qy = 230;

for( int i=0; i<50 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

//--------------------------------------------

qx= 384;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}
for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}


for( int i=0; i<5 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}


qx=377;
qy=191;

glVertex2i(378, 191);
glVertex2i(379, 190);
glVertex2i(380, 190);
glVertex2i(381, 189);
glVertex2i(382, 189);
glVertex2i(383, 188);
glVertex2i(384, 188);
glVertex2i(385, 187);
glVertex2i(386, 187);
glVertex2i(387, 186);
glVertex2i(388, 186);
glVertex2i(389, 185);
glVertex2i(390, 185);
glVertex2i(391, 184);
glVertex2i(392, 184);

glVertex2i(393, 183);
glVertex2i(394, 183);

glVertex2i(395, 182);
glVertex2i(396, 182);

glVertex2i(397, 181);
glVertex2i(398, 181);

glVertex2i(399, 181);
glVertex2i(400, 181);

glVertex2i(401, 181);
glVertex2i(402, 181);

//***

qx=370;
qy=230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}
for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}


for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

glVertex2i(398, 242);
glVertex2i(398, 241);
glVertex2i(398, 240);
glVertex2i(398, 239);
glVertex2i(398, 238);
glVertex2i(397, 237);
glVertex2i(396, 236);
glVertex2i(395, 237);
glVertex2i(394, 237);
glVertex2i(393, 237);
glVertex2i(392, 237);

glVertex2i(392, 237);
glVertex2i(392, 238);
glVertex2i(392, 239);
glVertex2i(392, 240);
glVertex2i(392, 241);
glVertex2i(392, 242);


glVertex2i(391, 236);
glVertex2i(390, 236);
glVertex2i(389, 236);
glVertex2i(388, 236);


glVertex2i(387, 237);
glVertex2i(386, 238);

glVertex2i(386, 239);
glVertex2i(386, 240);
glVertex2i(386, 241);
glVertex2i(386, 242);



glEnd();


// ---------------------- Text ( zende ) ------------------------------

glBegin(GL_POINTS);

glVertex2d(550,70);
glVertex2d(551,70);
glVertex2d(551,69);
glVertex2d(550,69);

int px = 555;
int py = 55;


for( int i=0;i<15;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
}

for( int i=0;i<25;i++){
glVertex2f(px,py);
py--;
px--;
}

px = 535;
py = 65;


for( int i=0;i<30;i++){
glVertex2f(px,py);
py--;
}

for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
px--;
}


for( int i=0;i<20;i++){
px++;
py--;
}


for( int i=0;i<20;i++){
glVertex2f(px,py);
py--;
px--;
}

glVertex2f(510,70);
glVertex2f(511,70);
glVertex2f(511,69);
glVertex2f(510,69);


// ------------------ heeeeeeeeeeee ----------------------

glVertex2f(470,38);

px=470;
py=38;
for( int i=0;i<10;i++){
glVertex2f(px,py);
py--;
px++;
}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
px--;
}

for( int i=0;i<10;i++){
glVertex2f(px,py);
px--;

}
for( int i=0;i<10;i++){
glVertex2f(px,py);
py++;

}

for( int i=0;i<7;i++){
glVertex2f(px,py);
py++;
px++;
}

// ----------------------- text ( baaaad) --------------------
px = 450;
py = 35;

for( int i=0;i<10;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
px--;
}

for( int i=0;i<30;i++){
glVertex2f(px,py);
px--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py++;
px--;
}

for( int i=0;i<40;i++){
glVertex2f(px,py);
py++;

}
glVertex2f(430,10);
glVertex2f(430,9);
glVertex2f(429,9);
glVertex2f(430,10);

px = 395;
py = 30;

for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
px--;
}
for( int i=0;i<20;i++){
py--;
px++;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
py--;
px--;
}

// ------------------------ text ( iran ) ----------------------------

px = 340;
py = 80;

for( int i=0;i<60;i++){
glVertex2f(px,py);

py--;
}

// ---------------------------------- ---- -------------------------------

px = 320;
py = 50;

for( int i=0;i<20;i++){
glVertex2f(px,py);

py--;
}
for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;

}
for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;
py--;
}


px = 315;
py = 10;

for( int i=0;i<10;i++){
glVertex2f(px,py);
px--;

}


px = 270;
py = 75;

for( int i=0;i<55;i++){
glVertex2f(px,py);

py--;
}

px = 250 ;
py = 40 ;

for( int i=0;i<20;i++){
glVertex2f(px,py);

py--;
}
for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<15;i++){
glVertex2f(px,py);
px--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py++;
}
for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
}

glVertex2f(239,40);
glVertex2f(238,40);
glVertex2f(238,41);
glVertex2f(239,41);



glEnd();

glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

خروجی برنامه :

http://alladin.persiangig.com/image/GraPhic/mostafa-kaveh%205.JPG

Admin
17th September 2008, 04:14 PM
این برنامه همین برنامه ی قبلیه كه پرچم رو با استفاده از كلمه ی مقدس الله اكبر Stipple کردم.


// M3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{

GLubyte allah[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0C, 0x60, 0x00, 0x00, 0x06, 0x60, 0x00, 0x20, 0x03, 0x00, 0x1F, 0xA0,
0x01, 0xF1, 0x12, 0xA0, 0x00, 0x31, 0x72, 0xA0, 0x00, 0x11, 0x72, 0xA0, 0x00, 0x11, 0x32, 0xA0,
0x00, 0x19, 0x00, 0xA0, 0x00, 0x0C, 0x00, 0x20, 0x00, 0x06, 0x0F, 0x80, 0x00, 0x02, 0x0A, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};



glClear(GL_COLOR_BUFFER_BIT); // clear the screen

// ---------------- back ground -------------------------

glBegin(GL_POLYGON);

glVertex2i(200, 600);
glVertex2i(205, 600);
glVertex2i(205, 0);
glVertex2i(200, 0);

glEnd();


glBegin(GL_POLYGON);
glColor3f(1.0f, 1.0f, 1.0f);
glVertex2i(205, 600);
glVertex2i(800, 600);
glVertex2i(800, 0);
glVertex2i(205, 0);

glEnd();



//----------------------------------------------------------




glBegin(GL_POLYGON);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(50, 50);
glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 50);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

//--------------------------------------------------

glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(200, 200);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(200, 50);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

glEnd();
//---------------------------------------------------
//---------------------------------------------------
glBegin(GL_POLYGON);



//--------------------------------------------------

glColor3f(0.9f, 0.0f, 0.0f);

glVertex2i(50, 200);

glColor3f(0.0f, 0.0f, 0.9f);

glVertex2i(50, 350);

glColor3f(1.0f, 1.0f, 0.0f);


glVertex2i(200, 200);
glVertex2i(50, 200);


//-------------------------------------

glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(200, 350);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(200, 200);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(50, 350);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex2i(200, 350);


//-------------------------
glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(50, 200);
glColor3f(0.0f, 0.0f, 0.9f);
glVertex2i(50, 350);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(200, 200);

glEnd();

// ****************************** parcham ******************************

glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);

int qx=227;
int qy=302;

for(int i=0; i <350 ; i++){
glVertex2i(qx, qy);

qx++;
qy;
}

for(int i=0; i <179 ; i++){
glVertex2i(qx, qy);

qx;
qy--;
}

for(int i=0; i <354 ; i++){
glVertex2i(qx, qy);

qx--;
qy;
}


for(int i=0; i <180 ; i++){
glVertex2i(qx, qy);

qx;
qy++;
}

glEnd();

//---------------------- plygon GREEN ----------------------------
glColor3f(0.0f, 0.9f, 0.0f);
glBegin(GL_POLYGON);

glVertex2i(225, 300);
glColor3f(0.5f, 0.9f, 0.5f);
glVertex2i(575, 300);
glVertex2i(575,245);
glColor3f(0.0f, 0.9f, 0.0f);
glVertex2i(225, 245);

glEnd();
//------------------------- Polygon Stripple first allah --------------------------
glEnable (GL_POLYGON_STIPPLE);
glPolygonStipple (allah);
glColor3f(0.0f, 0.0f, 0.0f);

glBegin(GL_POLYGON);

glVertex2i(225, 300);
glVertex2i(575, 300);
glVertex2i(575,255);
glVertex2i(225, 255);

glEnd();
glDisable (GL_POLYGON_STIPPLE);

//-------------------------polygon white -------------------------------
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POLYGON);
glVertex2i(225, 245);
glVertex2i(575,245);

glVertex2i(575, 180);
glVertex2i(225, 180);
glEnd();


//------------------------polygon red --------------------

glColor3f(0.9f, 0.0f, 0.0f);
glBegin(GL_POLYGON);

glVertex2i(225, 180);
glColor3f(0.9f, 0.5f, 0.5f);
glVertex2i(575, 180);
glVertex2i(575, 125);
glColor3f(0.9f, 0.0f, 0.0f);
glVertex2i(225, 125);

glEnd();


//----------------------- polygon Striple second polygon -------------------
glEnable (GL_POLYGON_STIPPLE);
glPolygonStipple (allah);

glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POLYGON);

glVertex2i(225, 160);
glVertex2i(575, 160);
glVertex2i(575, 125);
glVertex2i(225, 125);


glEnd();

glDisable (GL_POLYGON_STIPPLE);



// ---------------------- mileye parcham ------------------
glBegin(GL_POLYGON);
glColor3f(0.5f, 0.25f, 0.25f);


glVertex2i(578, 308);
glColor3f(0.68f, 0.37f, 0.37f);

glVertex2i(587, 308);
glVertex2i(587,0);

glColor3f(0.5f, 0.25f, 0.25f);
glVertex2i(578,0);




glEnd();

//----------------------------- allah ---------------------------


glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);


qx= 412;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}



//****

qx= 398;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

for( int i=0; i<5 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}

glVertex2i(404, 191);
glVertex2i(403, 190);
glVertex2i(402, 190);
glVertex2i(401, 189);
glVertex2i(400, 189);
glVertex2i(399, 188);
glVertex2i(398, 188);
glVertex2i(397, 187);
glVertex2i(396, 187);
glVertex2i(395, 186);
glVertex2i(394, 186);
glVertex2i(393, 185);
glVertex2i(392, 185);
glVertex2i(391, 184);
glVertex2i(390, 184);

glVertex2i(389, 183);
glVertex2i(388, 183);


glVertex2i(387, 182);
glVertex2i(386, 182);
glVertex2i(385, 181);
glVertex2i(384, 181);

glVertex2i(383, 181);
glVertex2i(383, 181);

glVertex2i(382, 181);
glVertex2i(382, 181);


glVertex2i(381, 181);
glVertex2i(381, 181);

//--------------------------------------------

qx= 391;
qy = 230;

for( int i=0; i<50 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}

//--------------------------------------------

qx= 384;
qy = 230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}
for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}


for( int i=0; i<5 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}


qx=377;
qy=191;

glVertex2i(378, 191);
glVertex2i(379, 190);
glVertex2i(380, 190);
glVertex2i(381, 189);
glVertex2i(382, 189);
glVertex2i(383, 188);
glVertex2i(384, 188);
glVertex2i(385, 187);
glVertex2i(386, 187);
glVertex2i(387, 186);
glVertex2i(388, 186);
glVertex2i(389, 185);
glVertex2i(390, 185);
glVertex2i(391, 184);
glVertex2i(392, 184);

glVertex2i(393, 183);
glVertex2i(394, 183);

glVertex2i(395, 182);
glVertex2i(396, 182);

glVertex2i(397, 181);
glVertex2i(398, 181);

glVertex2i(399, 181);
glVertex2i(400, 181);

glVertex2i(401, 181);
glVertex2i(402, 181);

//***

qx=370;
qy=230;

for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx--;
qy--;
}
for( int i=0; i<22 ; i++){

glVertex2i(qx, qy);

qx;
qy--;
}


for( int i=0; i<12 ; i++){

glVertex2i(qx, qy);

qx++;
qy--;
}

glVertex2i(398, 242);
glVertex2i(398, 241);
glVertex2i(398, 240);
glVertex2i(398, 239);
glVertex2i(398, 238);
glVertex2i(397, 237);
glVertex2i(396, 236);
glVertex2i(395, 237);
glVertex2i(394, 237);
glVertex2i(393, 237);
glVertex2i(392, 237);

glVertex2i(392, 237);
glVertex2i(392, 238);
glVertex2i(392, 239);
glVertex2i(392, 240);
glVertex2i(392, 241);
glVertex2i(392, 242);


glVertex2i(391, 236);
glVertex2i(390, 236);
glVertex2i(389, 236);
glVertex2i(388, 236);


glVertex2i(387, 237);
glVertex2i(386, 238);

glVertex2i(386, 239);
glVertex2i(386, 240);
glVertex2i(386, 241);
glVertex2i(386, 242);



glEnd();


// ---------------------- Text ( zende ) ------------------------------

glBegin(GL_POINTS);

glVertex2d(550,70);
glVertex2d(551,70);
glVertex2d(551,69);
glVertex2d(550,69);

int px = 555;
int py = 55;


for( int i=0;i<15;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
}

for( int i=0;i<25;i++){
glVertex2f(px,py);
py--;
px--;
}

px = 535;
py = 65;


for( int i=0;i<30;i++){
glVertex2f(px,py);
py--;
}

for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
px--;
}


for( int i=0;i<20;i++){
px++;
py--;
}


for( int i=0;i<20;i++){
glVertex2f(px,py);
py--;
px--;
}

glVertex2f(510,70);
glVertex2f(511,70);
glVertex2f(511,69);
glVertex2f(510,69);


// ------------------ heeeeeeeeeeee ----------------------

glVertex2f(470,38);

px=470;
py=38;
for( int i=0;i<10;i++){
glVertex2f(px,py);
py--;
px++;
}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
px--;
}

for( int i=0;i<10;i++){
glVertex2f(px,py);
px--;

}
for( int i=0;i<10;i++){
glVertex2f(px,py);
py++;

}

for( int i=0;i<7;i++){
glVertex2f(px,py);
py++;
px++;
}

// ----------------------- text ( baaaad) --------------------
px = 450;
py = 35;

for( int i=0;i<10;i++){
glVertex2f(px,py);
py--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py--;
px--;
}

for( int i=0;i<30;i++){
glVertex2f(px,py);
px--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
py++;
px--;
}

for( int i=0;i<40;i++){
glVertex2f(px,py);
py++;

}
glVertex2f(430,10);
glVertex2f(430,9);
glVertex2f(429,9);
glVertex2f(430,10);

px = 395;
py = 30;

for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
px--;
}
for( int i=0;i<20;i++){
py--;
px++;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
py--;
px--;
}

// ------------------------ text ( iran ) ----------------------------

px = 340;
py = 80;

for( int i=0;i<60;i++){
glVertex2f(px,py);

py--;
}

// ---------------------------------- ---- -------------------------------

px = 320;
py = 50;

for( int i=0;i<20;i++){
glVertex2f(px,py);

py--;
}
for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;

}
for( int i=0;i<20;i++){
glVertex2f(px,py);
px--;
py--;
}


px = 315;
py = 10;

for( int i=0;i<10;i++){
glVertex2f(px,py);
px--;

}


px = 270;
py = 75;

for( int i=0;i<55;i++){
glVertex2f(px,py);

py--;
}

px = 250 ;
py = 40 ;

for( int i=0;i<20;i++){
glVertex2f(px,py);

py--;
}
for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py--;
}

for( int i=0;i<15;i++){
glVertex2f(px,py);
px--;

}

for( int i=0;i<5;i++){
glVertex2f(px,py);
px--;
py++;
}
for( int i=0;i<20;i++){
glVertex2f(px,py);
py++;
}

glVertex2f(239,40);
glVertex2f(238,40);
glVertex2f(238,41);
glVertex2f(239,41);



glEnd();

glFlush(); // send all output to display
}

//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("parcham"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}

تصویر خروجی رو به عنوان پیوست آپلود کردم.

Admin
17th September 2008, 05:46 PM
خب از این به بعد می ریم سر قرار دادن برنامه های انیمیشن و متحرك.... http://www.daneshju.ir/forum/images/smilies/2007/icon_arrow.gif

این برنامه ی چینش دیواره كه در سیستم عامل های قدیمی به عنوان اسكرین سیور هم استفاده می شد. http://www.daneshju.ir/forum/images/smilies/2007/icon_wink.gif


#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
int flag=0;
int x1=0,y1=0,ystep=8,xstep=8,count=1,gap=1;
void display()
{
switch(flag){ // Switch Flag For Changing Brick Color
case 1:
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 2:
glColor3f(0.0f, 1.0f, 0.0f);
break;

case 3:
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 4:
glColor3f(1.0f, 1.0f, 0.0f);
break;
case 5:
glColor3f(1.0f, 0.0f, 1.0f);
break;
case 6:
glColor3f(1.0f, 0.5f, 0.0f);
break;
case 7:
glColor3f(0.5f, 0.0f, 1.0f);
break;
case 8:
glColor3f(1.0f, 1.0f, 0.0f);
break;
case 9:
glColor3f(0.5f, 0.0f, 0.5f);
break;
case 10:
glColor3f(0.0f, 1.0f, 1.0f);
break;

}
glBegin(GL_POLYGON);
glVertex2i(x1,y1);
glVertex2i(x1,y1+ystep);
glVertex2i(x1+xstep,y1+ystep);
glVertex2i(x1+xstep,y1);
glEnd();
glFlush();
}
void myinit()
{
gluOrtho2D(100,0,0,300);
}
void TimerFunction(int value)
{
if(value!=1){ //First BRICK INCREASEING
x1+=(xstep+gap);
}
else glClear(GL_COLOR_BUFFER_BIT); //For First Time Implementation Must Screen Was Black


if(x1>100){
y1=count*(ystep+2*gap);
count++;
if(count%2==0)x1=-5;
else x1=0;
flag++;
if (flag == 10) flag = 0;
} // if // //One Row Is Set


if(y1>300){ //repeat wall
y1=0;
x1=0;
count=0;
glClear(GL_COLOR_BUFFER_BIT);
} //if
glutPostRedisplay();
glutTimerFunc(50,TimerFunction,2);
} // end TimerFunction
void main()
{
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("Mostafa Wall");
glutInitWindowSize (640, 480);
glutDisplayFunc(display);
glutTimerFunc(60, TimerFunction,1);
myinit();
glutMainLoop();
}

Admin
17th September 2008, 05:48 PM
خب این برنامه برنامه ی گوی هایی است كه به شكلی به دور گوی دیگه ای می چرخند ..!


// Atom.c
// OpenGL SuperBible, Chapter 5
// Demonstrates OpenGL coordinate transformation
// Program by Richard S. Wright Jr.
#include "stdafx.h"
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include <math.h>




// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
// Angle of revolution around the nucleus
static float fElect1 = 0.0f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Reset the modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Translate the whole scene out and into view
// This is the initial viewing transformation
glTranslatef(0.0f, 0.0f, -100.0f);

// Green Nucleus
glColor3ub(0, 255, 0);
glutSolidSphere(10.0f, 15, 15);

// Yellow Electron1
glColor3ub(0,0,255);

// First Electron Orbit //////////////////////////////////// Abi ///////////////////
// Save viewing transformation
glPushMatrix();

// Rotate by angle of revolution
glRotatef(fElect1, 1.0f, 0.0f, 0.0f);

// Translate out from origin to orbit distance
glTranslatef(90.0f, 30.0f, 0.0f);

// Draw the electron
glutSolidSphere(6.0f, 15, 15);


// Restore the viewing transformation
glPopMatrix();

glColor3ub(255,255,255);

// Second Electron Orbit //////////// sefid //////////////////////////////////
glPushMatrix();
glRotatef(0.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(30.0f, 90.0f, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();

// Second Electron Orbit //////////// narengi //////////////////////////////////
glColor3ub(255,128,0);
glPushMatrix();
glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 1.0f, 0.0f, 0.0f);
glTranslatef(30.0f, 0.0f - 90, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();

// Second Electron Orbit //////////// narengi //////////////////////////////////
glColor3ub(255,128,0);
glPushMatrix();
glRotatef(0.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 1.0f, 0.0f, 0.0f);
glTranslatef(0.0f - 30, 0.0f - 90, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();


// Second Electron Orbit //////////// narengi y 1//////////////////////////////////
glColor3ub(255,128,0);
glPushMatrix();
glRotatef(0.0f, 0.0f, 1.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(0.0f - 90, 0.0f - 30, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();


// Second Electron Orbit //////////// narengi y 1//////////////////////////////////
glColor3ub(255,128,0);
glPushMatrix();
glRotatef(180.0f, 0.0f, 1.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(0.0f - 90, 0.0f + 30, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();



glColor3ub(255,0,0); //////////////////////////////// ghermez /////////////////////

glPushMatrix();
glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 1.0f, 0.0f, 0.0f);
glTranslatef(0.0f - 90, 30.0f, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();


glColor3ub(255,255,0); // Second Electron Orbit //////////// zard //////////////////////////////////
glPushMatrix();
glRotatef(180.0f, 0.0f, 1.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(30.0f, 0.0f - 90, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();



// Increment the angle of revolution
fElect1 += 10.0f;
if(fElect1 > 360.0f)
fElect1 = 0.0f;

// Show the image
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}

void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100, TimerFunc, 1);
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);


// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, nRange*h/w, -nRange*h/w, -nRange*2.0f, nRange*2.0f);
else
glOrtho (-nRange*w/h, nRange*w/h, nRange, -nRange, -nRange*2.0f, nRange*2.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("OpenGL Atom");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
glutTimerFunc(500, TimerFunc, 1);
SetupRC();
glutMainLoop();

return 0;
}

تصویر خروجی برنامه به همراه فایل اجرایی به عنوان فایل پیوست قرار دارد.
موفق باشید

Admin
17th September 2008, 05:53 PM
نمايش ساعت سيستم بصورت آنالوگ و ديجيتال
اين برنامه در محيط سي ++ و با پسوند cpp هست.





//Programmed By : Himanshu Mishra
//Email ID : himanshu_mishra007@yahoo.co.in
/*Other Programmes: 1) SNAKEG
2) PIANO
*/
#include<graphics.h>
#include<math.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
const float PI=3.141;
class needle
{
int size,color,x,y,end_x,end_y;
double theta;
public:
void draw(float,float);
void init(int a,int b,int c,int d)
{x=a;y=b;size=c;color=d;}
};
void needle::draw(float a,float b)
{
theta=(a*b-90)*(PI/180);
setcolor(0);
line(x,y,end_x,end_y);
setcolor(color);
end_x=x+cos(theta)*size;
end_y=y+sin(theta)*size;
line(x,y,end_x,end_y);
}
void main()
{
int d=DETECT,m;
initgraph(&d,&m,"c:\\tc\\bgi");
// setbkcolor(0);
int size=90,a;
float theta;
char tim[12][3]={"3","4","5","6","7","8","9","10","11","12","1","2"};
for(int i=0,j=0;i<360;i+=6)
{
theta=PI/180*i;
a=3;
if(i%5==0)
{
a=12;
outtextxy(320+cos(theta)*(size-a)-textwidth(tim[j])/2,240+sin(theta)*(size-a)-textheight(tim[j])/2,tim[j]);
j++;
a=8;
}
line(320+cos(theta)*(size-a),240+sin(theta)*(size-a),320+cos(theta)*size,240+sin(theta)*size);
}
circle(320,240,size+2);
circle(320,240,size+8);
setfillstyle(1,LIGHTBLUE);
floodfill(320,240+size+3,getcolor());
// setfillstyle(1,6);
// floodfill(0,0,getcolor());
outtext("Press any key to exit......");
needle second,minute,hour,milli;
second.init(320,240,60,BLUE);
minute.init(320,240,70,RED);
hour.init(320,240,40,LIGHTGRAY);
milli.init(320,240,65,6);
int sec,min,hr,hun,last_hun;
static char d_hr[3],d_min[3],d_sec[3],d_hun[3],time[20];
int d_x=275,d_y=120;
struct time t;
while(!kbhit())
{
gettime(&t);
hun=t.ti_hund;
sec=t.ti_sec;
min=t.ti_min;
hr=t.ti_hour;
if(hun!=last_hun)
{
//STARTING ANALOG CLOCK
setcolor(getbkcolor());
outtextxy(d_x,d_y,time);
setlinestyle(0,0,1);
milli.draw(hun,360/100);
second.draw(sec*100+hun,0.06);
setlinestyle(0,0,3);
minute.draw(min*60+sec,0.1);
hour.draw(hr*60+min,0.5);
//ENDING ANALOG CLOCK
//STARTING DIGITAL WATCH
itoa(hr,d_hr,10);
itoa(min,d_min,10);
itoa(sec,d_sec,10);
itoa(hun,d_hun,10);
time[0]=d_hr[0];
time[1]=d_hr[1];
time[2]=':';
time[3]=d_min[0];
time[4]=d_min[1];
time[5]=':';
time[6]=d_sec[0];
time[7]=d_sec[1];
time[8]='.';
time[9]=d_hun[0];
time[10]=d_hun[1];
for(int i=0;i<11;i++)
if(time[i]=='\0'){time[i]=time[i-1];time[i-1]='0';}
time[11]='\0';
setcolor(random(15));
outtextxy(d_x,d_y,time);
//ENDING DIGITAL WATCH
}
last_hun=hun;
}
closegraph();
}

مشخصات نويسنده ي برنامه در متن برنامه آورده شده

Admin
17th September 2008, 05:53 PM
مسابقه ماشين سواري

ابتدا نام بازيكن رو وارد كرده و اينتر مي زنيد سپس وارد برنامه مي شويد...

با استفاده از كليدهاي مكان نماي راست و چپ مي توانيد ماشين را حركت دهيد...

در قسمت سمت راست صفحه نام و امتياز اولين بازيكن از ابتدايي كه بازي را برا اولين بار در سيستم خود اجرا كرديد تا كنون، را نمايش مي دهد نام و امتياز برنده در فايلي به نامhscore.txt در درايو سي ذخيره ميشود...


//**************************************
// Name: Car Race
// Description:It have no complexities, very simple to understand, and it shows that you can make impressive program by using simple beginner coding.
// By: CppKid
//
//
// Inputs:None
//
// Returns:None
//
//Assumes:Just set the path for bgi directory.
//
//Side Effects:None
//This code is copyrighted and has limited warranties.
//Please see http://www.planet-source-code.com/xq...s/ShowCode.htm
//for details.
//**************************************


#include<graphics.h>
#include<fstream.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<dos.h>
#define b setfillstyle(1,1)
#define n setfillstyle(1,0)
#define r setfillstyle
int x=270,cha=10,sp=6;
struct hs

{
char name[30];
int ad;
};
ifstream pt;
void burn()

{
setcolor(14);
circle(x-20,451,4);
circle(x-18,451,4);
circle(x-16,451,5);
circle(x-14,451,6);
circle(x-12,451,6);
circle(x-10,451,5);
circle(x-8,451,6);
circle(x-38,451,4);
circle(x-36,451,5);
circle(x-34,451,5);
circle(x-22,451,5);
circle(x-24,451,5);//Burn
circle(x-26,451,4);
circle(x-28,451,4);
circle(x-30,451,6);
circle(x-32,451,6);
setcolor(4);
circle(x-19,450,6);
circle(x-17,450,5);
circle(x-15,450,5);
circle(x-13,450,6);
circle(x-11,450,6);
circle(x-9,450,5);
circle(x-37,450,4);
circle(x-35,450,5);
circle(x-33,450,6);
circle(x-31,450,6);//Burn
circle(x-21,450,5);
circle(x-23,450,5);
circle(x-25,450,4);
circle(x-27,450,4);
circle(x-29,450,4);
setcolor(14);
circle(x-20,461,4);
circle(x-18,461,4);
circle(x-16,461,5);
circle(x-14,461,6);
circle(x-12,461,6);
circle(x-10,461,5);
circle(x-8,461,6);
circle(x-38,461,4);
circle(x-36,461,5);
circle(x-34,461,5);
circle(x-22,461,5);
circle(x-24,461,5);
circle(x-26,461,4);
circle(x-28,461,4);
circle(x-30,461,6);
circle(x-32,461,6);
setcolor(4);
circle(x-19,460,6);
circle(x-17,460,5);
circle(x-15,460,5);
circle(x-13,460,6);
circle(x-11,460,6); //Burn
circle(x-9,460,5);
circle(x-37,460,4);
circle(x-35,460,5);
circle(x-33,460,6);
circle(x-31,460,6);
circle(x-21,460,5);
circle(x-23,460,5);
circle(x-25,460,4);
circle(x-27,460,4);
circle(x-29,460,4);
}
ofstream ptr;
void main(void)

{
clrscr();
hs rea,wri;
cout<<" Enter name = ";
cin.getline(wri.name,30);
int as=0;
int DRIVER= DETECT,MODE;
MODE=2;
DRIVER=9;
initgraph(&DRIVER, &MODE,"c:\\tc\\bgi");
pt.open("c:\\hscore.txt",ios::in);
if(pt)
pt.read((signed char *)(&rea),sizeof(hs));
if(!pt)

{
rea.name[0]=0;
rea.ad=0;
}
pt.close();
ptr.open("c:\\hscore.txt",ios::out);

{
setcolor(8);
line(300,190,200,500);
line(400,190,500,500);
line(302,190,202,500);
line(402,190,502,500);
setcolor(7); //road
line(298,190,198,500);
line(300,190,200,500);
line(402,190,502,500);
line(404,190,504,500);
setcolor(10);
line(292,190,192,500);
line(294,190,194,500);
line(408,190,508,500);
line(410,190,510,500);
line(282,190,182,500);
line(284,190,184,500);
line(286,190,186,500);
line(288,190,188,500); //green road
line(414,190,514,500);
line(416,190,516,500);
line(420,190,520,500);
line(422,190,522,500);
r(1,9);
bar(0,0,650,190);
setcolor(14);
circle(100,50,1);
circle(100,50,2);
circle(100,50,3);
circle(100,50,4);
circle(100,50,5);
circle(100,50,6);
circle(100,50,7);
circle(100,50,8);
circle(100,50,9);
circle(100,50,10); //sun
circle(100,50,11);
circle(100,50,12);
circle(100,50,13);
circle(100,50,14);
circle(100,50,15);
circle(100,50,16);
circle(100,50,17);
circle(100,50,18);
int x=270;
b;
bar(x,457,x-50,468);
r(1,4);
bar(x-30,457,x-50,465);
bar(x,457,x-20,465);
r(8,6);//Car
bar(x-40,459,x-10,463);
r(8,14);
bar(x-40,463,x-10,464);
setcolor(0);
circle(x-5,460,3);
circle(x-5,460,2); //Cylencer
circle(x-5,460,1);
r(1,8);
bar(x-2,465,x-8,472);
bar(x-48,465,x-42,472);
setcolor(2);
line(x-2,457,x-8,447); //Car tyre & roof
line(x-50,457,x-42,447);
line(x-42,447,x-8,447);
r(1,14);
pieslice(100,50,300,50,18);
pieslice(100,50,0,99,18);
pieslice(100,50,-20,624,18);
}
char a;
int o,l,m,c,p,t,q,w;
o=270;
l=200;
m=80;
c=315;
p=200;
q=205;
t=310;
w=350;
int ene=21;
float sd=0;
gotoxy(2,19);
cout<<"Name = "<<wri.name<<"\n Score = ";
setcolor(9);
settextstyle(5,0,2);
outtextxy(20,415,"Energy");
setcolor(6);
rectangle(19,461,123,449);
rectangle(20,460,122,450);
settextstyle(7,0,2);
outtextxy(440,190,"HIGHEST SCORE ");
gotoxy(58,16);
cout<<"Name = "<<rea.name;
gotoxy(58,17);
cout<<"Score = "<<rea.ad;
setcolor(14);
rectangle(520,430,620,440);
setfillstyle(1,9);
bar(521,431,559,439);
outtextxy(521,400,"Speed");
for(int i=0;sd<=4500;i++)

{
if(a=='e')

{
wri.ad=as;
if (rea.ad>wri.ad)
ptr.write((signed char *)(&rea),sizeof(hs));
else
ptr.write((signed char *)(&wri),sizeof(hs));
ptr.close();
burn();
closegraph();
exit(1);
sd=4500;
}
if (a=='a')

{
setfillstyle(1,0);
bar(521,431,619,439);
setfillstyle(1,13);
bar(521,431,539,439);
sp=5;
}
if (a=='s')

{
setfillstyle(1,0);
bar(521,431,619,439);
setfillstyle(1,9);
bar(521,431,559,439);
sp=6;
}
if (a=='d')

{
sp=7;
setfillstyle(1,0);
bar(521,431,619,439);
setfillstyle(1,11);
bar(521,431,579,439);
}
if (a=='f')

{
setfillstyle(1,0);
bar(521,431,619,439);
setfillstyle(1,10);
bar(521,431,599,439);
sp=8;
}
if (a=='g')

{
setfillstyle(1,0);
bar(521,431,619,439);
setfillstyle(1,4);
bar(521,431,619,439);
sp=9;
}
while(!kbhit())

{
delay(22);
sd++;
gotoxy(9,20);
cout<<as;
gotoxy(2,16);
setcolor(1);
setfillstyle(1,0);
rectangle(1,184,637,188);
rectangle(2,183,638,189);
bar(3,185,sd/7,187);
l=l+18; //while
m=m-1;
p=p+sp;
q=q+sp-2;
r(1,15);
bar(347,l,353,l+40);
r(1,8);
circle(t,p,8);
setcolor(0);
circle(t,p-sp,8);
if(p>455)//Khadday
if(t>x-50)
if(t<x)

{
cha--;
ene=ene+10;
setcolor(9);
setfillstyle(1,14);
rectangle(19,461,123,449);//Energy
rectangle(20,460,122,450);
bar(21,459,ene,451);
if(cha<1)

{
setcolor(4);
settextstyle(7,0,6);
outtextxy(140,100,"GAME OVER");
getch();
//************************************************** *************************
wri.ad=as;
if (rea.ad>wri.ad)
ptr.write((signed char *)(&rea),sizeof(hs));
else
ptr.write((signed char *)(&wri),sizeof(hs));
ptr.close();
burn();
getch();
closegraph();
exit(1);
}
}
if(q>455&&q<470)
if(w>x-50)
if(w<x)

{
//cout<<"\a";
delay(20);
as=as+1;
}
n;
bar(347,l-18,353,l);
//Bars
b;
bar(x-50,457,x,468);
r(1,4);
bar(x,457,x-20,465);
bar(x-50,457,x-30,465);
r(8,6); //Car
bar(x-40,459,x-10,463);
r(8,14);
bar(x-40,463,x-10,464);
setcolor(0);
circle(x-5,460,3);
circle(x-5,460,2); //Cylencer
circle(x-5,460,1);
r(1,8);
bar(x-2,465,x-8,472);
bar(x-48,465,x-42,472);
setcolor(2);
line(x-2,457,x-8,447); //Car tyre & roof
line(x-50,457,x-42,447);
line(x-42,447,x-8,447);
putpixel(c,m,10);
putpixel(c+1,m,10);
putpixel(c+2,m,10);
putpixel(c+3,m+1,10);
putpixel(c+4,m+1,10);
putpixel(c+5,m+1,10);
putpixel(c+6,m,10);
putpixel(c+7,m,10);
putpixel(c+8,m,10);
putpixel(c,m+1,9);
putpixel(c+1,m+1,9);
putpixel(c+2,m+1,9);
putpixel(c+3,m+2,9);
putpixel(c+4,m+2,9);
putpixel(c+5,m+2,9);
putpixel(c+6,m+1,9);
putpixel(c+7,m+1,9);
putpixel(c+8,m+1,9);
setcolor(14);
r(1,14);
pieslice(100,50,300,50,18);
pieslice(100,50,0,99,18);
pieslice(100,50,-20,624,18);
r(1,8);
circle(t,p,8);
setcolor(0);
circle(t,p-sp,8);
setcolor(4); //Khadday
circle(w,q,8);
setcolor(0);
circle(w,q-sp+2,8);
if(l>480)

{
l=200; //Return bars
}
if(p>488)

{
p=200;
t=random(100);
t=t+310;
}
if(q>650)

{
q=205;
w=random(100);
w=w+310;
}
if(m<-1)

{
m=random(150);
c=random(350);
}
}

{
a=getch();
if(a=='K'|x>420)

{
setcolor(8);
line(300,190,200,500);
line(400,190,500,500);//Road
line(302,190,202,500);
line(402,190,502,500);
x=x-6;
o=o-6;
l=l+10;
m=m-1;
r(1,15);
bar(347,l,353,l+40);
n;//Bars
bar(347,l-18,353,l);
b;
bar(x,457,x-50,468);
r(1,4);
bar(x-30,457,x-50,465);
bar(x,457,x-20,465);
r(8,6);//Car
bar(x-40,459,x-10,463);
r(8,14);
bar(x-40,463,x-10,464);
setcolor(0);
circle(x-5,460,3);
circle(x-5,460,2); //Cylencer
circle(x-5,460,1);
putpixel(c,m,10);
putpixel(c+1,m,10);
putpixel(c+2,m,10);
putpixel(c+3,m+1,10);
putpixel(c+4,m+1,10);
putpixel(c+5,m+1,10);
putpixel(c+6,m,10);
putpixel(c+7,m,10);
putpixel(c+8,m,10);
putpixel(c,m+1,9);
putpixel(c+1,m+1,9);
putpixel(c+2,m+1,9);
putpixel(c+3,m+2,9);
putpixel(c+4,m+2,9);
putpixel(c+5,m+2,9);
putpixel(c+6,m+1,9);
putpixel(c+7,m+1,9);
putpixel(c+8,m+1,9);
r(1,8);
bar(x-2,465,x-8,472);
bar(x-48,465,x-42,472);
setcolor(2);
line(x-2,457,x-8,447); //Car tyre & roof
line(x-50,457,x-42,447);
line(x-42,447,x-8,447);
n;
bar(o+6,457,o,470);
bar(x+4,465,x-2,478);
bar(x-42,465,x-36,478);
setcolor(0); //No Car
line(x+4,457,x-2,447);
line(x-44,457,x-36,447);
line(x-8,447,x-2,447);
}
else if(a=='M'|x<320)

{
setcolor(8);
line(300,190,200,500);
line(400,190,500,500);
line(302,190,202,500);//Road
line(402,190,502,500);
x=x+6;
o=o+6;
l=l+10;
c=c+1;
r(1,15);
bar(347,l,353,l+40);
n; //Bars
bar(347,l-18,353,l);
b;
bar(x-50,457,x,468);
r(1,4);
bar(x,457,x-20,465);
bar(x-50,457,x-30,465);
r(8,6); //Car
bar(x-40,459,x-10,463);
r(8,14);
bar(x-40,463,x-10,464);
setcolor(0);
circle(x-5,460,3);
circle(x-5,460,2); //Cylencer
circle(x-5,460,1);
putpixel(c,m,10);
putpixel(c+1,m,10);
putpixel(c+2,m,10);
putpixel(c+3,m+1,10);
putpixel(c+4,m+1,10);
putpixel(c+5,m+1,10);
putpixel(c+6,m,10);
putpixel(c+7,m,10);
putpixel(c+8,m,10);
putpixel(c-1,m,9);
putpixel(c+2,m+1,9);
putpixel(c+5,m,9);
setcolor(2);
line(x-2,457,x-8,447);
line(x-50,457,x-42,447);//Car Tyres
line(x-42,447,x-8,447);
r(1,8);
bar(x-2,465,x-8,472);
bar(x-50,465,x-42,472);
n;
bar(o-56,457,o-50,478);
bar(x-8,465,x-14,478);
bar(x-50,465,x-48,478);
setcolor(0);//No car
line(x-8,457,x-14,447);
line(x-56,457,x-48,447);
line(x-42,447,x-48,447);
}
if(l>480)

{
l=200;//Return bars
}
if(m<-1)

{
m=80;
c=315;
}
}
}
wri.ad=as;
if (rea.ad>wri.ad)
ptr.write((signed char *)(&rea),sizeof(hs));
else
ptr.write((signed char *)(&wri),sizeof(hs));
ptr.close();
}



مشخصات نويسنده ي برنامه در متن برنامه آورده شده

Admin
17th September 2008, 06:47 PM
خب دوستان از این به بعد سورس كد ها به همراه تصویری از برنامه و همچنین فایل اجرایی اون در انتهای برنامه فكر كنم كافی باشه.

نكته: توجه داشته باشید كه برنامه ها رفته ، رفته گرافیكی تر و حرفه ای تر خواهد شد. http://www.daneshju.ir/forum/images/smilies/2007/icon_arrow.gif

نكته 2: توجه كنید كه Include های برنامه را باید با این سه کد زیر حتمآ از این به بعد جایگزین کنید تا برنامه ی شما در محیط برنامه نویسی Visual c اجرا شود.


#include "stdafx.h"
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>


// Block.c
// OpenGL SuperBible, Chapter 1
// Demonstrates an assortment of basic 3D concepts
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>


// Keep track of effects step
int nStep = 0;


// Lighting data
GLfloat lightAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat lightDiffuse[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat lightSpecular[] = { 0.9f, 0.9f, 0.9f };
GLfloat materialColor[] = { 0.8f, 0.0f, 0.0f };
GLfloat lightpos[] = { -80.0f, 120.0f, 100.0f, 0.0f };
GLfloat ground[3][3] = { { 0.0f, -25.0f, 0.0f },
{ 10.0f, -25.0f, 0.0f },
{ 10.0f, -25.0f, -10.0f } };

GLuint textures[4];


// Reduces a normal vector specified as a set of three coordinates,
// to a unit normal vector of length one.
void ReduceToUnit(float vector[3])
{
float length;

// Calculate the length of the vector
length = (float)sqrt((vector[0]*vector[0]) +
(vector[1]*vector[1]) +
(vector[2]*vector[2]));

// Keep the program from blowing up by providing an exceptable
// value for vectors that may calculated too close to zero.
if(length == 0.0f)
length = 1.0f;

// Dividing each element by the length will result in a
// unit normal vector.
vector[0] /= length;
vector[1] /= length;
vector[2] /= length;
}


// Points p1, p2, & p3 specified in counter clock-wise order
void calcNormal(float v[3][3], float out[3])
{
float v1[3],v2[3];
static const int x = 0;
static const int y = 1;
static const int z = 2;

// Calculate two vectors from the three points
v1[x] = v[0][x] - v[1][x];
v1[y] = v[0][y] - v[1][y];
v1[z] = v[0][z] - v[1][z];

v2[x] = v[1][x] - v[2][x];
v2[y] = v[1][y] - v[2][y];
v2[z] = v[1][z] - v[2][z];

// Take the cross product of the two vectors to get
// the normal vector which will be stored in out
out[x] = v1[y]*v2[z] - v1[z]*v2[y];
out[y] = v1[z]*v2[x] - v1[x]*v2[z];
out[z] = v1[x]*v2[y] - v1[y]*v2[x];

// Normalize the vector (shorten length to one)
ReduceToUnit(out);
}


// Creates a shadow projection matrix out of the plane equation
// coefficients and the position of the light. The return value is stored
// in destMat[][]
void MakeShadowMatrix(GLfloat points[3][3], GLfloat lightPos[4], GLfloat destMat[4][4])
{
GLfloat planeCoeff[4];
GLfloat dot;

// Find the plane equation coefficients
// Find the first three coefficients the same way we
// find a normal.
calcNormal(points,planeCoeff);

// Find the last coefficient by back substitutions
planeCoeff[3] = - (
(planeCoeff[0]*points[2][0]) + (planeCoeff[1]*points[2][1]) +
(planeCoeff[2]*points[2][2]));


// Dot product of plane and light position
dot = planeCoeff[0] * lightPos[0] +
planeCoeff[1] * lightPos[1] +
planeCoeff[2] * lightPos[2] +
planeCoeff[3] * lightPos[3];

// Now do the projection
// First column
destMat[0][0] = dot - lightPos[0] * planeCoeff[0];
destMat[1][0] = 0.0f - lightPos[0] * planeCoeff[1];
destMat[2][0] = 0.0f - lightPos[0] * planeCoeff[2];
destMat[3][0] = 0.0f - lightPos[0] * planeCoeff[3];

// Second column
destMat[0][1] = 0.0f - lightPos[1] * planeCoeff[0];
destMat[1][1] = dot - lightPos[1] * planeCoeff[1];
destMat[2][1] = 0.0f - lightPos[1] * planeCoeff[2];
destMat[3][1] = 0.0f - lightPos[1] * planeCoeff[3];

// Third Column
destMat[0][2] = 0.0f - lightPos[2] * planeCoeff[0];
destMat[1][2] = 0.0f - lightPos[2] * planeCoeff[1];
destMat[2][2] = dot - lightPos[2] * planeCoeff[2];
destMat[3][2] = 0.0f - lightPos[2] * planeCoeff[3];

// Fourth Column
destMat[0][3] = 0.0f - lightPos[3] * planeCoeff[0];
destMat[1][3] = 0.0f - lightPos[3] * planeCoeff[1];
destMat[2][3] = 0.0f - lightPos[3] * planeCoeff[2];
destMat[3][3] = dot - lightPos[3] * planeCoeff[3];
}



// Called to draw scene
void RenderScene(void)
{
GLfloat cubeXform[4][4];

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);

glPushMatrix();


// Draw plane that the cube rests on
glDisable(GL_LIGHTING);
if(nStep == 5)
{
glColor3ub(255,255,255);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-100.0f, -25.3f, -100.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-100.0f, -25.3f, 100.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(100.0f, -25.3f, 100.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(100.0f, -25.3f, -100.0f);
glEnd();
}
else
{
glColor3f(0.0f, 0.0f, 0.90f); // Blue
glBegin(GL_QUADS);
glVertex3f(-100.0f, -25.3f, -100.0f);
glVertex3f(-100.0f, -25.3f, 100.0f);
glVertex3f(100.0f, -25.3f, 100.0f);
glVertex3f(100.0f, -25.3f, -100.0f);
glEnd();
}


// Set drawing color to Red
glColor3f(1.0f, 0.0f, 0.0f);

// Enable, disable lighting
if(nStep > 2)
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_COLOR_MATERIAL);

glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glMaterialfv(GL_FRONT, GL_SPECULAR,lightSpecular);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialColor);
glMateriali(GL_FRONT, GL_SHININESS,128);
}

// Move the cube slightly forward and to the left
glTranslatef(-10.0f, 0.0f, 10.0f);

switch(nStep)
{
// Just draw the wire framed cube
case 0:
glutWireCube(50.0f);
break;

// Same wire cube with hidden line removal simulated
case 1:
// Front Face (before rotation)
glBegin(GL_LINES);
glVertex3f(25.0f,25.0f,25.0f);
glVertex3f(25.0f,-25.0f,25.0f);

glVertex3f(25.0f,-25.0f,25.0f);
glVertex3f(-25.0f,-25.0f,25.0f);

glVertex3f(-25.0f,-25.0f,25.0f);
glVertex3f(-25.0f,25.0f,25.0f);

glVertex3f(-25.0f,25.0f,25.0f);
glVertex3f(25.0f,25.0f,25.0f);
glEnd();

// Top of cube
glBegin(GL_LINES);
// Front Face
glVertex3f(25.0f,25.0f,25.0f);
glVertex3f(25.0f,25.0f,-25.0f);

glVertex3f(25.0f,25.0f,-25.0f);
glVertex3f(-25.0f,25.0f,-25.0f);

glVertex3f(-25.0f,25.0f,-25.0f);
glVertex3f(-25.0f,25.0f,25.0f);

glVertex3f(-25.0f,25.0f,25.0f);
glVertex3f(25.0f,25.0f,25.0f);
glEnd();

// Last two segments for effect
glBegin(GL_LINES);
glVertex3f(25.0f,25.0f,-25.0f);
glVertex3f(25.0f,-25.0f,-25.0f);

glVertex3f(25.0f,-25.0f,-25.0f);
glVertex3f(25.0f,-25.0f,25.0f);
glEnd();

break;

// Uniform colored surface, looks 2D and goofey
case 2:
glutSolidCube(50.0f);
break;

case 3:
glutSolidCube(50.0f);
break;

// Draw a shadow with some lighting
case 4:
glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *) cubeXform);
glutSolidCube(50.0f);
glPopMatrix();

// Disable lighting, we'll just draw the shadow as black
glDisable(GL_LIGHTING);

glPushMatrix();

MakeShadowMatrix(ground, lightpos, cubeXform);
glMultMatrixf((GLfloat *)cubeXform);

glTranslatef(-10.0f, 0.0f, 10.0f);

// Set drawing color to Black
glColor3f(0.0f, 0.0f, 0.0f);

glutSolidCube(50.0f);
break;

case 5:
glColor3ub(255,255,255);
glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *) cubeXform);

// Front Face (before rotation)
glBindTexture(GL_TEXTURE_2D, textures[1]);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(25.0f,25.0f,25.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(25.0f,-25.0f,25.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-25.0f,-25.0f,25.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-25.0f,25.0f,25.0f);
glEnd();

// Top of cube
glBindTexture(GL_TEXTURE_2D, textures[2]);
glBegin(GL_QUADS);
// Front Face
glTexCoord2f(0.0f, 0.0f);
glVertex3f(25.0f,25.0f,25.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(25.0f,25.0f,-25.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-25.0f,25.0f,-25.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-25.0f,25.0f,25.0f);
glEnd();

// Last two segments for effect
glBindTexture(GL_TEXTURE_2D, textures[3]);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(25.0f,25.0f,-25.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(25.0f,-25.0f,-25.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(25.0f,-25.0f,25.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(25.0f,25.0f,25.0f);
glEnd();


glPopMatrix();

// Disable lighting, we'll just draw the shadow as black
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);

glPushMatrix();

MakeShadowMatrix(ground, lightpos, cubeXform);
glMultMatrixf((GLfloat *)cubeXform);

glTranslatef(-10.0f, 0.0f, 10.0f);

// Set drawing color to Black
glColor3f(0.0f, 0.0f, 0.0f);
glutSolidCube(50.0f);
break;

}

glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLbyte *pBytes;
GLint nWidth, nHeight, nComponents;
GLenum format;

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_MODULATE);
glGenTextures(4, textures);

// Load the texture objects
pBytes = gltLoadTGA("floor.tga", &nWidth, &nHeight, &nComponents, &format);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,nComponents,nWidth, nHeight, 0,
format, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

pBytes = gltLoadTGA("Block4.tga", &nWidth, &nHeight, &nComponents, &format);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,nComponents,nWidth, nHeight, 0,
format, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

pBytes = gltLoadTGA("block5.tga", &nWidth, &nHeight, &nComponents, &format);
glBindTexture(GL_TEXTURE_2D, textures[2]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,nComponents,nWidth, nHeight, 0,
format, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

pBytes = gltLoadTGA("block6.tga", &nWidth, &nHeight, &nComponents, &format);
glBindTexture(GL_TEXTURE_2D, textures[3]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,nComponents,nWidth, nHeight, 0,
format, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);
}

void KeyPressFunc(unsigned char key, int x, int y)
{
if(key == 32)
{
nStep++;

if(nStep > 5)
nStep = 0;
}

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
// Calculate new clipping volume
GLfloat windowWidth;
GLfloat windowHeight;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

// Keep the square square
if (w <= h)
{
windowHeight = 100.0f*(GLfloat)h/(GLfloat)w;
windowWidth = 100.0f;
}
else
{
windowWidth = 100.0f*(GLfloat)w/(GLfloat)h;
windowHeight = 100.0f;
}

// Set the viewport to be the entire window
glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
glOrtho(-100.0f, windowWidth, -100.0f, windowHeight, -200.0f, 200.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glLightfv(GL_LIGHT0,GL_POSITION, lightpos);

glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
glRotatef(330.0f, 0.0f, 1.0f, 0.0f);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("3D Effects Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutDisplayFunc(RenderScene);

SetupRC();

glutMainLoop();
glDeleteTextures(4,textures);
return 0;
}

Admin
17th September 2008, 06:48 PM
برنامه Bounce



// Bounce.c
// Demonstrates a simple animated rectangle program with GLUT
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff



// Initial square position and size
GLfloat x = 0.0f;
GLfloat y = 0.0f;
GLfloat rsize = 25;

// Step size in x and y directions
// (number of pixels to move each time)
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;

// Keep track of windows changing width and height
GLfloat windowWidth;
GLfloat windowHeight;

///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Set current drawing color to red
// R G B
glColor3f(1.0f, 0.0f, 0.0f);

// Draw a filled rectangle with current color
glRectf(x, y, x + rsize, y - rsize);

// Flush drawing commands and swap
glutSwapBuffers();
}

///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Reverse direction when you reach left or right edge
if(x > windowWidth-rsize || x < -windowWidth)
xstep = -xstep;

// Reverse direction when you reach top or bottom edge
if(y > windowHeight || y < -windowHeight + rsize)
ystep = -ystep;

// Actually move the square
x += xstep;
y += ystep;

// Check bounds. This is in case the window is made
// smaller while the rectangle is bouncing and the
// rectangle suddenly finds itself outside the new
// clipping volume
if(x > (windowWidth-rsize + xstep))
x = windowWidth-rsize-1;
else if(x < -(windowWidth + xstep))
x = -windowWidth -1;

if(y > (windowHeight + ystep))
y = windowHeight-1;
else if(y < -(windowHeight - rsize + ystep))
y = -windowHeight + rsize - 1;



// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}


///////////////////////////////////////////////////////////
// Setup the rendering state
void SetupRC(void)
{
// Set clear color to blue
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
}


///////////////////////////////////////////////////////////
// Called by GLUT library when the window has chanaged size
void ChangeSize(int w, int h)
{
GLfloat aspectRatio;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <= h)
{
windowWidth = 100;
windowHeight = 100 / aspectRatio;
glOrtho (-100.0, 100.0, -windowHeight, windowHeight, 1.0, -1.0);
}
else
{
windowWidth = 100 * aspectRatio;
windowHeight = 100;
glOrtho (-windowWidth, windowWidth, -100.0, 100.0, 1.0, -1.0);
}

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////////////
// Main program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800,600);
glutCreateWindow("Bounce");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutTimerFunc(33, TimerFunction, 1);

SetupRC();

glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:50 PM
برنامه ای كه از خط ساخته شده و با كیبور می چرخد.


// Lines.c
// Demonstrates primative GL_LINES
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLfloat x,y,z,angle; // Storeage for coordinates and angles

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Call only once for all remaining points
glBegin(GL_LINES);

z = 0.0f;
for(angle = 0.0f; angle <= GL_PI; angle += (GL_PI / 20.0f))
{
// Top half of the circle
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);
glVertex3f(x, y, z);

// Bottom half of the circle
x = 50.0f*sin(angle+GL_PI);
y = 50.0f*cos(angle+GL_PI);
glVertex3f(x, y, z);
}

// Done drawing points
glEnd();

// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

///////////////////////////////////////////////////////////
// This function does any needed initialization on the
// rendering context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

///////////////////////////////////////////////////////////
// Respond to arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}

///////////////////////////////////////////////////////////
// Window has changed size, recalculate projection
void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////////////
// Main Program Entry Point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Lines Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:51 PM
// Linesw.c
// OpenGL SuperBible, Chapter 4
// Demonstrates primative GL_LINES with line widths
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLfloat y; // Storeage for varying Y coordinate
GLfloat fSizes[2]; // Line width range metrics
GLfloat fCurrSize; // Save current size


// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Get line size metrics and save the smallest value
glGetFloatv(GL_LINE_WIDTH_RANGE,fSizes);
fCurrSize = fSizes[0];

// Step up Y axis 20 units at a time
for(y = -90.0f; y < 90.0f; y += 20.0f)
{
// Set the line width
glLineWidth(fCurrSize);

// Draw the line
glBegin(GL_LINES);
glVertex2f(-80.0f, y);
glVertex2f(80.0f, y);
glEnd();

// Increase the line width
fCurrSize += 1.0f;
}


// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Line Width Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:52 PM
// Lstipple.c
// OpenGL SuperBible, Chapter 4
// Demonstrates line stippling
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLfloat y; // Storeage for varying Y coordinate
GLint factor = 3; // Stippling factor
GLushort pattern = 0x5555; // Stipple pattern


// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);



// Step up Y axis 20 units at a time
for(y = -90.0f; y < 90.0f; y += 20.0f)
{
// Reset the repeat factor and pattern
glLineStipple(factor,pattern);

// Draw the line
glBegin(GL_LINES);
glVertex2f(-80.0f, y);
glVertex2f(80.0f, y);
glEnd();

factor++;
}


// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);

// Enable Stippling
glEnable(GL_LINE_STIPPLE);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Stippled Line Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:53 PM
// LStrips.c
// OpenGL SuperBible, Chapter 4
// Demonstrates primative GL_LINE_STRIP
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLfloat x,y,z,angle; // Storeage for coordinates and angles

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Call only once for all remaining points
glBegin(GL_LINE_STRIP);

z = -50.0f;
for(angle = 0.0f; angle <= (2.0f*3.1415f)*3.0f; angle += 0.1f)
{
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);

// Specify the point and move the Z value up a little
glVertex3f(x, y, z);
z += 0.5f;
}

// Done drawing points
glEnd();

// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Line Strips Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:57 PM
// Points.c
// OpenGL SuperBible, Chapter 3
// Demonstrates OpenGL Primative GL_POINTS
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLfloat x,y,z,angle; // Storeage for coordinates and angles

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Call only once for all remaining points
glBegin(GL_POINTS);

z = -50.0f;
for(angle = 0.0f; angle <= (2.0f*GL_PI)*3.0f; angle += 0.1f)
{
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);

// Specify the point and move the Z value up a little
glVertex3f(x, y, z);
z += 0.5f;
}

// Done drawing points
glEnd();

// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Points Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 06:58 PM
// Pointsz.c
// OpenGL SuperBible, Chapter 4
// Demonstrates OpenGL Primative GL_POINTS with point size
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLfloat x,y,z,angle; // Storeage for coordinates and angles
GLfloat sizes[2]; // Store supported point size range
GLfloat step; // Store supported point size increments
GLfloat curSize; // Store current size

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Get supported point size range and step size
glGetFloatv(GL_POINT_SIZE_RANGE,sizes);
glGetFloatv(GL_POINT_SIZE_GRANULARITY,&step);

// Set the initial point size
curSize = sizes[0];

// Set beginning z coordinate
z = -50.0f;

// Loop around in a circle three times
for(angle = 0.0f; angle <= (2.0f*3.1415f)*3.0f; angle += 0.1f)
{
// Calculate x and y values on the circle
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);

// Specify the point size before the primative is specified
glPointSize(curSize);

// Draw the point
glBegin(GL_POINTS);
glVertex3f(x, y, z);
glEnd();

// Bump up the z value and the point size
z += 0.5f;
curSize += step;
}

// Restore matrix state
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Points Size Example");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:00 PM
برنامه ی Plygon Stippeling که تصویری را در داخل تصویر دیگر Stipple می کند.


// PStipple.c
// OpenGL SuperBible, Chapter 3
// Demonstrates OpenGL Polygon Stippling
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

// Bitmap of camp fire
GLubyte fire[128] = { 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xc0,
0x00, 0x00, 0x01, 0xf0,
0x00, 0x00, 0x07, 0xf0,
0x0f, 0x00, 0x1f, 0xe0,
0x1f, 0x80, 0x1f, 0xc0,
0x0f, 0xc0, 0x3f, 0x80,
0x07, 0xe0, 0x7e, 0x00,
0x03, 0xf0, 0xff, 0x80,
0x03, 0xf5, 0xff, 0xe0,
0x07, 0xfd, 0xff, 0xf8,
0x1f, 0xfc, 0xff, 0xe8,
0xff, 0xe3, 0xbf, 0x70,
0xde, 0x80, 0xb7, 0x00,
0x71, 0x10, 0x4a, 0x80,
0x03, 0x10, 0x4e, 0x40,
0x02, 0x88, 0x8c, 0x20,
0x05, 0x05, 0x04, 0x40,
0x02, 0x82, 0x14, 0x40,
0x02, 0x40, 0x10, 0x80,
0x02, 0x64, 0x1a, 0x80,
0x00, 0x92, 0x29, 0x00,
0x00, 0xb0, 0x48, 0x00,
0x00, 0xc8, 0x90, 0x00,
0x00, 0x85, 0x10, 0x00,
0x00, 0x03, 0x00, 0x00,
0x00, 0x00, 0x10, 0x00 };


// Called to draw scene
void RenderScene(void)
{
// Clear the window
glClear(GL_COLOR_BUFFER_BIT);

// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Begin the stop sign shape,
// use a standard polygon for simplicity
glBegin(GL_POLYGON);
glVertex2f(-20.0f, 50.0f);
glVertex2f(20.0f, 50.0f);
glVertex2f(50.0f, 20.0f);
glVertex2f(50.0f, -20.0f);
glVertex2f(20.0f, -50.0f);
glVertex2f(-20.0f, -50.0f);
glVertex2f(-50.0f, -20.0f);
glVertex2f(-50.0f, 20.0f);
glEnd();

// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to red
glColor3f(1.0f, 0.0f, 0.0f);

// Enable polygon stippling
glEnable(GL_POLYGON_STIPPLE);

// Specify a specific stipple pattern
glPolygonStipple(fire);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Polygon Stippling");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:01 PM
برنامه ی رسم تصویر پیوست به صورت انیمیشن.


// Scissor.c
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>

///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
static GLdouble dRadius = 0.1;
static GLdouble dAngle = 0.0;

// Clear blue window
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);

if(dAngle == 0.0)
glClear(GL_COLOR_BUFFER_BIT);

glBegin(GL_POINTS);
glVertex2d(dRadius * cos(dAngle), dRadius * sin(dAngle));
glEnd();

dRadius *= 1.01;
dAngle += 0.1;

if(dAngle > 30.0)
{
dRadius = 0.1;
dAngle = 0.0;
}

glFlush();
}

///////////////////////////////////////////////////////////
// Trigger a repaint
void Timer(int value)
{
glutTimerFunc(50,Timer, 0);
glutPostRedisplay();
}


///////////////////////////////////////////////////////////
// Set viewport and projection
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);


// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set 2D Coordinate system
gluOrtho2D(-4.0, 4.0, -3.0, 3.0);

// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


///////////////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL Single Buffered");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(50,Timer, 0);
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:03 PM
برنامه ستاره که با کیبور هم حرکت می کند.


// Star.c
// OpenGL SuperBible, Chapter 4
// Demonstrates OpenGL Primative GL_POINTS with point size
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

// Flags for effects
#define MODE_SOLID 0
#define MODE_LINE 1
#define MODE_POINT 2

int iMode = MODE_SOLID;
GLboolean bEdgeFlag = TRUE;

///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
{
switch(value)
{
case 1:
iMode = MODE_SOLID;
break;

case 2:
iMode = MODE_LINE;
break;

case 3:
iMode = MODE_POINT;
break;

case 4:
bEdgeFlag = TRUE;
break;

case 5:
default:
bEdgeFlag = FALSE;
break;
}

glutPostRedisplay();
}


// Called to draw scene
void RenderScene(void)
{
// Clear the window
glClear(GL_COLOR_BUFFER_BIT);


// Draw back side as a polygon only, if flag is set
if(iMode == MODE_LINE)
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);

if(iMode == MODE_POINT)
glPolygonMode(GL_FRONT_AND_BACK,GL_POINT);

if(iMode == MODE_SOLID)
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);


// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);


// Begin the triangles
glBegin(GL_TRIANGLES);

glEdgeFlag(bEdgeFlag);
glVertex2f(-20.0f, 0.0f);
glEdgeFlag(TRUE);
glVertex2f(20.0f, 0.0f);
glVertex2f(0.0f, 40.0f);

glVertex2f(-20.0f,0.0f);
glVertex2f(-60.0f,-20.0f);
glEdgeFlag(bEdgeFlag);
glVertex2f(-20.0f,-40.0f);
glEdgeFlag(TRUE);

glVertex2f(-20.0f,-40.0f);
glVertex2f(0.0f, -80.0f);
glEdgeFlag(bEdgeFlag);
glVertex2f(20.0f, -40.0f);
glEdgeFlag(TRUE);

glVertex2f(20.0f, -40.0f);
glVertex2f(60.0f, -20.0f);
glEdgeFlag(bEdgeFlag);
glVertex2f(20.0f, 0.0f);
glEdgeFlag(TRUE);

// Center square as two triangles
glEdgeFlag(bEdgeFlag);
glVertex2f(-20.0f, 0.0f);
glVertex2f(-20.0f,-40.0f);
glVertex2f(20.0f, 0.0f);

glVertex2f(-20.0f,-40.0f);
glVertex2f(20.0f, -40.0f);
glVertex2f(20.0f, 0.0f);
glEdgeFlag(TRUE);

// Done drawing Triangles
glEnd();

// Restore transformations
glPopMatrix();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
int nModeMenu;
int nEdgeMenu;
int nMainMenu;

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Solid and Outlined Star");

// Create the Menu
nModeMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Solid",1);
glutAddMenuEntry("Outline",2);
glutAddMenuEntry("Points",3);

nEdgeMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("On",4);
glutAddMenuEntry("Off",5);

nMainMenu = glutCreateMenu(ProcessMenu);
glutAddSubMenu("Mode", nModeMenu);
glutAddSubMenu("Edges", nEdgeMenu);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:12 PM
برنامه ای كه مركب از دو برنامه Bounce ( پست 19 ) و برنامه ی پست 27 است.


// Stencil.c
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff

// Initial square position and size
GLfloat x = 0.0f;
GLfloat y = 0.0f;
GLfloat rsize = 25;

// Step size in x and y directions
// (number of pixels to move each time)
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;

// Keep track of windows changing width and height
GLfloat windowWidth;
GLfloat windowHeight;

///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLdouble dRadius = 0.1; // Initial radius of spiral
GLdouble dAngle; // Looping variable

// Clear blue window
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);

// Use 0 for clear stencil, enable stencil test
glClearStencil(0.0f);
glEnable(GL_STENCIL_TEST);

// Clear color and stencil buffer
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

// All drawing commands fail the stencil test, and are not
// drawn, but increment the value in the stencil buffer.
glStencilFunc(GL_NEVER, 0x0, 0x0);
glStencilOp(GL_INCR, GL_INCR, GL_INCR);

// Spiral pattern will create stencil pattern
// Draw the spiral pattern with white lines. We
// make the lines white to demonstrate that the
// stencil function prevents them from being drawn
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINE_STRIP);
for(dAngle = 0; dAngle < 400.0; dAngle += 0.1)
{
glVertex2d(dRadius * cos(dAngle), dRadius * sin(dAngle));
dRadius *= 1.002;
}
glEnd();

// Now, allow drawing, except where the stencil pattern is 0x1
// and do not make any further changes to the stencil buffer
glStencilFunc(GL_NOTEQUAL, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

// Now draw red bouncing square
// (x and y) are modified by a timer function
glColor3f(1.0f, 0.0f, 0.0f);
glRectf(x, y, x + rsize, y - rsize);

// All done, do the buffer swap
glutSwapBuffers();
}

///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Reverse direction when you reach left or right edge
if(x > windowWidth-rsize || x < -windowWidth)
xstep = -xstep;

// Reverse direction when you reach top or bottom edge
if(y > windowHeight || y < -windowHeight + rsize)
ystep = -ystep;


// Check bounds. This is in case the window is made
// smaller while the rectangle is bouncing and the
// rectangle suddenly finds itself outside the new
// clipping volume
if(x > windowWidth-rsize)
x = windowWidth-rsize-1;

if(y > windowHeight)
y = windowHeight-1;

// Actually move the square
x += xstep;
y += ystep;

// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}


///////////////////////////////////////////////////////////
// Called by GLUT library when the window has chanaged size
void ChangeSize(int w, int h)
{
GLfloat aspectRatio;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <= h)
{
windowWidth = 100;
windowHeight = 100 / aspectRatio;
glOrtho (-100.0, 100.0, -windowHeight, windowHeight, 1.0, -1.0);
}
else
{
windowWidth = 100 * aspectRatio;
windowHeight = 100;
glOrtho (-windowWidth, windowWidth, -100.0, 100.0, 1.0, -1.0);
}

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


///////////////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL Stencil Test");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(33, TimerFunction, 1);
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:37 PM
// Triangle.c
// OpenGL SuperBible, Chapter 4
// Demonstrates OpenGL Triangle Fans, backface culling, and depth testing
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

// Flags for effects
// Flags for effects
int iCull = 0;
int iOutline = 0;
int iDepth = 0;

///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
{
switch(value)
{
case 1:
iDepth = !iDepth;
break;

case 2:
iCull = !iCull;
break;

case 3:
iOutline = !iOutline;
default:
break;
}

glutPostRedisplay();
}


// Called to draw scene
void RenderScene(void)
{
GLfloat x,y,angle; // Storage for coordinates and angles
int iPivot = 1; // Used to flag alternating colors

// Clear the window and the depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Turn culling on if flag is set
if(iCull)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);

// Enable depth testing if flag is set
if(iDepth)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);

// Draw back side as a polygon only, if flag is set
if(iOutline)
glPolygonMode(GL_BACK,GL_LINE);
else
glPolygonMode(GL_BACK,GL_FILL);


// Save matrix state and do the rotation
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);


// Begin a triangle fan
glBegin(GL_TRIANGLE_FAN);

// Pinnacle of cone is shared vertex for fan, moved up Z axis
// to produce a cone instead of a circle
glVertex3f(0.0f, 0.0f, 75.0f);

// Loop around in a circle and specify even points along the circle
// as the vertices of the triangle fan
for(angle = 0.0f; angle < (2.0f*GL_PI); angle += (GL_PI/8.0f))
{
// Calculate x and y position of the next vertex
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);

// Alternate color between red and green
if((iPivot %2) == 0)
glColor3f(0.0f, 1.0f, 0.0f);
else
glColor3f(1.0f, 0.0f, 0.0f);

// Increment pivot to change color next time
iPivot++;

// Specify the next vertex for the triangle fan
glVertex2f(x, y);
}

// Done drawing fan for cone
glEnd();


// Begin a new triangle fan to cover the bottom
glBegin(GL_TRIANGLE_FAN);

// Center of fan is at the origin
glVertex2f(0.0f, 0.0f);
for(angle = 0.0f; angle < (2.0f*GL_PI); angle += (GL_PI/8.0f))
{
// Calculate x and y position of the next vertex
x = 50.0f*sin(angle);
y = 50.0f*cos(angle);

// Alternate color between red and green
if((iPivot %2) == 0)
glColor3f(0.0f, 1.0f, 0.0f);
else
glColor3f(1.0f, 0.0f, 0.0f);

// Increment pivot to change color next time
iPivot++;

// Specify the next vertex for the triangle fan
glVertex2f(x, y);
}

// Done drawing the fan that covers the bottom
glEnd();

// Restore transformations
glPopMatrix();


// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);

// Set color shading model to flat
glShadeModel(GL_FLAT);

// Clock wise wound polygons are front facing, this is reversed
// because we are using triangle fans
glFrontFace(GL_CW);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Triangle Culling Example");

// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle depth test",1);
glutAddMenuEntry("Toggle cull backface",2);
glutAddMenuEntry("Toggle outline back",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:38 PM
خب تا اینجای کار امیدوارم مفید واقع بوده باشه ..!
از این مرحله به بعد کم کم وارد برنامه های پیچیده تر و قشنگ تر می شیم.
موفق باشید ;)

Admin
17th September 2008, 07:40 PM
برنامه ی اتم ... كه چرخش مولكولها به صورت انیمیشن رو به دور هسته نمایش می ده.


// Atom.c
// OpenGL SuperBible
// Demonstrates OpenGL coordinate transformation
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff#include <math.h>

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
// Angle of revolution around the nucleus
static GLfloat fElect1 = 0.0f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Reset the modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Translate the whole scene out and into view
// This is the initial viewing transformation
glTranslatef(0.0f, 0.0f, -100.0f);

// Red Nucleus
glColor3ub(255, 0, 0);
glutSolidSphere(10.0f, 15, 15);

// Yellow Electrons
glColor3ub(255,255,0);

// First Electron Orbit
// Save viewing transformation
glPushMatrix();

// Rotate by angle of revolution
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);

// Translate out from origin to orbit distance
glTranslatef(90.0f, 0.0f, 0.0f);

// Draw the electron
glutSolidSphere(6.0f, 15, 15);


// Restore the viewing transformation
glPopMatrix();

// Second Electron Orbit
glPushMatrix();
glRotatef(45.0f, 0.0f, 0.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(-70.0f, 0.0f, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();


// Third Electron Orbit
glPushMatrix();
glRotatef(360.0f-45.0f,0.0f, 0.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(0.0f, 0.0f, 60.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();


// Increment the angle of revolution
fElect1 += 10.0f;
if(fElect1 > 360.0f)
fElect1 = 0.0f;

// Show the image
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}

void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100, TimerFunc, 1);
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 100.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);


// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, nRange*h/w, -nRange*h/w, -nRange*2.0f, nRange*2.0f);
else
glOrtho (-nRange*w/h, nRange*w/h, nRange, -nRange, -nRange*2.0f, nRange*2.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Atom");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
glutTimerFunc(500, TimerFunc, 1);
SetupRC();
glutMainLoop();

return 0;
}

این برنامه به صورت انیمیشن می باشد.

Admin
17th September 2008, 07:41 PM
برنامه ی برای محیط دو بعدی ( Ortho )


// Ortho.c
// OpenGL SuperBible
// Richard S. Wright Jr.
// Demonstrates Orthographic Projection

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Change viewing volume and viewport. Called when window is resized
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat nRange = 120.0f;
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange*2.0f, nRange*2.0f);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange*2.0f, nRange*2.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}



// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the lighting for
// the scene.
void SetupRC()
{
// Light values and coordinates
GLfloat whiteLight[] = { 0.45f, 0.45f, 0.45f, 1.0f };
GLfloat sourceLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat lightPos[] = { -50.f, 25.0f, 250.0f, 0.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_AMBIENT,sourceLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black blue background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

// Respond to arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

xRot = (GLfloat)((const int)xRot % 360);
yRot = (GLfloat)((const int)yRot % 360);

// Refresh the Window
glutPostRedisplay();
}


// Called to draw scene
void RenderScene(void)
{
float fZ,bZ;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

fZ = 100.0f;
bZ = -100.0f;

// Save the matrix state and do the rotations
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Set material color, Red
glColor3f(1.0f, 0.0f, 0.0f);

// Front Face ///////////////////////////////////
glBegin(GL_QUADS);
// Pointing straight out Z
glNormal3f(0.0f, 0.0f, 1.0f);

// Left Panel
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(-50.0f, -50.0f, fZ);
glVertex3f(-35.0f, -50.0f, fZ);
glVertex3f(-35.0f,50.0f,fZ);

// Right Panel
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(35.0f, 50.0f, fZ);
glVertex3f(35.0f, -50.0f, fZ);
glVertex3f(50.0f,-50.0f,fZ);

// Top Panel
glVertex3f(-35.0f, 50.0f, fZ);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, 50.0f,fZ);

// Bottom Panel
glVertex3f(-35.0f, -35.0f, fZ);
glVertex3f(-35.0f, -50.0f, fZ);
glVertex3f(35.0f, -50.0f, fZ);
glVertex3f(35.0f, -35.0f,fZ);

// Top length section ////////////////////////////
// Normal points up Y axis
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(50.0f, 50.0f, bZ);
glVertex3f(-50.0f,50.0f,bZ);

// Bottom section
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(-50.0f, -50.0f, fZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(50.0f, -50.0f, bZ);
glVertex3f(50.0f, -50.0f, fZ);

// Left section
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(50.0f, -50.0f, fZ);
glVertex3f(50.0f, -50.0f, bZ);
glVertex3f(50.0f, 50.0f, bZ);

// Right Section
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(-50.0f, 50.0f, bZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(-50.0f, -50.0f, fZ);
glEnd();

glFrontFace(GL_CW); // clock-wise polygons face out

glBegin(GL_QUADS);
// Back section
// Pointing straight out Z
glNormal3f(0.0f, 0.0f, -1.0f);

// Left Panel
glVertex3f(-50.0f, 50.0f, bZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(-35.0f, -50.0f, bZ);
glVertex3f(-35.0f,50.0f,bZ);

// Right Panel
glVertex3f(50.0f, 50.0f, bZ);
glVertex3f(35.0f, 50.0f, bZ);
glVertex3f(35.0f, -50.0f, bZ);
glVertex3f(50.0f,-50.0f,bZ);

// Top Panel
glVertex3f(-35.0f, 50.0f, bZ);
glVertex3f(-35.0f, 35.0f, bZ);
glVertex3f(35.0f, 35.0f, bZ);
glVertex3f(35.0f, 50.0f,bZ);

// Bottom Panel
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(-35.0f, -50.0f, bZ);
glVertex3f(35.0f, -50.0f, bZ);
glVertex3f(35.0f, -35.0f,bZ);

// Insides /////////////////////////////
glColor3f(0.75f, 0.75f, 0.75f);

// Normal points up Y axis
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, bZ);
glVertex3f(-35.0f,35.0f,bZ);

// Bottom section
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-35.0f, -35.0f, fZ);
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(35.0f, -35.0f, bZ);
glVertex3f(35.0f, -35.0f, fZ);

// Left section
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(-35.0f, 35.0f, bZ);
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(-35.0f, -35.0f, fZ);

// Right Section
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, -35.0f, fZ);
glVertex3f(35.0f, -35.0f, bZ);
glVertex3f(35.0f, 35.0f, bZ);
glEnd();

glFrontFace(GL_CCW); // Counter clock-wise polygons face out

// Restore the matrix state
glPopMatrix();

// Buffer swap
glutSwapBuffers();
}



int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Orthographic Projection");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:42 PM
برنامه ی قبلی در محیط سه بعدی ( Perspective )


// Perspect.c
// Demonstrates Perspective Projection
// OpenGL SuperBible
// Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Change viewing volume and viewport. Called when window is resized
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

fAspect = (GLfloat)w/(GLfloat)h;

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Produce the perspective projection
gluPerspective(60.0f, fAspect, 1.0, 400.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the lighting for
// the scene.
void SetupRC()
{
// Light values and coordinates
GLfloat whiteLight[] = { 0.45f, 0.45f, 0.45f, 1.0f };
GLfloat sourceLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat lightPos[] = { -50.f, 25.0f, 250.0f, 0.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_AMBIENT,sourceLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black blue background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

// Respond to arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

xRot = (GLfloat)((const int)xRot % 360);
yRot = (GLfloat)((const int)yRot % 360);

// Refresh the Window
glutPostRedisplay();
}


// Called to draw scene
void RenderScene(void)
{
float fZ,bZ;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

fZ = 100.0f;
bZ = -100.0f;

// Save the matrix state and do the rotations
glPushMatrix();
glTranslatef(0.0f, 0.0f, -300.0f);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Set material color, Red
glColor3f(1.0f, 0.0f, 0.0f);

// Front Face ///////////////////////////////////
glBegin(GL_QUADS);
// Pointing straight out Z
glNormal3f(0.0f, 0.0f, 1.0f);

// Left Panel
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(-50.0f, -50.0f, fZ);
glVertex3f(-35.0f, -50.0f, fZ);
glVertex3f(-35.0f,50.0f,fZ);

// Right Panel
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(35.0f, 50.0f, fZ);
glVertex3f(35.0f, -50.0f, fZ);
glVertex3f(50.0f,-50.0f,fZ);

// Top Panel
glVertex3f(-35.0f, 50.0f, fZ);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, 50.0f,fZ);

// Bottom Panel
glVertex3f(-35.0f, -35.0f, fZ);
glVertex3f(-35.0f, -50.0f, fZ);
glVertex3f(35.0f, -50.0f, fZ);
glVertex3f(35.0f, -35.0f,fZ);

// Top length section ////////////////////////////
// Normal points up Y axis
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(50.0f, 50.0f, bZ);
glVertex3f(-50.0f,50.0f,bZ);

// Bottom section
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(-50.0f, -50.0f, fZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(50.0f, -50.0f, bZ);
glVertex3f(50.0f, -50.0f, fZ);

// Left section
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(50.0f, 50.0f, fZ);
glVertex3f(50.0f, -50.0f, fZ);
glVertex3f(50.0f, -50.0f, bZ);
glVertex3f(50.0f, 50.0f, bZ);

// Right Section
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-50.0f, 50.0f, fZ);
glVertex3f(-50.0f, 50.0f, bZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(-50.0f, -50.0f, fZ);
glEnd();

glFrontFace(GL_CW); // clock-wise polygons face out

glBegin(GL_QUADS);
// Back section
// Pointing straight out Z
glNormal3f(0.0f, 0.0f, -1.0f);

// Left Panel
glVertex3f(-50.0f, 50.0f, bZ);
glVertex3f(-50.0f, -50.0f, bZ);
glVertex3f(-35.0f, -50.0f, bZ);
glVertex3f(-35.0f,50.0f,bZ);

// Right Panel
glVertex3f(50.0f, 50.0f, bZ);
glVertex3f(35.0f, 50.0f, bZ);
glVertex3f(35.0f, -50.0f, bZ);
glVertex3f(50.0f,-50.0f,bZ);

// Top Panel
glVertex3f(-35.0f, 50.0f, bZ);
glVertex3f(-35.0f, 35.0f, bZ);
glVertex3f(35.0f, 35.0f, bZ);
glVertex3f(35.0f, 50.0f,bZ);

// Bottom Panel
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(-35.0f, -50.0f, bZ);
glVertex3f(35.0f, -50.0f, bZ);
glVertex3f(35.0f, -35.0f,bZ);

// Insides /////////////////////////////
glColor3f(0.75f, 0.75f, 0.75f);

// Normal points up Y axis
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, 35.0f, bZ);
glVertex3f(-35.0f,35.0f,bZ);

// Bottom section
glNormal3f(0.0f, 1.0f, 0.0f);
glVertex3f(-35.0f, -35.0f, fZ);
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(35.0f, -35.0f, bZ);
glVertex3f(35.0f, -35.0f, fZ);

// Left section
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(-35.0f, 35.0f, fZ);
glVertex3f(-35.0f, 35.0f, bZ);
glVertex3f(-35.0f, -35.0f, bZ);
glVertex3f(-35.0f, -35.0f, fZ);

// Right Section
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(35.0f, 35.0f, fZ);
glVertex3f(35.0f, -35.0f, fZ);
glVertex3f(35.0f, -35.0f, bZ);
glVertex3f(35.0f, 35.0f, bZ);
glEnd();

glFrontFace(GL_CCW); // Counter clock-wise polygons face out

// Restore the matrix state
glPopMatrix();

// Buffer swap
glutSwapBuffers();
}



int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Perspective Projection");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:43 PM
برنامه ای كه گردش زمین و ماه رو به دور خورشید نمایش داده با جلوه های نور پردازی و سه بعدی


// Solar.c
// OpenGL SuperBible
// Demonstrates OpenGL nested coordinate transformations
// and perspective
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>


// Lighting values
GLfloat whiteLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat sourceLight[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };


// Called to draw scene
void RenderScene(void)
{
// Earth and Moon angle of revolution
static float fMoonRot = 0.0f;
static float fEarthRot = 0.0f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the matrix state and do the rotations
glMatrixMode(GL_MODELVIEW);
glPushMatrix();

// Translate the whole scene out and into view
glTranslatef(0.0f, 0.0f, -300.0f);

// Set material color, Red
// Sun
glDisable(GL_LIGHTING);
glColor3ub(255, 255, 0);
glutSolidSphere(15.0f, 30, 17);
glEnable(GL_LIGHTING);

// Move the light after we draw the sun!
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);

// Rotate coordinate system
glRotatef(fEarthRot, 0.0f, 1.0f, 0.0f);

// Draw the Earth
glColor3ub(0,0,255);
glTranslatef(105.0f,0.0f,0.0f);
glutSolidSphere(15.0f, 30, 17);


// Rotate from Earth based coordinates and draw Moon
glColor3ub(200,200,200);
glRotatef(fMoonRot,0.0f, 1.0f, 0.0f);
glTranslatef(30.0f, 0.0f, 0.0f);
fMoonRot+= 15.0f;
if(fMoonRot > 360.0f)
fMoonRot = 0.0f;

glutSolidSphere(6.0f, 30, 17);

// Restore the matrix state
glPopMatrix(); // Modelview matrix


// Step earth orbit 5 degrees
fEarthRot += 5.0f;
if(fEarthRot > 360.0f)
fEarthRot = 0.0f;

// Show the image
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values and coordinates
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black blue background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}


void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100, TimerFunc, 1);
}

void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Calculate aspect ratio of the window
fAspect = (GLfloat)w/(GLfloat)h;

// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// field of view of 45 degrees, near and far planes 1.0 and 425
gluPerspective(45.0f, fAspect, 1.0, 425.0);

// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Earth/Moon/Sun System");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(250, TimerFunc, 1);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:44 PM
برنامه ی SphereWorld كه محیطی از كره های مختلف رو به نمایش گذاشته.


// SphereWorld.c
// OpenGL SuperBible
// Demonstrates an immersive 3D environment using actors
// and a camera.
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>


#define NUM_SPHERES 50
GLTFrame spheres[NUM_SPHERES];
GLTFrame frameCamera;

//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
int iSphere;

// Bluish background
glClearColor(0.0f, 0.0f, .50f, 1.0f );

// Draw everything as wire frame
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

gltInitFrame(&frameCamera); // Initialize the camera

// Randomly place the sphere inhabitants
for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
{
gltInitFrame(&spheres[iSphere]); // Initialize the frame

// Pick a random location between -20 and 20 at .1 increments
spheres[iSphere].vLocation[0] = (float)((rand() % 400) - 200) * 0.1f;
spheres[iSphere].vLocation[1] = 0.0f;
spheres[iSphere].vLocation[2] = (float)((rand() % 400) - 200) * 0.1f;
}
}


///////////////////////////////////////////////////////////
// Draw a gridded ground
void DrawGround(void)
{
GLfloat fExtent = 20.0f;
GLfloat fStep = 1.0f;
GLfloat y = -0.4f;
GLint iLine;

glBegin(GL_LINES);
for(iLine = -fExtent; iLine <= fExtent; iLine += fStep)
{
glVertex3f(iLine, y, fExtent); // Draw Z lines
glVertex3f(iLine, y, -fExtent);

glVertex3f(fExtent, y, iLine);
glVertex3f(-fExtent, y, iLine);
}

glEnd();
}


// Called to draw scene
void RenderScene(void)
{
int i;
static GLfloat yRot = 0.0f; // Rotation angle for animation
yRot += 0.5f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();
gltApplyCameraTransform(&frameCamera);

// Draw the ground
DrawGround();

// Draw the randomly located spheres
for(i = 0; i < NUM_SPHERES; i++)
{
glPushMatrix();
gltApplyActorTransform(&spheres[i]);
glutSolidSphere(0.1f, 13, 26);
glPopMatrix();
}

glPushMatrix();
glTranslatef(0.0f, 0.0f, -2.5f);

glPushMatrix();
glRotatef(-yRot * 2.0f, 0.0f, 1.0f, 0.0f);
glTranslatef(1.0f, 0.0f, 0.0f);
glutSolidSphere(0.1f, 13, 26);
glPopMatrix();

glRotatef(yRot, 0.0f, 1.0f, 0.0f);
gltDrawTorus(0.35, 0.15, 40, 20);
glPopMatrix();
glPopMatrix();

// Do the buffer Swap
glutSwapBuffers();
}



// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
gltMoveFrameForward(&frameCamera, 0.1f);

if(key == GLUT_KEY_DOWN)
gltMoveFrameForward(&frameCamera, -0.1f);

if(key == GLUT_KEY_LEFT)
gltRotateFrameLocalY(&frameCamera, 0.1);

if(key == GLUT_KEY_RIGHT)
gltRotateFrameLocalY(&frameCamera, -0.1);

// Refresh the Window
glutPostRedisplay();
}


///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(3,TimerFunction, 1);
}

void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL SphereWorld Demo");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);

SetupRC();
glutTimerFunc(33, TimerFunction, 1);

glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:46 PM
برنامه ی چرخش حلقه


// Transform.c
// OpenGL SuperBible
// Demonstrates manual transformations
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>


// Draw a torus (doughnut), using the current 1D texture for light shading
void DrawTorus(GLTMatrix mTransform)
{
GLfloat majorRadius = 0.35f;
GLfloat minorRadius = 0.15f;
GLint numMajor = 40;
GLint numMinor = 20;
GLTVector3 objectVertex; // Vertex in object/eye space
GLTVector3 transformedVertex; // New Transformed vertex
double majorStep = 2.0f*GLT_PI / numMajor;
double minorStep = 2.0f*GLT_PI / numMinor;
int i, j;

for (i=0; i<numMajor; ++i)
{
double a0 = i * majorStep;
double a1 = a0 + majorStep;
GLfloat x0 = (GLfloat) cos(a0);
GLfloat y0 = (GLfloat) sin(a0);
GLfloat x1 = (GLfloat) cos(a1);
GLfloat y1 = (GLfloat) sin(a1);

glBegin(GL_TRIANGLE_STRIP);
for (j=0; j<=numMinor; ++j)
{
double b = j * minorStep;
GLfloat c = (GLfloat) cos(b);
GLfloat r = minorRadius * c + majorRadius;
GLfloat z = minorRadius * (GLfloat) sin(b);

// First point
objectVertex[0] = x0*r;
objectVertex[1] = y0*r;
objectVertex[2] = z;
gltTransformPoint(objectVertex, mTransform, transformedVertex);
glVertex3fv(transformedVertex);

// Second point
objectVertex[0] = x1*r;
objectVertex[1] = y1*r;
objectVertex[2] = z;
gltTransformPoint(objectVertex, mTransform, transformedVertex);
glVertex3fv(transformedVertex);
}
glEnd();
}
}


// Called to draw scene
void RenderScene(void)
{
GLTMatrix transformationMatrix; // Storeage for rotation matrix
static GLfloat yRot = 0.0f; // Rotation angle for animation
yRot += 0.5f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Build a rotation matrix
gltRotationMatrix(gltDegToRad(yRot), 0.0f, 1.0f, 0.0f, transformationMatrix);
transformationMatrix[12] = 0.0f;
transformationMatrix[13] = 0.0f;
transformationMatrix[14] = -2.5f;

DrawTorus(transformationMatrix);

// Do the buffer Swap
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Bluish background
glClearColor(0.0f, 0.0f, .50f, 1.0f );

// Draw everything as wire frame
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}

///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}



void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Manual Transformations Demo");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);

SetupRC();
glutTimerFunc(33, TimerFunction, 1);

glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:47 PM
برنامه ی CUBE كه در این برنامه می توان با كیبورد CUBE را در موقعیتهای مختلف دید.


// ccube.c
// OpenGL SuperBible
// Demonstrates primative RGB Color Cube
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();

glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);


// Draw six quads
glBegin(GL_QUADS);
// Front Face
// White
glColor3ub((GLubyte) 255, (GLubyte)255, (GLubyte)255);
glVertex3f(50.0f,50.0f,50.0f);

// Yellow
glColor3ub((GLubyte) 255, (GLubyte)255, (GLubyte)0);
glVertex3f(50.0f,-50.0f,50.0f);

// Red
glColor3ub((GLubyte) 255, (GLubyte)0, (GLubyte)0);
glVertex3f(-50.0f,-50.0f,50.0f);

// Magenta
glColor3ub((GLubyte) 255, (GLubyte)0, (GLubyte)255);
glVertex3f(-50.0f,50.0f,50.0f);


// Back Face
// Cyan
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f(50.0f,50.0f,-50.0f);

// Green
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(50.0f,-50.0f,-50.0f);

// Black
glColor3f(0.0f, 0.0f, 0.0f);
glVertex3f(-50.0f,-50.0f,-50.0f);

// Blue
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-50.0f,50.0f,-50.0f);

// Top Face
// Cyan
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f(50.0f,50.0f,-50.0f);

// White
glColor3f(1.0f, 1.0f, 1.0f);
glVertex3f(50.0f,50.0f,50.0f);

// Magenta
glColor3f(1.0f, 0.0f, 1.0f);
glVertex3f(-50.0f,50.0f,50.0f);

// Blue
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-50.0f,50.0f,-50.0f);

// Bottom Face
// Green
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(50.0f,-50.0f,-50.0f);

// Yellow
glColor3f(1.0f, 1.0f, 0.0f);
glVertex3f(50.0f,-50.0f,50.0f);

// Red
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-50.0f,-50.0f,50.0f);

// Black
glColor3f(0.0f, 0.0f, 0.0f);
glVertex3f(-50.0f,-50.0f,-50.0f);

// Left face
// White
glColor3f(1.0f, 1.0f, 1.0f);
glVertex3f(50.0f,50.0f,50.0f);

// Cyan
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f(50.0f,50.0f,-50.0f);

// Green
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(50.0f,-50.0f,-50.0f);

// Yellow
glColor3f(1.0f, 1.0f, 0.0f);
glVertex3f(50.0f,-50.0f,50.0f);

// Right face
// Magenta
glColor3f(1.0f, 0.0f, 1.0f);
glVertex3f(-50.0f,50.0f,50.0f);

// Blue
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-50.0f,50.0f,-50.0f);

// Black
glColor3f(0.0f, 0.0f, 0.0f);
glVertex3f(-50.0f,-50.0f,-50.0f);

// Red
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-50.0f,-50.0f,50.0f);
glEnd();

glPopMatrix();

// Show the graphics
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

glEnable(GL_DEPTH_TEST);
glEnable(GL_DITHER);
glShadeModel(GL_SMOOTH);
}

/////////////////////////////////////////////////
// Get Arrow Keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

fAspect = (GLfloat)w / (GLfloat)h;
gluPerspective(35.0f, fAspect, 1.0f, 1000.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -400.0f);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("RGB Cube");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:48 PM
برنامه چرخش اتم ها به دور هسته ... به همراه امكانات زوم و چرخش سریع اتم ها.


// gooy project tamrin 9.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include <math.h>


GLfloat whiteLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat sourceLight[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
float zoom = 0.0;

// Called to draw scene

void ProcessMenu(int value)
{
switch(value)
{
case 1:
zoom +=30;
break;

case 2:
zoom -=30;
break;

default:
break;
}

glutPostRedisplay();
}

void RenderScene(void)
{
GLUquadricObj *pObj;
// Angle of revolution around the nucleus
static float fElect1 = 0.0f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Save the matrix state and do the rotations
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Move object back and do in place rotation
glTranslatef(0.0f, -1.0f, -5.0f ); //********************************************
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);

// Reset the modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Translate the whole scene out and into view
// This is the initial viewing transformation
glTranslatef(0.0f, 0.0f, -100.0f +zoom ); //****************************************
glPushMatrix();

///////////////////////////// Green Nucleus //////////////////////////////////////
glDisable(GL_LIGHTING);
glColor3ub(255, 255, 0);
// glColor3ub(0, 255, 0);
glutSolidSphere(10.0f, 15, 15);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);

// First Electron Orbit //////////////////////////////////// Abi ///////////////////
glColor3ub(0,0,255);
glRotatef(0.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 1.0f, 0.0f, 0.0f);
glTranslatef(0.0f, 30.0f , 0.0f ); //*************************************
glutSolidSphere(6.0f, 15, 15);
// Restore the viewing transformation
glPopMatrix();

// Second Electron Orbit //////////// sefid //////////////////////////////////
glPushMatrix();
glColor3ub(255,255,255);
glRotatef(0.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(30.0f , 0.0f, 0.0f ); //********************************************
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();
//////////////////////////////// ghermez /////////////////////
glPushMatrix();
glColor3ub(255,0,0);
glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
glRotatef(fElect1, 0.0f, 1.0f, 1.0f);
glTranslatef(0.0f , 30.0f , 0.0f ); //***************************************
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();
// Second Electron Orbit //////////// zard //////////////////////////////////
// glPushMatrix();
glColor3ub(255,255,0);
glRotatef(180.0f, 0.0f, 1.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(30.0f , 0.0f , 0.0f ); //************************************
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();
// Increment the angle of revolution
fElect1 += 10.0f;
if(fElect1 > 360.0f)
fElect1 = 0.0f;

// Show the image
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet
glEnable(GL_LIGHTING);

glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 1.0f;

/* if(key == GLUT_KEY_DOWN)
xRot += 1.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 1.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 1.0f;
*/
if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100, TimerFunc, 1);
}


void ChangeSize(int w, int h)
{
GLfloat fAspect;
// GLfloat nRange = 300.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Calculate aspect ratio of the window
fAspect = (GLfloat)w/(GLfloat)h;

// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// field of view of 45 degrees, near and far planes 1.0 and 425
gluPerspective(100.0f, fAspect, 1.0, 425.0);
// Establish clipping volume (left, right, bottom, top, near, far)
/* if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

*/
// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Atom");

//-------------------
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Zoom In",1);
glutAddMenuEntry("Zoom Out",2);
glutAddMenuEntry("Note: Plz Up To Speed Up",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//-------------------
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
glutTimerFunc(500, TimerFunc, 1);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:49 PM
خب برنامه ی هواپیما با نور پردازی Ambient یا نور پردازی غیر متمرکز.


// Ambient.c
// OpenGL SuperBible
// Beginning of OpenGL lighting sample
// Demonstrates Ambient Lighting
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff


// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the matrix state
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Nose Cone /////////////////////////////
// Bright Green
glColor3ub(0, 255, 0);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 0.0f, 60.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(15.0f,0.0f,30.0f);

glVertex3f(15.0f,0.0f,30.0f);
glVertex3f(0.0f, 15.0f, 30.0f);
glVertex3f(0.0f, 0.0f, 60.0f);

glVertex3f(0.0f, 0.0f, 60.0f);
glVertex3f(0.0f, 15.0f, 30.0f);
glVertex3f(-15.0f,0.0f,30.0f);

// Body of the Plane ////////////////////////
// light gray
glColor3ub(192,192,192);
glVertex3f(-15.0f,0.0f,30.0f);
glVertex3f(0.0f, 15.0f, 30.0f);
glVertex3f(0.0f, 0.0f, -56.0f);

glVertex3f(0.0f, 0.0f, -56.0f);
glVertex3f(0.0f, 15.0f, 30.0f);
glVertex3f(15.0f,0.0f,30.0f);

glVertex3f(15.0f,0.0f,30.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(0.0f, 0.0f, -56.0f);


///////////////////////////////////////////////
// Left wing
// Dark gray
glColor3ub(64,64,64);
glVertex3f(0.0f,2.0f,27.0f);
glVertex3f(-60.0f, 2.0f, -8.0f);
glVertex3f(60.0f, 2.0f, -8.0f);

glVertex3f(60.0f, 2.0f, -8.0f);
glVertex3f(0.0f, 7.0f, -8.0f);
glVertex3f(0.0f,2.0f,27.0f);

glVertex3f(60.0f, 2.0f, -8.0f);
glVertex3f(-60.0f, 2.0f, -8.0f);
glVertex3f(0.0f,7.0f,-8.0f);


// Other wing top section
glVertex3f(0.0f,2.0f,27.0f);
glVertex3f(0.0f, 7.0f, -8.0f);
glVertex3f(-60.0f, 2.0f, -8.0f);

// Tail section///////////////////////////////
// Bottom of back fin
glColor3ub(255,255,0);
glVertex3f(-30.0f, -0.50f, -57.0f);
glVertex3f(30.0f, -0.50f, -57.0f);
glVertex3f(0.0f,-0.50f,-40.0f);

// top of left side
glVertex3f(0.0f,-0.5f,-40.0f);
glVertex3f(30.0f, -0.5f, -57.0f);
glVertex3f(0.0f, 4.0f, -57.0f);

// top of right side
glVertex3f(0.0f, 4.0f, -57.0f);
glVertex3f(-30.0f, -0.5f, -57.0f);
glVertex3f(0.0f,-0.5f,-40.0f);

// back of bottom of tail
glVertex3f(30.0f,-0.5f,-57.0f);
glVertex3f(-30.0f, -0.5f, -57.0f);
glVertex3f(0.0f, 4.0f, -57.0f);


// Top of Tail section left
glColor3ub(255,0,0);
glVertex3f(0.0f,0.5f,-40.0f);
glVertex3f(3.0f, 0.5f, -57.0f);
glVertex3f(0.0f, 25.0f, -65.0f);

glVertex3f(0.0f, 25.0f, -65.0f);
glVertex3f(-3.0f, 0.5f, -57.0f);
glVertex3f(0.0f,0.5f,-40.0f);


// Back of horizontal section
glVertex3f(3.0f,0.5f,-57.0f);
glVertex3f(-3.0f, 0.5f, -57.0f);
glVertex3f(0.0f, 25.0f, -65.0f);
glEnd();

glPopMatrix();

// Display the results
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values
// Bright white light
GLfloat ambientLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glEnable(GL_CULL_FACE); // Do not calculate inside of jet
glFrontFace(GL_CCW); // Counter clock-wise polygons face out

// Lighting stuff
glEnable(GL_LIGHTING); // Enable lighting

// Set light model to use ambient light specified by ambientLight
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,ambientLight );

glEnable(GL_COLOR_MATERIAL); // Enable Material color tracking

// Front material ambient and diffuse colors track glColor
glColorMaterial(GL_FRONT,GL_AMBIENT_AND_DIFFUSE);

// Nice light blue
glClearColor(0.0f, 0.0f, 05.f,1.0f);
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat nRange = 80.0f;
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Ambient Light Jet");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:51 PM
برنامه ی جت با نور پردازی DIFFUSE یا نور پردازی نیمه متمركز.


// LitJet.c
// OpenGL SuperBible
// Demonstrates OpenGL Lighting
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/gltools.h" // gltools library

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLTVector3 vNormal; // Storeage for calculated surface normal

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the matrix state and do the rotations
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);


// Nose Cone - Points straight down
// Set material color
glColor3ub(128, 128, 128);
glBegin(GL_TRIANGLES);
glNormal3f(0.0f, -1.0f, 0.0f);
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 60.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(15.0f,0.0f,30.0f);


// Verticies for this panel
{
GLTVector3 vPoints[3] = {{ 15.0f, 0.0f, 30.0f},
{ 0.0f, 15.0f, 30.0f},
{ 0.0f, 0.0f, 60.0f}};

// Calculate the normal for the plane
gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 0.0f, 60.0f },
{ 0.0f, 15.0f, 30.0f },
{ -15.0f, 0.0f, 30.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


// Body of the Plane ////////////////////////
{
GLTVector3 vPoints[3] = {{ -15.0f, 0.0f, 30.0f },
{ 0.0f, 15.0f, 30.0f },
{ 0.0f, 0.0f, -56.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 0.0f, 0.0f, -56.0f },
{ 0.0f, 15.0f, 30.0f },
{ 15.0f,0.0f,30.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(15.0f,0.0f,30.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(0.0f, 0.0f, -56.0f);

///////////////////////////////////////////////
// Left wing
// Large triangle for bottom of wing
{
GLTVector3 vPoints[3] = {{ 0.0f,2.0f,27.0f },
{ -60.0f, 2.0f, -8.0f },
{ 60.0f, 2.0f, -8.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 60.0f, 2.0f, -8.0f},
{0.0f, 7.0f, -8.0f},
{0.0f,2.0f,27.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{60.0f, 2.0f, -8.0f},
{-60.0f, 2.0f, -8.0f},
{0.0f,7.0f,-8.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{0.0f,2.0f,27.0f},
{0.0f, 7.0f, -8.0f},
{-60.0f, 2.0f, -8.0f}};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


// Tail section///////////////////////////////
// Bottom of back fin
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(-30.0f, -0.50f, -57.0f);
glVertex3f(30.0f, -0.50f, -57.0f);
glVertex3f(0.0f,-0.50f,-40.0f);

{
GLTVector3 vPoints[3] = {{ 0.0f,-0.5f,-40.0f },
{30.0f, -0.5f, -57.0f},
{0.0f, 4.0f, -57.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 4.0f, -57.0f },
{ -30.0f, -0.5f, -57.0f },
{ 0.0f,-0.5f,-40.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 30.0f,-0.5f,-57.0f },
{ -30.0f, -0.5f, -57.0f },
{ 0.0f, 4.0f, -57.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 0.0f,0.5f,-40.0f },
{ 3.0f, 0.5f, -57.0f },
{ 0.0f, 25.0f, -65.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 25.0f, -65.0f },
{ -3.0f, 0.5f, -57.0f},
{ 0.0f,0.5f,-40.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 3.0f,0.5f,-57.0f },
{ -3.0f, 0.5f, -57.0f },
{ 0.0f, 25.0f, -65.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


glEnd();

// Restore the matrix state
glPopMatrix();
// Display the results
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values and coordinates
GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Light blue background
glClearColor(0.0f, 0.0f, 1.0f, 1.0f );
}

/////////////////////////////////////////////////////
// Handle arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


//////////////////////////////////////////////////////////
// Reset projection and light position
void ChangeSize(int w, int h)
{
GLfloat fAspect;
GLfloat lightPos[] = { -50.f, 50.0f, 100.0f, 1.0f };

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

fAspect = (GLfloat) w / (GLfloat) h;
gluPerspective(45.0f, fAspect, 1.0f, 225.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glTranslatef(0.0f, 0.0f, -150.0f);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Lighted Jet");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:52 PM
برنامه ی جت با نور متمرکز ..!


// ShinyJet.c
// OpenGL SuperBible
// Demonstrates OpenGL Lighting
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/gltools.h" // gltools library

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Called to draw scene
void RenderScene(void)
{
GLTVector3 vNormal; // Storeage for calculated surface normal

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the matrix state and do the rotations
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);


// Nose Cone - Points straight down
// Set material color
glColor3ub(128, 128, 128);
glBegin(GL_TRIANGLES);
glNormal3f(0.0f, -1.0f, 0.0f);
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 60.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(15.0f,0.0f,30.0f);


// Verticies for this panel
{
GLTVector3 vPoints[3] = {{ 15.0f, 0.0f, 30.0f},
{ 0.0f, 15.0f, 30.0f},
{ 0.0f, 0.0f, 60.0f}};

// Calculate the normal for the plane
gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 0.0f, 60.0f },
{ 0.0f, 15.0f, 30.0f },
{ -15.0f, 0.0f, 30.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


// Body of the Plane ////////////////////////
{
GLTVector3 vPoints[3] = {{ -15.0f, 0.0f, 30.0f },
{ 0.0f, 15.0f, 30.0f },
{ 0.0f, 0.0f, -56.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 0.0f, 0.0f, -56.0f },
{ 0.0f, 15.0f, 30.0f },
{ 15.0f,0.0f,30.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(15.0f,0.0f,30.0f);
glVertex3f(-15.0f, 0.0f, 30.0f);
glVertex3f(0.0f, 0.0f, -56.0f);

///////////////////////////////////////////////
// Left wing
// Large triangle for bottom of wing
{
GLTVector3 vPoints[3] = {{ 0.0f,2.0f,27.0f },
{ -60.0f, 2.0f, -8.0f },
{ 60.0f, 2.0f, -8.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 60.0f, 2.0f, -8.0f},
{0.0f, 7.0f, -8.0f},
{0.0f,2.0f,27.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{60.0f, 2.0f, -8.0f},
{-60.0f, 2.0f, -8.0f},
{0.0f,7.0f,-8.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{0.0f,2.0f,27.0f},
{0.0f, 7.0f, -8.0f},
{-60.0f, 2.0f, -8.0f}};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


// Tail section///////////////////////////////
// Bottom of back fin
glNormal3f(0.0f, -1.0f, 0.0f);
glVertex3f(-30.0f, -0.50f, -57.0f);
glVertex3f(30.0f, -0.50f, -57.0f);
glVertex3f(0.0f,-0.50f,-40.0f);

{
GLTVector3 vPoints[3] = {{ 0.0f,-0.5f,-40.0f },
{30.0f, -0.5f, -57.0f},
{0.0f, 4.0f, -57.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 4.0f, -57.0f },
{ -30.0f, -0.5f, -57.0f },
{ 0.0f,-0.5f,-40.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 30.0f,-0.5f,-57.0f },
{ -30.0f, -0.5f, -57.0f },
{ 0.0f, 4.0f, -57.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 0.0f,0.5f,-40.0f },
{ 3.0f, 0.5f, -57.0f },
{ 0.0f, 25.0f, -65.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}


{
GLTVector3 vPoints[3] = {{ 0.0f, 25.0f, -65.0f },
{ -3.0f, 0.5f, -57.0f},
{ 0.0f,0.5f,-40.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

{
GLTVector3 vPoints[3] = {{ 3.0f,0.5f,-57.0f },
{ -3.0f, 0.5f, -57.0f },
{ 0.0f, 25.0f, -65.0f }};

gltGetNormalVector(vPoints[0], vPoints[1], vPoints[2], vNormal);
glNormal3fv(vNormal);
glVertex3fv(vPoints[0]);
glVertex3fv(vPoints[1]);
glVertex3fv(vPoints[2]);
}

glEnd();

// Restore the matrix state
glPopMatrix();
// Display the results
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values and coordinates
GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat specref[] = { 1.0f, 1.0f, 1.0f, 1.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);
glLightfv(GL_LIGHT0,GL_SPECULAR, specular);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// All materials hereafter have full specular reflectivity
// with a high shine
glMaterialfv(GL_FRONT, GL_SPECULAR, specref);
glMateriali(GL_FRONT, GL_SHININESS, 128);

// Light blue background
glClearColor(0.0f, 0.0f, 1.0f, 1.0f );
}

/////////////////////////////////////////////////////
// Handle arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


//////////////////////////////////////////////////////////
// Reset projection and light position
void ChangeSize(int w, int h)
{
GLfloat fAspect;
GLfloat lightPos[] = { -50.f, 50.0f, 100.0f, 1.0f };

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

fAspect = (GLfloat) w / (GLfloat) h;
gluPerspective(45.0f, fAspect, 1.0f, 225.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glTranslatef(0.0f, 0.0f, -150.0f);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Shiny Jet");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:53 PM
// SphereWorld.c
// OpenGL SuperBible
// Demonstrates an immersive 3D environment using actors
// and a camera. This version adds lights and material properties
// and shadows.
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>

#define NUM_SPHERES 30
GLTFrame spheres[NUM_SPHERES];
GLTFrame frameCamera;

// Light and material Data
GLfloat fLightPos[4] = { -100.0f, 100.0f, 50.0f, 1.0f }; // Point source
GLfloat fNoLight[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat fLowLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat fBrightLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

GLTMatrix mShadowMatrix;



//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
int iSphere;

// Calculate shadow matrix
GLTVector3 vPoints[3] = {{ 0.0f, -0.4f, 0.0f },
{ 10.0f, -0.4f, 0.0f },
{ 5.0f, -0.4f, -5.0f }};

// Grayish background
glClearColor(fLowLight[0], fLowLight[1], fLowLight[2], fLowLight[3]);

// Cull backs of polygons
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);

// Setup light parameters
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fNoLight);
glLightfv(GL_LIGHT0, GL_AMBIENT, fLowLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);



gltMakeShadowMatrix(vPoints, fLightPos, mShadowMatrix);

// Mostly use material tracking
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMateriali(GL_FRONT, GL_SHININESS, 128);

gltInitFrame(&frameCamera); // Initialize the camera

// Randomly place the sphere inhabitants
for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
{
gltInitFrame(&spheres[iSphere]); // Initialize the frame

// Pick a random location between -20 and 20 at .1 increments
spheres[iSphere].vLocation[0] = (float)((rand() % 400) - 200) * 0.1f;
spheres[iSphere].vLocation[1] = 0.0f;
spheres[iSphere].vLocation[2] = (float)((rand() % 400) - 200) * 0.1f;
}
}


///////////////////////////////////////////////////////////
// Draw the ground as a series of triangle strips
void DrawGround(void)
{
GLfloat fExtent = 20.0f;
GLfloat fStep = 1.0f;
GLfloat y = -0.4f;
GLint iStrip, iRun;

for(iStrip = -fExtent; iStrip <= fExtent; iStrip += fStep)
{
glBegin(GL_TRIANGLE_STRIP);
glNormal3f(0.0f, 1.0f, 0.0f); // All Point up

for(iRun = fExtent; iRun >= -fExtent; iRun -= fStep)
{
glVertex3f(iStrip, y, iRun);
glVertex3f(iStrip + fStep, y, iRun);
}
glEnd();
}
}

///////////////////////////////////////////////////////////////////////
// Draw random inhabitants and the rotating torus/sphere duo
void DrawInhabitants(GLint nShadow)
{
static GLfloat yRot = 0.0f; // Rotation angle for animation
GLint i;

if(nShadow == 0)
yRot += 0.5f;
else
glColor3f(0.0f, 0.0f, 0.0f);

// Draw the randomly located spheres
if(nShadow == 0)
glColor3f(0.0f, 1.0f, 0.0f);


for(i = 0; i < NUM_SPHERES; i++)
{
glPushMatrix();
gltApplyActorTransform(&spheres[i]);
glutSolidSphere(0.3f, 17, 9);
glPopMatrix();
}

glPushMatrix();
glTranslatef(0.0f, 0.1f, -2.5f);

if(nShadow == 0)
glColor3f(0.0f, 0.0f, 1.0f);

glPushMatrix();
glRotatef(-yRot * 2.0f, 0.0f, 1.0f, 0.0f);
glTranslatef(1.0f, 0.0f, 0.0f);
glutSolidSphere(0.1f, 17, 9);
glPopMatrix();

if(nShadow == 0)
{
// Torus alone will be specular
glColor3f(1.0f, 0.0f, 0.0f);
glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
}

glRotatef(yRot, 0.0f, 1.0f, 0.0f);
gltDrawTorus(0.35, 0.15, 61, 37);
glMaterialfv(GL_FRONT, GL_SPECULAR, fNoLight);
glPopMatrix();
}


// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();
gltApplyCameraTransform(&frameCamera);

// Position light before any other transformations
glLightfv(GL_LIGHT0, GL_POSITION, fLightPos);

// Draw the ground
glColor3f(0.60f, .40f, .10f);
DrawGround();

// Draw shadows first
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glPushMatrix();
glMultMatrixf(mShadowMatrix);
DrawInhabitants(1);
glPopMatrix();
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);

// Draw inhabitants normally
DrawInhabitants(0);

glPopMatrix();

// Do the buffer Swap
glutSwapBuffers();
glutPostRedisplay();
}



// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
gltMoveFrameForward(&frameCamera, 0.1f);

if(key == GLUT_KEY_DOWN)
gltMoveFrameForward(&frameCamera, -0.1f);

if(key == GLUT_KEY_LEFT)
gltRotateFrameLocalY(&frameCamera, 0.1);

if(key == GLUT_KEY_RIGHT)
gltRotateFrameLocalY(&frameCamera, -0.1);

// Refresh the Window
glutPostRedisplay();
}


///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(3,TimerFunction, 1);
}

void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL SphereWorld Demo + Lights and Shadow");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);

SetupRC();
glutTimerFunc(33, TimerFunction, 1);

glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:54 PM
برنامه ی تغییر مکان نور ..!
همون طور که در تصویر می بینید مکان نور با تغییر مکان چراغ قوه عوض می شه.


// Spot.c
// OpenGL SuperBible
// Demonstrates OpenGL Spotlight
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff


// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

// Light values and coordinates
GLfloat lightPos[] = { 0.0f, 0.0f, 75.0f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f};
GLfloat specref[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat ambientLight[] = { 0.5f, 0.5f, 0.5f, 1.0f};
GLfloat spotDir[] = { 0.0f, 0.0f, -1.0f };

// Flags for effects
#define MODE_FLAT 1
#define MODE_SMOOTH 2
#define MODE_VERYLOW 3
#define MODE_MEDIUM 4
#define MODE_VERYHIGH 5

int iShade = MODE_FLAT;
int iTess = MODE_VERYLOW;

///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
{
switch(value)
{
case 1:
iShade = MODE_FLAT;
break;

case 2:
iShade = MODE_SMOOTH;
break;

case 3:
iTess = MODE_VERYLOW;
break;

case 4:
iTess = MODE_MEDIUM;
break;

case 5:
default:
iTess = MODE_VERYHIGH;
break;
}

glutPostRedisplay();
}



// Called to draw scene
void RenderScene(void)
{
if(iShade == MODE_FLAT)
glShadeModel(GL_FLAT);
else // iShade = MODE_SMOOTH;
glShadeModel(GL_SMOOTH);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// First place the light
// Save the coordinate transformation
glPushMatrix();
// Rotate coordinate system
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);

// Specify new position and direction in rotated coords.
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glLightfv(GL_LIGHT0,GL_SPOT_DIRECTION,spotDir);

// Draw a red cone to enclose the light source
glColor3ub(255,0,0);

// Translate origin to move the cone out to where the light
// is positioned.
glTranslatef(lightPos[0],lightPos[1],lightPos[2]);
glutSolidCone(4.0f,6.0f,15,15);

// Draw a smaller displaced sphere to denote the light bulb
// Save the lighting state variables
glPushAttrib(GL_LIGHTING_BIT);

// Turn off lighting and specify a bright yellow sphere
glDisable(GL_LIGHTING);
glColor3ub(255,255,0);
glutSolidSphere(3.0f, 15, 15);

// Restore lighting state variables
glPopAttrib();

// Restore coordinate transformations
glPopMatrix();


// Set material color and draw a sphere in the middle
glColor3ub(0, 0, 255);

if(iTess == MODE_VERYLOW)
glutSolidSphere(30.0f, 7, 7);
else
if(iTess == MODE_MEDIUM)
glutSolidSphere(30.0f, 15, 15);
else // iTess = MODE_MEDIUM;
glutSolidSphere(30.0f, 50, 50);

// Display the results
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not try to display the back sides

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
// Supply a slight ambient light so the objects can be seen
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);

// The light is composed of just a diffuse and specular components
glLightfv(GL_LIGHT0,GL_DIFFUSE,ambientLight);
glLightfv(GL_LIGHT0,GL_SPECULAR,specular);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);

// Specific spot effects
// Cut off angle is 60 degrees
glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,50.0f);

// Enable this light in particular
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// All materials hereafter have full specular reflectivity
// with a high shine
glMaterialfv(GL_FRONT, GL_SPECULAR,specref);
glMateriali(GL_FRONT, GL_SHININESS,128);


// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish viewing volume
fAspect = (GLfloat) w / (GLfloat) h;
gluPerspective(35.0f, fAspect, 1.0f, 500.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -250.0f);
}

int main(int argc, char* argv[])
{
int nMenu;

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Spot Light");

// Create the Menu
nMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Flat Shading",1);
glutAddMenuEntry("Smooth Shading",2);
glutAddMenuEntry("VL Tess",3);
glutAddMenuEntry("MD Tess",4);
glutAddMenuEntry("VH Tess",5);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 07:56 PM
خب این برنامه ای است كه با راست كلیك بر روی صفحه می تونیم موقعیت چراغها رو عوض كنیم و نوع نوری و رنگ اون رو مشاهده كنیم.


// gooy project tamrin 9.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include <math.h>


// GLfloat whiteLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat redLight[] = { 0.5f, 0.2f, 0.2f, 1.0f };
GLfloat greenLight[] = { 0.2f, 0.5f, 0.2f, 1.0f };
GLfloat yellowLight[] = { 0.5f, 0.5f, 0.2f, 1.0f };
GLfloat otherLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };

GLfloat sourceLight[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat sourceLightoff[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
float zoom = 0.0;
// colors
float R1 = 100 , G1 = 100 , B1 = 100 ,R2= 100 ,G2= 100 ,B2 = 100 ,R3 = 100 ,G3 = 100 ,B3 = 100 ;
// Called to draw scene

void ProcessMenu(int value)
{
switch(value)
{
case 1:
R1 = 0;
G1 = 255;
B1 = 0;
R2=G2=B2 = R3 = G3 = B3 = 100;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,greenLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
break;

case 2:
R2 = 255;
G2 = 255;
B2 = 0;
R1=G1=B1 = R3 = G3 = B3 = 100;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,yellowLight) ;
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
break;
case 3:
R3 = 255;
G3 = 0;
B3 = 0;
R1=G1=B1 = R2 = G2 = B2 = 100;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,redLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
break;

case 4:
R2 = 255;
G2 = 255;
B2 = 0;
R1= 0;
G1= 255;
B1 = 0;
R3 = 255;
G3 = B3 = 0;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,otherLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
break;

case 5:
R3=G3=B3=R1=G1=B1 = R2 = G2 = B2 = 100;
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLightoff);
break;

default:
break;
}

glutPostRedisplay();
}

void RenderScene(void)
{
GLUquadricObj *pObj;
// Angle of revolution around the nucleus
static float fElect1 = 0.0f;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Save the matrix state and do the rotations
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Move object back and do in place rotation
glTranslatef(100.0f, -1.0f, -5.0f ); //********************************************
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);

// Reset the modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Translate the whole scene out and into view
// This is the initial viewing transformation

glColor3f(1.0f, 1.0f, 1.0f);
glRotatef(0.0f,30.0f,30.0f,0.0f);

glTranslatef(100.0f, 30.0f, -100.0f );
///////////////////////////// Green Nucleus //////////////////////////////////////
if ( G1 == 255 ){
glDisable(GL_LIGHTING);
// glColor3ub(0, 255, 0);
glColor3ub(R1, G1, B1);
glutSolidSphere(10.0f, 15, 15);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glLoadIdentity();}

else {
glColor3ub(R1, G1, B1);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity(); }

///////////////////////////// Yellow Nucleus //////////////////////////////////////
glTranslatef(100.0f, 0.0f, -100.0f );
if ( R2 == 255 && G2 == 255 ){
glDisable(GL_LIGHTING);
// glColor3ub(255, 255, 0);
glColor3ub(R2, G2, B2);
glutSolidSphere(10.0f, 30, 15);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glLoadIdentity();}
else {
glColor3ub(R2, G2, B2);
glutSolidSphere(10.0f, 30, 15);
glLoadIdentity();}

///////////////////////////// Red Nucleus //////////////////////////////////////
glTranslatef(100.0f, -30.0f, -100.0f );
if ( R3 == 255){
glDisable(GL_LIGHTING);
// glColor3ub(255, 0, 0);
glColor3ub(R3, G3, B3);
glutSolidSphere(10.0f, 15, 15);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glLoadIdentity();
}
else {
glColor3ub(R3, G3, B3);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();}
//////////////////////////////////// Other Athoms /////////////////////////////////
glTranslatef(0.0f, 0.0f, -100.0f );
//------------------------------------ Athom 1 ----------------------------------
glColor3ub(255, 255, 255);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();
//-------------------------------------Athom 2 ----------------------------------
glTranslatef(15.0f, 0.0f, -100.0f );
glColor3ub(0, 0, 255);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();

//-------------------------------------Athom 3 ----------------------------------
glTranslatef(-15.0f, 0.0f, -100.0f );
glColor3ub(255, 0, 0);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();

//-------------------------------------Athom 4 ----------------------------------
glTranslatef(0.0f, 15.0f, -100.0f );
glColor3ub(255, 255, 0);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();
//-------------------------------------Athom 5 ----------------------------------
glTranslatef(0.0f, -15.0f, -100.0f );
glColor3ub(0, 255, 0);
glutSolidSphere(10.0f, 15, 15);
glLoadIdentity();


// Show the image
glutSwapBuffers();
}


// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet
glEnable(GL_LIGHTING);

/* if( G1 == 255 )
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,greenLight); */
// if ( R2 == 255 && G2 == 255)
// glLightModelfv(GL_LIGHT_MODEL_AMBIENT,yellowLight) ;
// if ( R3 == 255 )
// glLightModelfv(GL_LIGHT_MODEL_AMBIENT,redLight);
// else
// glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLightoff);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
glEnable(GL_DEPTH_TEST);
glEnable(GL_DITHER);
glShadeModel(GL_SMOOTH);

}

void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 1.0f;

/* if(key == GLUT_KEY_DOWN)
xRot += 1.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 1.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 1.0f;
*/
if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100, TimerFunc, 1);
}


void ChangeSize(int w, int h)
{
GLfloat fAspect;
// GLfloat nRange = 300.0f;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Calculate aspect ratio of the window
fAspect = (GLfloat)w/(GLfloat)h;

// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// field of view of 45 degrees, near and far planes 1.0 and 425
gluPerspective(100.0f, fAspect, 1.0, 425.0);
// Establish clipping volume (left, right, bottom, top, near, far)
/* if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

*/
// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -400.0f);

}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Atom1233");

//-------------------
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Turn On Green",1);
glutAddMenuEntry("Turn On Yellow",2);
glutAddMenuEntry("Turn On Red",3);
glutAddMenuEntry("Turn On ALL",4);
glutAddMenuEntry("Turn Off ALL",5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//-------------------
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
glutTimerFunc(500, TimerFunc, 1);
SetupRC();
glutMainLoop();

return 0;
}

فایل اجرایی پیوست همین پست می باشد.

Admin
17th September 2008, 07:57 PM
با کیبور می تونید این تصویر رو عقب و جلو از زاویه ای بخصوصی جلو و عقب کنین.


// BufferObject.c
// OpenGL SuperBible, Chapter 16
// Demonstrates vertex buffer objects
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <stdio.h>

PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLBUFFERSUBDATAPROC glBufferSubData;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLMAPBUFFERPROC glMapBuffer;
PFNGLUNMAPBUFFERPROC glUnmapBuffer;

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLuint bufferID;

GLboolean useBufferObject = GL_TRUE;
GLboolean mapBufferObject = GL_TRUE;
GLboolean animating = GL_TRUE;

GLint numSphereVertices = 30000;
GLfloat *sphereVertexArray = NULL;

GLfloat ambientLight[] = { 0.4f, 0.4f, 0.4f, 1.0f};
GLfloat diffuseLight[] = { 0.9f, 0.9f, 0.9f, 1.0f};
GLfloat cameraPos[] = { 400.0f, 400.0f, 400.0f, 1.0f};

// Called to regenerate points on the sphere
void RegenerateSphere(void)
{
GLint i;

if (mapBufferObject && useBufferObject)
{
// Delete old vertex array memory
if (sphereVertexArray)
free(sphereVertexArray);

glBindBuffer(GL_ARRAY_BUFFER, bufferID);

// Avoid pipeline flush during glMapBuffer by
// marking data store as empty
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) *
numSphereVertices * 3, NULL,
animating ? GL_STREAM_DRAW : GL_STATIC_DRAW);

sphereVertexArray = (GLfloat *)glMapBuffer(GL_ARRAY_BUFFER,
GL_WRITE_ONLY);
if (!sphereVertexArray)
{
fprintf(stderr, "Unable to map buffer object!\n");
Sleep(2000);
exit(0);
}
}
else if (!sphereVertexArray)
{
// We need our old vertex array memory back
sphereVertexArray = (GLfloat *)malloc(sizeof(GLfloat) *
numSphereVertices * 3);
if (!sphereVertexArray)
{
fprintf(stderr, "Unable to allocate memory for vertex arrays!\n");
Sleep(2000);
exit(0);
}
}

for (i = 0; i < numSphereVertices; i++)
{
GLfloat r1, r2, r3, scaleFactor;

// pick a random vector
r1 = (GLfloat)(rand() - (RAND_MAX/2));
r2 = (GLfloat)(rand() - (RAND_MAX/2));
r3 = (GLfloat)(rand() - (RAND_MAX/2));

// determine normalizing scale factor
scaleFactor = 1.0f / sqrt(r1*r1 + r2*r2 + r3*r3);

sphereVertexArray[(i*3)+0] = r1 * scaleFactor;
sphereVertexArray[(i*3)+1] = r2 * scaleFactor;
sphereVertexArray[(i*3)+2] = r3 * scaleFactor;
}

if (mapBufferObject && useBufferObject)
{
if (!glUnmapBuffer(GL_ARRAY_BUFFER))
{
// Some window system event has trashed our data...
// Try, try again!
RegenerateSphere();
}
sphereVertexArray = NULL;
}
}

// Switch between buffer objects and plain old vertex arrays
void SetRenderingMethod(void)
{
if (useBufferObject)
{
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
// No stride, no offset
glNormalPointer(GL_FLOAT, 0, 0);
glVertexPointer(3, GL_FLOAT, 0, 0);

if (!mapBufferObject)
{
if (animating)
{
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat) *
numSphereVertices * 3, sphereVertexArray);
}
else
{
// If not animating, this gets called once
// to establish new static buffer object
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) *
numSphereVertices * 3, sphereVertexArray,
GL_STATIC_DRAW);
}
}
}
else
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
glNormalPointer(GL_FLOAT, 0, sphereVertexArray);
glVertexPointer(3, GL_FLOAT, 0, sphereVertexArray);
}
}

// Called to draw scene objects
void DrawModels(void)
{
GLint r, g, b;

// Draw 27 spheres in a color cube
for (r = 0; r < 3; r++)
{
for (g = 0; g < 3; g++)
{
for (b = 0; b < 3; b++)
{
glColor3f(r * 0.5f, g * 0.5f, b * 0.5f);

glPushMatrix();
glTranslatef(100.0f * r - 100.0f,
100.0f * g - 100.0f,
100.0f * b - 100.0f);
glScalef(50.0f, 50.0f, 50.0f);
glDrawArrays(GL_POINTS, 0, numSphereVertices);
glPopMatrix();
}
}
}
}

// Called to draw scene
void RenderScene(void)
{
static GLTStopwatch stopWatch;
static int frameCounter = 0;

// Get initial time
if (frameCounter == 0)
gltStopwatchReset(&stopWatch);


frameCounter++;
if (frameCounter == 100)
{
frameCounter = 0;
fprintf(stdout, "FPS: %f\n", 100.0f / gltStopwatchRead(&stopWatch));
gltStopwatchReset(&stopWatch);
}

// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 10.0f, 10000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

if (animating)
{
RegenerateSphere();
SetRenderingMethod();
}

// Draw objects in the scene
DrawModels();

// Flush drawing commands
glutSwapBuffers();

glutPostRedisplay();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
const GLubyte *version;
GLboolean glVersion15 = GL_FALSE;

fprintf(stdout, "Buffer Object Demo\n\n");

// Make sure required functionality is available!
version = glGetString(GL_VERSION);
if ((version[0] == '1') && (version[1] == '.') &&
(version[2] >= '5') && (version[2] <= '9'))
{
glVersion15 = GL_TRUE;
}

if (!glVersion15 && !gltIsExtSupported("GL_ARB_vertex_buffer_object"))
{
fprintf(stderr, "Neither OpenGL 1.5 nor GL_ARB_vertex_buffer_object"
" extension is available!\n");
Sleep(2000);
exit(0);
}

// Load the function pointers
if (glVersion15)
{
glBindBuffer = gltGetExtensionPointer("glBindBuffer");
glBufferData = gltGetExtensionPointer("glBufferData");
glBufferSubData = gltGetExtensionPointer("glBufferSubData");
glDeleteBuffers = gltGetExtensionPointer("glDeleteBuffers");
glGenBuffers = gltGetExtensionPointer("glGenBuffers");
glMapBuffer = gltGetExtensionPointer("glMapBuffer");
glUnmapBuffer = gltGetExtensionPointer("glUnmapBuffer");
}
else
{
glBindBuffer = gltGetExtensionPointer("glBindBufferARB");
glBufferData = gltGetExtensionPointer("glBufferDataARB");
glBufferSubData = gltGetExtensionPointer("glBufferSubDataARB");
glDeleteBuffers = gltGetExtensionPointer("glDeleteBuffersARB");
glGenBuffers = gltGetExtensionPointer("glGenBuffersARB");
glMapBuffer = gltGetExtensionPointer("glMapBufferARB");
glUnmapBuffer = gltGetExtensionPointer("glUnmapBufferARB");
}

if (!glBindBuffer || !glBufferData || !glBufferSubData ||
!glDeleteBuffers || !glGenBuffers || !glMapBuffer || !glUnmapBuffer)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}

sphereVertexArray = (GLfloat *)malloc(sizeof(GLfloat) *
numSphereVertices * 3);
if (!sphereVertexArray)
{
fprintf(stderr, "Unable to allocate system memory for vertex arrays!");
Sleep(2000);
exit(0);
}

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Generate a buffer object
glGenBuffers(1, &bufferID);
// Create the data store
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) *
numSphereVertices * 3, NULL,
GL_STATIC_DRAW);

// Set up vertex arrays
RegenerateSphere();
SetRenderingMethod();
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

// Dark background
glClearColor(0.3f, 0.3f, 0.3f, 1.0f );

// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

// Set up some lighting state that never changes
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
useBufferObject = !useBufferObject;
RegenerateSphere();
SetRenderingMethod();
if (useBufferObject)
{
glutChangeToMenuEntry(1, "Toggle buffer object usage (currently ON)", 1);
}
else
{
glutChangeToMenuEntry(1, "Toggle buffer object usage (currently OFF)", 1);
}
break;

case 2:
mapBufferObject = !mapBufferObject;
RegenerateSphere();
SetRenderingMethod();
if (mapBufferObject)
{
glutChangeToMenuEntry(2, "Toggle mapped buffer object (currently ON)", 2);
}
else
{
glutChangeToMenuEntry(2, "Toggle mapped buffer object (currently OFF)", 2);
}
break;

case 3:
animating = !animating;
if (animating)
{
glutChangeToMenuEntry(3, "Toggle animation (currently ON)", 3);
// Establish streaming buffer object
// Data will be loaded with subsequent calls to glBufferSubData
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) *
numSphereVertices * 3, NULL, GL_STREAM_DRAW);
}
else
{
glutChangeToMenuEntry(3, "Toggle animation (currently OFF)", 3);
// Establish static buffer object
// Data will be loaded with subsequent calls to glBufferSubData
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) *
numSphereVertices * 3, NULL, GL_STATIC_DRAW);
RegenerateSphere();
SetRenderingMethod();
}
break;

default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'x':
cameraPos[0] += 5.0f;
break;
case 'X':
cameraPos[0] -= 5.0f;
break;
case 'y':
cameraPos[1] += 5.0f;
break;
case 'Y':
cameraPos[1] -= 5.0f;
break;
case 'z':
cameraPos[2] += 5.0f;
break;
case 'Z':
cameraPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
cameraPos[0] += 5.0f;
break;
case GLUT_KEY_RIGHT:
cameraPos[0] -= 5.0f;
break;
case GLUT_KEY_UP:
cameraPos[1] += 5.0f;
break;
case GLUT_KEY_DOWN:
cameraPos[1] -= 5.0f;
break;
default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
windowWidth = w;
windowHeight = h;

glViewport(0, 0, windowWidth, windowHeight);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Buffer Object Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle buffer object usage (currently ON)", 1);
glutAddMenuEntry("Toggle mapped buffer object (currently ON)", 2);
glutAddMenuEntry("Toggle animation (currently ON)", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);

SetupRC();

glutMainLoop();

if (sphereVertexArray)
free(sphereVertexArray);
if (glDeleteBuffers)
glDeleteBuffers(1, &bufferID);

return 0;
}

Admin
17th September 2008, 07:59 PM
اینم مثل برنامه ی قبلی با کیبور می تونین زاویه تصویر رو عوض کنین.


// OcclusionQuery.c
// OpenGL SuperBible, Chapter 17
// Demonstrates occlusion queries
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <stdio.h>

PFNGLBEGINQUERYPROC glBeginQuery;
PFNGLDELETEQUERIESPROC glDeleteQueries;
PFNGLENDQUERYPROC glEndQuery;
PFNGLGENQUERIESPROC glGenQueries;
PFNGLGETQUERYIVPROC glGetQueryiv;
PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv;

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLint mainMenu, bboxMenu; // menu handles

GLboolean occlusionDetection = GL_TRUE;
GLboolean showBoundingVolume = GL_FALSE;
GLint boundingVolume = 0;
GLuint queryIDs[27];

GLfloat ambientLight[] = { 0.4f, 0.4f, 0.4f, 1.0f};
GLfloat diffuseLight[] = { 0.9f, 0.9f, 0.9f, 1.0f};
GLfloat lightPos[] = { 100.0f, 300.0f, 100.0f, 1.0f};
GLfloat cameraPos[] = { 200.0f, 300.0f, 400.0f, 1.0f};

// Called to draw the occluding grid
void DrawOccluder(void)
{
glColor3f(0.5f, 0.25f, 0.0f);

glPushMatrix();
glScalef(30.0f, 30.0f, 1.0f);
glTranslatef(0.0f, 0.0f, 50.0f);
glutSolidCube(10.0f);
glTranslatef(0.0f, 0.0f, -100.0f);
glutSolidCube(10.0f);
glPopMatrix();

glPushMatrix();
glScalef(1.0f, 30.0f, 30.0f);
glTranslatef(50.0f, 0.0f, 0.0f);
glutSolidCube(10.0f);
glTranslatef(-100.0f, 0.0f, 0.0f);
glutSolidCube(10.0f);
glPopMatrix();

glPushMatrix();
glScalef(30.0f, 1.0f, 30.0f);
glTranslatef(0.0f, 50.0f, 0.0f);
glutSolidCube(10.0f);
glTranslatef(0.0f, -100.0f, 0.0f);
glutSolidCube(10.0f);
glPopMatrix();
}

// Called to draw sphere
void DrawSphere(GLint sphereNum)
{
GLboolean occluded = GL_FALSE;

if (occlusionDetection)
{
GLint passingSamples;

// Check if this sphere would be occluded
glGetQueryObjectiv(queryIDs[sphereNum], GL_QUERY_RESULT,
&passingSamples);
if (passingSamples == 0)
occluded = GL_TRUE;
}

if (!occluded)
{
glutSolidSphere(50.0f, 100, 100);
}
}

// Called to draw scene objects
void DrawModels(void)
{
GLint r, g, b;

if (occlusionDetection || showBoundingVolume)
{
// Draw bounding boxes after drawing the main occluder
DrawOccluder();

// All we care about for bounding box is resulting depth values
glShadeModel(GL_FLAT);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_NORMALIZE);
// Texturing is already disabled
if (!showBoundingVolume)
glColorMask(0, 0, 0, 0);

// Draw 27 spheres in a color cube
for (r = 0; r < 3; r++)
{
for (g = 0; g < 3; g++)
{
for (b = 0; b < 3; b++)
{
if (showBoundingVolume)
glColor3f(r * 0.5f, g * 0.5f, b * 0.5f);

glPushMatrix();
glTranslatef(100.0f * r - 100.0f,
100.0f * g - 100.0f,
100.0f * b - 100.0f);
glBeginQuery(GL_SAMPLES_PASSED, queryIDs[(r*9)+(g*3)+b]);
switch (boundingVolume)
{
case 0:
glutSolidCube(100.0f);
break;
case 1:
glScalef(150.0f, 150.0f, 150.0f);
glutSolidTetrahedron();
break;
case 2:
glScalef(90.0f, 90.0f, 90.0f);
glutSolidOctahedron();
break;
case 3:
glScalef(40.0f, 40.0f, 40.0f);
glutSolidDodecahedron();
break;
case 4:
glScalef(65.0f, 65.0f, 65.0f);
glutSolidIcosahedron();
break;
}
glEndQuery(GL_SAMPLES_PASSED);
glPopMatrix();
}
}
}

if (!showBoundingVolume)
glClear(GL_DEPTH_BUFFER_BIT);

// Restore normal drawing state
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glColorMask(1, 1, 1, 1);
}

DrawOccluder();

// Turn on texturing just for spheres
glEnable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);

// Draw 27 spheres in a color cube
for (r = 0; r < 3; r++)
{
for (g = 0; g < 3; g++)
{
for (b = 0; b < 3; b++)
{
glColor3f(r * 0.5f, g * 0.5f, b * 0.5f);

glPushMatrix();
glTranslatef(100.0f * r - 100.0f,
100.0f * g - 100.0f,
100.0f * b - 100.0f);
DrawSphere((r*9)+(g*3)+b);
glPopMatrix();
}
}
}

glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
}

// Called to draw scene
void RenderScene(void)
{
static GLTStopwatch stopWatch;
static int frameCounter = 0;

// Get initial time
if (frameCounter == 0)
gltStopwatchReset(&stopWatch);


frameCounter++;
if (frameCounter == 100)
{
frameCounter = 0;
fprintf(stdout, "FPS: %f\n", 100.0f / gltStopwatchRead(&stopWatch));
gltStopwatchReset(&stopWatch);
}

// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 10.0f, 10000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Draw objects in the scene
DrawModels();

if (glGetError() != GL_NO_ERROR)
{
fprintf(stderr, "GL Error!\n");
Sleep(5000);
}

// Flush drawing commands
glutSwapBuffers();

glutPostRedisplay();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
const GLubyte *version;
GLboolean glVersion15 = GL_FALSE;
GLint queryCounterBits;

fprintf(stdout, "Occlusion Query Demo\n\n");

// Make sure required functionality is available!
version = glGetString(GL_VERSION);
if ((version[0] == '1') && (version[1] == '.') &&
(version[2] >= '5') && (version[2] <= '9'))
{
glVersion15 = GL_TRUE;
}

if (!glVersion15 && !gltIsExtSupported("GL_ARB_occlusion_query"))
{
fprintf(stderr, "Neither OpenGL 1.5 nor GL_ARB_occlusion_query"
" extension is available!\n");
Sleep(2000);
exit(0);
}

// Load the function pointers
if (glVersion15)
{
glBeginQuery = gltGetExtensionPointer("glBeginQuery");
glDeleteQueries = gltGetExtensionPointer("glDeleteQueries");
glEndQuery = gltGetExtensionPointer("glEndQuery");
glGenQueries = gltGetExtensionPointer("glGenQueries");
glGetQueryiv = gltGetExtensionPointer("glGetQueryiv");
glGetQueryObjectiv = gltGetExtensionPointer("glGetQueryObjectiv");
}
else
{
glBeginQuery = gltGetExtensionPointer("glBeginQueryARB");
glDeleteQueries = gltGetExtensionPointer("glDeleteQueriesARB");
glEndQuery = gltGetExtensionPointer("glEndQueryARB");
glGenQueries = gltGetExtensionPointer("glGenQueriesARB");
glGetQueryiv = gltGetExtensionPointer("glGetQueryivARB");
glGetQueryObjectiv = gltGetExtensionPointer("glGetQueryObjectivARB");
}

if (!glBeginQuery || !glDeleteQueries || !glEndQuery || !glGenQueries ||
!glGetQueryiv || !glGetQueryObjectiv)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}

// Make sure query counter bits is non-zero
glGetQueryiv(GL_SAMPLES_PASSED, GL_QUERY_COUNTER_BITS, &queryCounterBits);
if (queryCounterBits == 0)
{
fprintf(stderr, "Occlusion queries not really supported!\n");
fprintf(stderr, "Available query counter bits: 0\n");
Sleep(2000);
exit(0);
}

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Generate occlusion query names
glGenQueries(27, queryIDs);

// Black background
glClearColor(0.3f, 0.3f, 0.3f, 1.0f );

// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

// Set up some lighting state that never changes
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

// Set up texturing for spheres
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
{
GLfloat p[4] = {1.0f/50.0f, 0.0f, 0.0f, -0.5f};
GLint w, h, c;
GLenum format;
GLbyte *texels = gltLoadTGA("logo.tga", &w, &h, &c, &format);
glTexImage2D(GL_TEXTURE_2D, 0, c, w, h, 0, format, GL_UNSIGNED_BYTE, texels);
free(texels);
glTexGenfv(GL_S, GL_OBJECT_PLANE, p);
p[0] = 0.0f;
p[1] = 1.0f/50.0f;
glTexGenfv(GL_T, GL_OBJECT_PLANE, p);
}
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
occlusionDetection = !occlusionDetection;
if (occlusionDetection)
{
glutChangeToMenuEntry(1, "Toggle occlusion query (currently ON)", 1);
}
else
{
glutChangeToMenuEntry(1, "Toggle occlusion query (currently OFF)", 1);
}
break;

case 2:
showBoundingVolume = !showBoundingVolume;
if (showBoundingVolume)
{
glutChangeToMenuEntry(2, "Toggle bounding volume (currently ON)", 2);
}
else
{
glutChangeToMenuEntry(2, "Toggle bounding volume (currently OFF)", 2);
}
break;

default:
boundingVolume = value - 3;
glutSetMenu(mainMenu);
switch (boundingVolume)
{
case 0:
glutChangeToSubMenu(3, "Choose bounding volume (currently BOX)", bboxMenu);
break;
case 1:
glutChangeToSubMenu(3, "Choose bounding volume (currently TETRAHEDRON)", bboxMenu);
break;
case 2:
glutChangeToSubMenu(3, "Choose bounding volume (currently OCTAHEDRON)", bboxMenu);
break;
case 3:
glutChangeToSubMenu(3, "Choose bounding volume (currently DODECAHEDRON)", bboxMenu);
break;
case 4:
glutChangeToSubMenu(3, "Choose bounding volume (currently ICOSAHEDRON)", bboxMenu);
break;
}
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'b':
case 'B':
boundingVolume = (boundingVolume+1)%5;
break;
case 's':
case 'S':
showBoundingVolume = !showBoundingVolume;
break;
case 'o':
case 'O':
occlusionDetection = !occlusionDetection;
break;
case 'x':
cameraPos[0] += 5.0f;
break;
case 'X':
cameraPos[0] -= 5.0f;
break;
case 'y':
cameraPos[1] += 5.0f;
break;
case 'Y':
cameraPos[1] -= 5.0f;
break;
case 'z':
cameraPos[2] += 5.0f;
break;
case 'Z':
cameraPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
cameraPos[0] += 5.0f;
break;
case GLUT_KEY_RIGHT:
cameraPos[0] -= 5.0f;
break;
case GLUT_KEY_UP:
cameraPos[1] += 5.0f;
break;
case GLUT_KEY_DOWN:
cameraPos[1] -= 5.0f;
break;
default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
windowWidth = w;
windowHeight = h;

glViewport(0, 0, windowWidth, windowHeight);
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Occlusion Query Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

// Create the Menu
bboxMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("BOX (CUBE)", 3);
glutAddMenuEntry("TETRAHEDRON", 4);
glutAddMenuEntry("OCTAHEDRON", 5);
glutAddMenuEntry("DODECAHEDRON", 6);
glutAddMenuEntry("ICOSAHEDRON", 7);

mainMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle occlusion query (currently ON)", 1);
glutAddMenuEntry("Show bounding volume (currently OFF)", 2);
glutAddSubMenu("Choose bounding volume (currently BOX)", bboxMenu);
glutAttachMenu(GLUT_RIGHT_BUTTON);

SetupRC();

glutMainLoop();

if (glDeleteQueries)
glDeleteQueries(27, queryIDs);

return 0;
}

Admin
17th September 2008, 08:00 PM
با این برنامه هم میشه با کیبور زاویه تصویر رو عوض کرد.


// ShadowMap.c
// OpenGL SuperBible, Chapter 18
// Demonstrates shadow mapping
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenGL Stuff
#include <stdio.h>

GLboolean ambientShadowAvailable = GL_FALSE;
GLboolean controlCamera = GL_TRUE; // xyz keys will control lightpos
GLboolean noShadows = GL_FALSE; // normal lighting
GLboolean showShadowMap = GL_FALSE; // show the shadowmap texture

GLfloat factor = 4.0f; // for polygon offset

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLint shadowSize = 512; // set based on window size
GLuint shadowTextureID;

GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f};
GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f};
GLfloat noLight[] = { 0.0f, 0.0f, 0.0f, 1.0f};
GLfloat lightPos[] = { 100.0f, 300.0f, 100.0f, 1.0f};
GLfloat cameraPos[] = { 100.0f, 150.0f, 200.0f, 1.0f};

// Called to draw scene objects
void DrawModels(void)
{
// Draw plane that the objects rest on
glColor3f(0.0f, 0.0f, 0.90f); // Blue
glNormal3f(0.0f, 1.0f, 0.0f);
glBegin(GL_QUADS);
glVertex3f(-100.0f, -25.0f, -100.0f);
glVertex3f(-100.0f, -25.0f, 100.0f);
glVertex3f(100.0f, -25.0f, 100.0f);
glVertex3f(100.0f, -25.0f, -100.0f);
glEnd();

// Draw red cube
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidCube(48.0f);

// Draw green sphere
glColor3f(0.0f, 1.0f, 0.0f);
glPushMatrix();
glTranslatef(-60.0f, 0.0f, 0.0f);
glutSolidSphere(25.0f, 50, 50);
glPopMatrix();

// Draw yellow cone
glColor3f(1.0f, 1.0f, 0.0f);
glPushMatrix();
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
glTranslatef(60.0f, 0.0f, -24.0f);
glutSolidCone(25.0f, 50.0f, 50, 50);
glPopMatrix();

// Draw magenta torus
glColor3f(1.0f, 0.0f, 1.0f);
glPushMatrix();
glTranslatef(0.0f, 0.0f, 60.0f);
glutSolidTorus(8.0f, 16.0f, 50, 50);
glPopMatrix();

// Draw cyan octahedron
glColor3f(0.0f, 1.0f, 1.0f);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -60.0f);
glScalef(25.0f, 25.0f, 25.0f);
glutSolidOctahedron();
glPopMatrix();
}

// Called to regenerate the shadow map
void RegenerateShadowMap(void)
{
GLfloat lightToSceneDistance, nearPlane, fieldOfView;
GLfloat lightModelview[16], lightProjection[16];

// Save the depth precision for where it's useful
lightToSceneDistance = sqrt(lightPos[0] * lightPos[0] +
lightPos[1] * lightPos[1] +
lightPos[2] * lightPos[2]);
nearPlane = lightToSceneDistance - 150.0f;
if (nearPlane < 50.0f)
nearPlane = 50.0f;
// Keep the scene filling the depth texture
fieldOfView = 17000.0f / lightToSceneDistance;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fieldOfView, 1.0f, nearPlane, nearPlane + 300.0f);
glGetFloatv(GL_PROJECTION_MATRIX, lightProjection);
// Switch to light's point of view
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(lightPos[0], lightPos[1], lightPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glGetFloatv(GL_MODELVIEW_MATRIX, lightModelview);
glViewport(0, 0, shadowSize, shadowSize);

// Clear the window with current clearing color
glClear(GL_DEPTH_BUFFER_BIT);

// All we care about here is resulting depth values
glShadeModel(GL_FLAT);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_NORMALIZE);
glColorMask(0, 0, 0, 0);

// Overcome imprecision
glEnable(GL_POLYGON_OFFSET_FILL);

// Draw objects in the scene
DrawModels();

// Copy depth values into depth texture
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
0, 0, shadowSize, shadowSize, 0);

// Restore normal drawing state
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);

glColorMask(1, 1, 1, 1);
glDisable(GL_POLYGON_OFFSET_FILL);

// Set up texture matrix for shadow map projection
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glTranslatef(0.5f, 0.5f, 0.5f);
glScalef(0.5f, 0.5f, 0.5f);
glMultMatrixf(lightProjection);
glMultMatrixf(lightModelview);
}

// Called to draw scene
void RenderScene(void)
{
// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glViewport(0, 0, windowWidth, windowHeight);

// Track light position
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

if (showShadowMap)
{
// Display shadow map for educational purposes
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Show the shadowMap at its actual size relative to window
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(((GLfloat)shadowSize/(GLfloat)windowWidth)*2.0-1.0f,
-1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(((GLfloat)shadowSize/(GLfloat)windowWidth)*2.0-1.0f,
((GLfloat)shadowSize/(GLfloat)windowHeight)*2.0-1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f,
((GLfloat)shadowSize/(GLfloat)windowHeight)*2.0-1.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
}
else if (noShadows)
{
// Set up some simple lighting
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);

// Draw objects in the scene
DrawModels();
}
else
{
GLfloat sPlane[4] = {1.0f, 0.0f, 0.0f, 0.0f};
GLfloat tPlane[4] = {0.0f, 1.0f, 0.0f, 0.0f};
GLfloat rPlane[4] = {0.0f, 0.0f, 1.0f, 0.0f};
GLfloat qPlane[4] = {0.0f, 0.0f, 0.0f, 1.0f};

if (!ambientShadowAvailable)
{
GLfloat lowAmbient[4] = {0.1f, 0.1f, 0.1f, 1.0f};
GLfloat lowDiffuse[4] = {0.35f, 0.35f, 0.35f, 1.0f};

// Because there is no support for an "ambient"
// shadow compare fail value, we'll have to
// draw an ambient pass first...
glLightfv(GL_LIGHT0, GL_AMBIENT, lowAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lowDiffuse);

// Draw objects in the scene
DrawModels();

// Enable alpha test so that shadowed fragments are discarded
glAlphaFunc(GL_GREATER, 0.9f);
glEnable(GL_ALPHA_TEST);
}

glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);

// Set up shadow comparison
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

// Set up the eye plane for projecting the shadow map on the scene
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
glEnable(GL_TEXTURE_GEN_Q);
glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
glTexGenfv(GL_T, GL_EYE_PLANE, tPlane);
glTexGenfv(GL_R, GL_EYE_PLANE, rPlane);
glTexGenfv(GL_Q, GL_EYE_PLANE, qPlane);

// Draw objects in the scene
DrawModels();

glDisable(GL_ALPHA_TEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_TEXTURE_GEN_Q);
}

if (glGetError() != GL_NO_ERROR)
fprintf(stderr, "GL Error!\n");

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
const GLubyte *version;

fprintf(stdout, "Shadow Mapping Demo\n\n");

// Make sure required functionality is available!
version = glGetString(GL_VERSION);
if (((version[0] != '1') || (version[1] != '.') ||
(version[2] < '4') || (version[2] > '9')) && // 1.4+
(!gltIsExtSupported("GL_ARB_shadow")))
{
fprintf(stderr, "Neither OpenGL 1.4 nor GL_ARB_shadow"
" extension is available!\n");
Sleep(2000);
exit(0);
}

// Check for optional extension
if (gltIsExtSupported("GL_ARB_shadow_ambient"))
{
ambientShadowAvailable = GL_TRUE;
}
else
{
fprintf(stderr, "GL_ARB_shadow_ambient extension not available!\n");
fprintf(stderr, "Extra ambient rendering pass will be required.\n\n");
Sleep(2000);
}

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tf/F\t\tChange polygon offset factor +/-\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glPolygonOffset(factor, 0.0f);

// Set up some lighting state that never changes
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHT0);

// Set up some texture state that never changes
glGenTextures(1, &shadowTextureID);
glBindTexture(GL_TEXTURE_2D, shadowTextureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
if (ambientShadowAvailable)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB,
0.5f);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);

RegenerateShadowMap();
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
noShadows = !noShadows;
showShadowMap = GL_FALSE;
if (noShadows)
{
glutChangeToMenuEntry(1, "Toggle shadows (currently OFF)", 1);
}
else
{
glutChangeToMenuEntry(1, "Toggle shadows (currently ON)", 1);
}
glutChangeToMenuEntry(2, "Toggle show shadowmap (currently OFF)", 2);
break;

case 2:
showShadowMap = !showShadowMap;
noShadows = GL_FALSE;
if (showShadowMap)
{
glutChangeToMenuEntry(2, "Toggle show shadowmap (currently ON)", 2);
}
else
{
glutChangeToMenuEntry(2, "Toggle show shadowmap (currently OFF)", 2);
}
glutChangeToMenuEntry(1, "Toggle shadows (currently ON)", 1);
break;

case 3:
controlCamera = !controlCamera;
if (controlCamera)
{
glutChangeToMenuEntry(3, "Switch to LIGHT control (currently CAMERA)", 3);
}
else
{
glutChangeToMenuEntry(3, "Switch to CAMERA control (currently LIGHT)", 3);
}
break;

default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'f':
factor++;
glPolygonOffset(factor, 0.0f);
RegenerateShadowMap();
break;
case 'F':
factor--;
glPolygonOffset(factor, 0.0f);
RegenerateShadowMap();
break;
case 'x':
if (controlCamera)
cameraPos[0] += 5.0f;
else
lightPos[0] += 5.0f;
break;
case 'X':
if (controlCamera)
cameraPos[0] -= 5.0f;
else
lightPos[0] -= 5.0f;
break;
case 'y':
if (controlCamera)
cameraPos[1] += 5.0f;
else
lightPos[1] += 5.0f;
break;
case 'Y':
if (controlCamera)
cameraPos[1] -= 5.0f;
else
lightPos[1] -= 5.0f;
break;
case 'z':
if (controlCamera)
cameraPos[2] += 5.0f;
else
lightPos[2] += 5.0f;
break;
case 'Z':
if (controlCamera)
cameraPos[2] -= 5.0f;
else
lightPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// We don't need to regenerate the shadow map
// if only the camera angle changes
if (!controlCamera)
RegenerateShadowMap();

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
if (controlCamera)
cameraPos[0] -= 5.0f;
else
lightPos[0] -= 5.0f;
break;
case GLUT_KEY_RIGHT:
if (controlCamera)
cameraPos[0] += 5.0f;
else
lightPos[0] += 5.0f;
break;
case GLUT_KEY_UP:
if (controlCamera)
cameraPos[2] -= 5.0f;
else
lightPos[2] -= 5.0f;
break;
case GLUT_KEY_DOWN:
if (controlCamera)
cameraPos[2] += 5.0f;
else
lightPos[2] += 5.0f;
break;
default:
break;
}

// We don't need to regenerate the shadow map
// if only the camera angle changes
if (!controlCamera)
RegenerateShadowMap();

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
GLint i;

windowWidth = w;
windowHeight = h;

// Find the largest power of two that will fit in window
if (w > h)
shadowSize = h;
else
shadowSize = w;

// Try each size until we get one that's too big
i = 0;
while ((1 << i) <= shadowSize)
i++;
shadowSize = (1 << (i-1));
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Shadow Mapping Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle shadows (currently ON)", 1);
glutAddMenuEntry("Toggle show shadowmap (currently OFF)", 2);
glutAddMenuEntry("Switch to LIGHT control (currently CAMERA)", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);

SetupRC();

glutMainLoop();
return 0;
}

Admin
17th September 2008, 08:01 PM
// LowLevelShaders.c
// OpenGL SuperBible, Chapter 20
// Demonstrates low-level shaders
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenGL Stuff
#include <stdio.h>

#ifndef __APPLE__
PFNGLPROGRAMSTRINGARBPROC glProgramStringARB;
PFNGLBINDPROGRAMARBPROC glBindProgramARB;
PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB;
PFNGLGENPROGRAMSARBPROC glGenProgramsARB;
PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB;

PFNGLSECONDARYCOLOR3FPROC glSecondaryColor3f;
#endif

GLboolean useVertexShader = GL_TRUE;
GLboolean useFragmentShader = GL_TRUE;
GLboolean doBlink = GL_FALSE;

GLuint ids[2]; // Shader object names

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLfloat cameraPos[] = { 100.0f, 150.0f, 200.0f, 1.0f};

// Called to draw scene objects
void DrawModels(void)
{
// Draw plane that the objects rest on
glColor3f(0.0f, 0.0f, 0.90f); // Blue
glNormal3f(0.0f, 1.0f, 0.0f);
glBegin(GL_QUADS);
glVertex3f(-100.0f, -25.0f, -100.0f);
glVertex3f(-100.0f, -25.0f, 100.0f);
glVertex3f(100.0f, -25.0f, 100.0f);
glVertex3f(100.0f, -25.0f, -100.0f);
glEnd();

// Draw red cube
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidCube(48.0f);

// Draw green sphere
glColor3f(0.0f, 1.0f, 0.0f);
glPushMatrix();
glTranslatef(-60.0f, 0.0f, 0.0f);
glutSolidSphere(25.0f, 50, 50);
glPopMatrix();

// Draw yellow cone
glColor3f(1.0f, 1.0f, 0.0f);
glPushMatrix();
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
glTranslatef(60.0f, 0.0f, -24.0f);
glutSolidCone(25.0f, 50.0f, 50, 50);
glPopMatrix();

// Draw magenta torus
glColor3f(1.0f, 0.0f, 1.0f);
glPushMatrix();
glTranslatef(0.0f, 0.0f, 60.0f);
glutSolidTorus(8.0f, 16.0f, 50, 50);
glPopMatrix();

// Draw cyan octahedron
glColor3f(0.0f, 1.0f, 1.0f);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -60.0f);
glScalef(25.0f, 25.0f, 25.0f);
glutSolidOctahedron();
glPopMatrix();
}

// Called to draw scene
void RenderScene(void)
{
static GLfloat flickerFactor = 1.0f;

// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glViewport(0, 0, windowWidth, windowHeight);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

if (doBlink)
{
// Pick a random flicker factor
flickerFactor += ((((GLfloat)rand())/((GLfloat)RAND_MAX)) - 0.5f) * 0.1f;
if (flickerFactor > 1.0f) flickerFactor = 1.0f;
if (flickerFactor < 0.0f) flickerFactor = 0.0f;
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_A RB, 0, flickerFactor, flickerFactor, flickerFactor, 1.0f);
}

// Draw objects in the scene
DrawModels();

if (glGetError() != GL_NO_ERROR)
fprintf(stderr, "GL Error!\n");

// Flush drawing commands
glutSwapBuffers();

glutPostRedisplay();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLint errorPos;
const GLubyte *version;

GLbyte vpString[] =
"!!ARBvp1.0\n"
"# This is our Hello World vertex shader\n"
"# notice how comments are preceded by '#'\n"
"\n"
"ATTRIB iPos = vertex.position; # input position\n"
"ATTRIB iPrC = vertex.color.primary; # input primary color\n"
"\n"
"OUTPUT oPos = result.position; # output position\n"
"OUTPUT oPrC = result.color.primary; # output primary color\n"
"OUTPUT oScC = result.color.secondary; # output secondary color\n"
"\n"
"PARAM mvp[4] = { state.matrix.mvp }; # model-view * projection matrix\n"
"\n"
"TEMP tmp; # temporary register\n"
"\n"
"DP4 tmp.x, iPos, mvp[0]; # multiply input position by MVP\n"
"DP4 tmp.y, iPos, mvp[1];\n"
"DP4 tmp.z, iPos, mvp[2];\n"
"DP4 tmp.w, iPos, mvp[3];\n"
"\n"
"MOV oPos, tmp; # output clip-space coord\n"
"\n"
"MOV oPrC, iPrC; # copy primary color input to output\n"
"\n"
"RCP tmp.w, tmp.w; # tmp now contains 1/W instead of W\n"
"MUL tmp.xyz, tmp, tmp.w; # tmp now contains persp-divided coords\n"
"MAD oScC, tmp, 0.5, 0.5; # map from [-1,1] to [0,1] and output\n"
"END\n";

GLbyte fpString[] =
"!!ARBfp1.0\n"
"# This is our Hello World fragment shader\n"
"\n"
"ATTRIB iPrC = fragment.color.primary; # input primary color\n"
"ATTRIB iScC = fragment.color.secondary;# input secondary color\n"
"TEMP tmp; # temporary register\n"
"\n"
"OUTPUT oCol = result.color; # output color\n"
"\n"
"LRP tmp.rgb, 0.5, iPrC, iScC; # 50/50 mix of two colors\n"
"MOV tmp.a, iPrC.a; # ignore secondary alpha\n"
"\n"
"MUL oCol, tmp, program.local[0]; # multiply by flicker factor\n"
"END\n";

fprintf(stdout, "Low-level Shaders Demo\n\n");

// Make sure required functionality is available!
if (!gltIsExtSupported("GL_ARB_vertex_program"))
{
fprintf(stderr, "GL_ARB_vertex_program extension is unavailable!\n");
Sleep(2000);
exit(0);
}
if (!gltIsExtSupported("GL_ARB_fragment_program"))
{
fprintf(stderr, "GL_ARB_fragment_program extension is unavailable!\n");
Sleep(2000);
exit(0);
}
version = glGetString(GL_VERSION);
if (((version[0] != '1') || (version[1] != '.') ||
(version[2] < '4') || (version[2] > '9')) && // 1.4+
(!gltIsExtSupported("GL_EXT_secondary_color")))
{
fprintf(stderr, "Neither OpenGL 1.4 nor GL_EXT_secondary_color"
" extension is available!\n");
Sleep(2000);
exit(0);
}

#ifndef __APPLE__
glGenProgramsARB = gltGetExtensionPointer("glGenProgramsARB");
glBindProgramARB = gltGetExtensionPointer("glBindProgramARB");
glProgramStringARB = gltGetExtensionPointer("glProgramStringARB");
glDeleteProgramsARB = gltGetExtensionPointer("glDeleteProgramsARB");
glProgramLocalParameter4fARB = gltGetExtensionPointer("glProgramLocalParameter4fARB");

if (gltIsExtSupported("GL_EXT_secondary_color"))
glSecondaryColor3f = gltGetExtensionPointer("glSecondaryColor3fEXT");
else
glSecondaryColor3f = gltGetExtensionPointer("glSecondaryColor3f");

if (!glGenProgramsARB || !glBindProgramARB || !glProgramStringARB ||
!glDeleteProgramsARB || !glProgramLocalParameter4fARB ||
!glSecondaryColor3f)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}
#endif

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
glSecondaryColor3f(1.0f, 1.0f, 1.0f);

// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

glShadeModel(GL_SMOOTH);

// Create, set and enable shaders
glGenProgramsARB(2, ids);

glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ids[0]);
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(vpString), vpString);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
if (errorPos != -1)
{
fprintf(stderr, "Error in vertex shader at position %d!\n", errorPos);
fprintf(stderr, "Error string: %s\n", glGetString(GL_PROGRAM_ERROR_STRING_ARB));
Sleep(5000);
exit(0);
}

glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ids[1]);
glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fpString), fpString);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
if (errorPos != -1)
{
fprintf(stderr, "Error in fragment shader at position %d!\n", errorPos);
fprintf(stderr, "Error string: %s\n", glGetString(GL_PROGRAM_ERROR_STRING_ARB));
Sleep(5000);
exit(0);
}

if (useVertexShader)
glEnable(GL_VERTEX_PROGRAM_ARB);
if (useFragmentShader)
glEnable(GL_FRAGMENT_PROGRAM_ARB);

// Initially set the blink parameter to 1 (no flicker)
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_A RB, 0, 1.0f, 1.0f, 1.0f, 1.0f);
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
useVertexShader = !useVertexShader;
if (useVertexShader)
{
glutChangeToMenuEntry(1, "Toggle vertex shader (currently ON)", 1);
glEnable(GL_VERTEX_PROGRAM_ARB);
}
else
{
glutChangeToMenuEntry(1, "Toggle vertex shader (currently OFF)", 1);
glDisable(GL_VERTEX_PROGRAM_ARB);
}
break;

case 2:
useFragmentShader = !useFragmentShader;
if (useFragmentShader)
{
glutChangeToMenuEntry(2, "Toggle fragment shader (currently ON)", 2);
glEnable(GL_FRAGMENT_PROGRAM_ARB);
}
else
{
glutChangeToMenuEntry(2, "Toggle fragment shader (currently OFF)", 2);
glDisable(GL_FRAGMENT_PROGRAM_ARB);
}
break;

case 3:
doBlink = !doBlink;
if (doBlink)
{
glutChangeToMenuEntry(3, "Toggle flicker (currently ON)", 3);
}
else
{
glutChangeToMenuEntry(3, "Toggle flicker (currently OFF)", 3);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_A RB, 0, 1.0f, 1.0f, 1.0f, 1.0f);
}
break;

default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'x':
cameraPos[0] += 5.0f;
break;
case 'X':
cameraPos[0] -= 5.0f;
break;
case 'y':
cameraPos[1] += 5.0f;
break;
case 'Y':
cameraPos[1] -= 5.0f;
break;
case 'z':
cameraPos[2] += 5.0f;
break;
case 'Z':
cameraPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
cameraPos[0] -= 5.0f;
break;
case GLUT_KEY_RIGHT:
cameraPos[0] += 5.0f;
break;
case GLUT_KEY_UP:
cameraPos[1] += 5.0f;
break;
case GLUT_KEY_DOWN:
cameraPos[1] -= 5.0f;
break;
default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
windowWidth = w;
windowHeight = h;
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Low-level Shaders Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle vertex shader (currently ON)", 1);
glutAddMenuEntry("Toggle fragment shader (currently ON)", 2);
glutAddMenuEntry("Toggle flicker (currently OFF)", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);

SetupRC();

glutMainLoop();

#ifndef __APPLE__
if (glDeleteProgramsARB)
glDeleteProgramsARB(2, ids);
#endif

return 0;
}

Admin
17th September 2008, 08:02 PM
با کیبورد می تونین این شکل رو خم و راست کنین.


// VertexBlending.c
// OpenGL SuperBible, Chapter 22
// Demonstrates vertex blending
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenGL Stuff
#include <stdio.h>

#ifndef __APPLE__
PFNGLPROGRAMSTRINGARBPROC glProgramStringARB;
PFNGLBINDPROGRAMARBPROC glBindProgramARB;
PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB;
PFNGLGENPROGRAMSARBPROC glGenProgramsARB;
PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glProgramLocalParameter4fvARB;
PFNGLVERTEXATTRIB1FARBPROC glVertexAttrib1fARB;
#endif

PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
PFNGLGETHANDLEARBPROC glGetHandleARB;
PFNGLDETACHOBJECTARBPROC glDetachObjectARB;
PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB;
PFNGLATTACHOBJECTARBPROC glAttachObjectARB;
PFNGLLINKPROGRAMARBPROC glLinkProgramARB;
PFNGLVALIDATEPROGRAMARBPROC glValidateProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB;
PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLUNIFORM3FVARBPROC glUniform3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC glUniformMatrix3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC glUniformMatrix4fvARB;
PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
PFNGLGETATTRIBLOCATIONARBPROC glGetAttribLocationARB;

GLboolean lowLevelAvailable = GL_FALSE;
GLboolean highLevelAvailable = GL_FALSE;
GLboolean useHighLevel = GL_FALSE;
GLboolean useBlending = GL_TRUE;
GLboolean showBones = GL_FALSE;

#define TOTAL_SHADERS 1
GLuint ids[TOTAL_SHADERS]; // low-level shader object names
GLhandleARB vShader[TOTAL_SHADERS], progObj[TOTAL_SHADERS]; // high-level shader object handles
GLboolean needsValidation[TOTAL_SHADERS];
char *shaderNames[TOTAL_SHADERS] = {"skinning"};

#define WEIGHT_SLOT 1 // locations for low-level attrib and program local parameters
#define LIGHT_POS_SLOT 0
#define MODELVIEW2_SLOT 1

GLint lightPosLoc, mv2Loc, mv2ITLoc; // locations for high-level uniforms
GLint weightLoc; // locations for high-level attribs

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLint mainMenu; // menu handles

GLint maxTexSize; // maximum allowed size for 1D/2D texture

GLfloat cameraPos[] = { 50.0f, 75.0f, 50.0f, 1.0f};
GLfloat lightPos[] = { -50.0f, 100.0f, 50.0f, 1.0f};

GLfloat elbowBend = 45.0f;
GLfloat sphereOfInfluence = 1.0f; // how much of each limb gets blended

#define MAX_INFO_LOG_SIZE 2048

// Create 1D texture to map NdotH to NdotH^128
GLvoid CreatePowMap(GLfloat r, GLfloat g, GLfloat b)
{
GLfloat texels[512 * 4];
GLint texSize = (maxTexSize > 512) ? 512 : maxTexSize;
GLint x;

for (x = 0; x < texSize; x++)
{
// Incoming N.H has been scaled by 8 and biased by -7 to take better
// advantage of the texture space. Otherwise, the texture will be
// entirely zeros until ~7/8 of the way into it. This way, we expand
// the useful 1/8 of the range and get better precision.
texels[x*4+0] = r * pow(((double)x / (double)(texSize-1)) * 0.125f + 0.875f, 128.0);
texels[x*4+1] = g * pow(((double)x / (double)(texSize-1)) * 0.125f + 0.875f, 128.0);
texels[x*4+2] = b * pow(((double)x / (double)(texSize-1)) * 0.125f + 0.875f, 128.0);
texels[x*4+3] = 1.0f;
}
// Make sure the first texel is exactly zero. Most
// incoming texcoords will clamp to this texel.
texels[0] = texels[1] = texels[2] = 0.0f;

glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, texSize, 0, GL_RGBA, GL_FLOAT, texels);
}

// Load shader from disk into a null-terminated string
GLubyte *LoadShaderText(const char *fileName)
{
GLubyte *shaderText = NULL;
GLint shaderLength = 0;
FILE *fp;

fp = fopen(fileName, "r");
if (fp != NULL)
{
while (fgetc(fp) != EOF)
{
shaderLength++;
}
rewind(fp);
shaderText = (GLubyte *)malloc(shaderLength+1);
if (shaderText != NULL)
{
fread(shaderText, 1, shaderLength, fp);
}
shaderText[shaderLength] = '\0';
fclose(fp);
}

return shaderText;
}

// Compile shaders
void PrepareShader(GLint shaderNum)
{
char fullFileName[255];
GLubyte *vsString;

// Create low-level shader objects and specify shader text
if (lowLevelAvailable)
{
GLint errorPos;

#ifdef __APPLE__
sprintf(fullFileName, "%s.vp", shaderNames[shaderNum]);
#else
sprintf(fullFileName, ".\\shaders\\%s.vp", shaderNames[shaderNum]);
#endif

vsString = LoadShaderText(fullFileName);
if (!vsString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ids[shaderNum]);
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(vsString), vsString);
free(vsString);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
if (errorPos != -1)
{
fprintf(stderr, "Error in low-level vertex shader #%d at position %d!\n", shaderNum, errorPos);
fprintf(stderr, "Error string: %s\n", glGetString(GL_PROGRAM_ERROR_STRING_ARB));
Sleep(5000);
exit(0);
}
}

// Create high-level shader objects and specify shader text
if (highLevelAvailable)
{
GLcharARB *vsStringPtr[1];
GLint success;

sprintf(fullFileName, ".\\shaders\\%s.vs", shaderNames[shaderNum]);
vsString = LoadShaderText(fullFileName);
if (!vsString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
vShader[shaderNum] = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
vsStringPtr[0] = vsString;
glShaderSourceARB(vShader[shaderNum], 1, vsStringPtr, NULL);
free(vsString);

// Compile shaders and check for any errors
glCompileShaderARB(vShader[shaderNum]);
glGetObjectParameterivARB(vShader[shaderNum], GL_OBJECT_COMPILE_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(vShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in high-level vertex shader #%d compilation!\n", shaderNum);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}

// Create program object, attach shader, then link
progObj[shaderNum] = glCreateProgramObjectARB();
glAttachObjectARB(progObj[shaderNum], vShader[shaderNum]);

glLinkProgramARB(progObj[shaderNum]);
glGetObjectParameterivARB(progObj[shaderNum], GL_OBJECT_LINK_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in high-level program #%d linkage!\n", shaderNum);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}

lightPosLoc = glGetUniformLocationARB(progObj[0], "lightPos");
mv2Loc = glGetUniformLocationARB(progObj[0], "mv2");
mv2ITLoc = glGetUniformLocationARB(progObj[0], "mv2IT");
weightLoc = glGetAttribLocationARB(progObj[0], "weight");

// Program object has changed, so we should revalidate
needsValidation[shaderNum] = GL_TRUE;
}
}

// Draw a cylinder with supplied dimensions
void DrawCylinder(GLfloat length, GLfloat diameter1, GLfloat diameter2,
GLfloat startWeight, GLfloat endWeight)
{
int numFacets = 50;
int numSections = 50;
GLfloat angleIncr = (2.0f * 3.14159f) / (float)numFacets;
GLfloat sectionLength = length / numSections;
GLfloat wEnd, influenceStart;
int i, j;

// Determine where our influence starts for this limb
if (startWeight == 0.5f)
{
influenceStart = sphereOfInfluence;
}
else
{
influenceStart = 1.0f - sphereOfInfluence;
}

// Skin
for (i = 0; i < numFacets; i++)
{
// Calculate geometry for this facet
GLfloat angle1 = i * angleIncr;
GLfloat angle2 = ((i+1)%numFacets) * angleIncr;
GLfloat y1AtFirstEnd = sin(angle1) * diameter1;
GLfloat y1AtOtherEnd = sin(angle1) * diameter2;
GLfloat z1AtFirstEnd = cos(angle1) * diameter1;
GLfloat z1AtOtherEnd = cos(angle1) * diameter2;
GLfloat y2AtFirstEnd = sin(angle2) * diameter1;
GLfloat y2AtOtherEnd = sin(angle2) * diameter2;
GLfloat z2AtFirstEnd = cos(angle2) * diameter1;
GLfloat z2AtOtherEnd = cos(angle2) * diameter2;
GLfloat n1y = y1AtFirstEnd;
GLfloat n1z = z1AtFirstEnd;
GLfloat n2y = y2AtFirstEnd;
GLfloat n2z = z2AtFirstEnd;

// One strip per facet
glBegin(GL_QUAD_STRIP);

glVertexAttrib1fARB(useHighLevel ? weightLoc : WEIGHT_SLOT,
useBlending ? startWeight : 1.0f);
glNormal3f(0.0f, n1y, n1z);
glVertex3f(0.0f, y1AtFirstEnd, z1AtFirstEnd);
glNormal3f(0.0f, n2y, n2z);
glVertex3f(0.0f, y2AtFirstEnd, z2AtFirstEnd);

for (j = 0; j < numSections; j++)
{
// Calculate geometry for end of this quad
GLfloat paramEnd = (float)(j+1) / (float)numSections;
GLfloat lengthEnd = paramEnd * length;
GLfloat y1End = y1AtFirstEnd + (paramEnd * (y1AtOtherEnd - y1AtFirstEnd));
GLfloat z1End = z1AtFirstEnd + (paramEnd * (z1AtOtherEnd - z1AtFirstEnd));
GLfloat y2End = y2AtFirstEnd + (paramEnd * (y2AtOtherEnd - y2AtFirstEnd));
GLfloat z2End = z2AtFirstEnd + (paramEnd * (z2AtOtherEnd - z2AtFirstEnd));

// Calculate vertex weights
if (!useBlending)
{
wEnd = 1.0f;
}
else if (paramEnd <= influenceStart)
{
// Map params [0,influenceStart] to weights [0,1]
GLfloat p = (paramEnd * (1.0f/influenceStart));

// We're in the first half of the cylinder: startWeight -> 1
wEnd = startWeight + p * (1.0f - startWeight);
}
else
{
// Map params [influenceStart,1] to weights [0,1]
GLfloat p = (paramEnd-influenceStart) * (1.0f/(1.0f-influenceStart));

// We're in the second half of the cylinder: 1 -> endWeight
wEnd = 1.0f + p * (endWeight - 1.0f);
}

glVertexAttrib1fARB(useHighLevel ? weightLoc : WEIGHT_SLOT, wEnd);
glNormal3f(0.0f, n1y, n1z);
glVertex3f(lengthEnd, y1End, z1End);
glNormal3f(0.0f, n2y, n2z);
glVertex3f(lengthEnd, y2End, z2End);
}

// End facet strip
glEnd();
}

if (showBones)
{
// Skeleton
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glColor4f(1.0f, 1.0f, 1.0f, 0.75f);
glNormal3f(0.0f, 1.0f, 0.0f);
glVertexAttrib1fARB(useHighLevel ? weightLoc : WEIGHT_SLOT, 1.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(length, 0.0f, 0.0f);
glEnd();
glColor3f(1.0f, 1.0f, 0.0f);
glBegin(GL_POINTS);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(length, 0.0f, 0.0f);
glEnd();
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
}
}

// Called to draw scene objects
void DrawModels(void)
{
GLTVector3 lightPosEye;
GLTMatrix mv, mv2;

// Transform light position to eye space
glGetFloatv(GL_MODELVIEW_MATRIX, mv);
gltTransformPoint(lightPos, mv, lightPosEye);

if (useHighLevel)
{
glUniform3fvARB(lightPosLoc, 1, lightPosEye);
}
else
{
glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_AR B, LIGHT_POS_SLOT, lightPosEye);
}

// Setup modelview matrices for upper arm
glPushMatrix();
glRotatef(elbowBend, 0.0f, 0.0f, 1.0f);
glTranslatef(-50.0f, 0.0f, 0.0f);
glGetFloatv(GL_MODELVIEW_MATRIX, mv2);
glPopMatrix();
glTranslatef(-50.0f, 0.0f, 0.0f);

if (useHighLevel)
{
GLTMatrix mv2IT_4x4;
GLfloat mv2IT_3x3[9];
GLint i;

glUniformMatrix4fvARB(mv2Loc, 1, GL_FALSE, mv2);

gltInvertMatrix(mv2, mv2IT_4x4);

// Take upper left 3x3 for 2nd normal matrix
for (i = 0; i < 9; i++)
{
mv2IT_3x3[i] = mv2IT_4x4[((i/3)*4)+(i%3)];
}
glUniformMatrix3fvARB(mv2ITLoc, 1, GL_TRUE, mv2IT_3x3);
}
else
{
glMatrixMode(GL_MATRIX0_ARB);
glLoadMatrixf(mv2);
glMatrixMode(GL_MODELVIEW);
}

// Draw upper arm cylinder
glColor3f(0.0f, 0.0f, 0.90f); // Blue
// 50 long, 10 shoulder, 9 elbow, with weights applied to second half
DrawCylinder(50.0f, 15.0f, 9.0f, 1.0f, 0.5f);

// Setup modelview matrices for forearm
glTranslatef(50.0f, 0.0f, 0.0f);
glPushMatrix();
glGetFloatv(GL_MODELVIEW_MATRIX, mv2);
glPopMatrix();
glRotatef(elbowBend, 0.0f, 0.0f, 1.0f);

if (useHighLevel)
{
GLTMatrix mv2IT_4x4;
GLfloat mv2IT_3x3[9];
GLint i;

glUniformMatrix4fvARB(mv2Loc, 1, GL_FALSE, mv2);

gltInvertMatrix(mv2, mv2IT_4x4);

// Take upper left 3x3 for 2nd normal matrix
for (i = 0; i < 9; i++)
{
mv2IT_3x3[i] = mv2IT_4x4[((i/3)*4)+(i%3)];
}
glUniformMatrix3fvARB(mv2ITLoc, 1, GL_TRUE, mv2IT_3x3);
}
else
{
glMatrixMode(GL_MATRIX0_ARB);
glLoadMatrixf(mv2);
glMatrixMode(GL_MODELVIEW);
}

// Draw forearm cylinder
glColor3f(0.9f, 0.0f, 0.0f); // Red
// 40 long, 9 elbow, 5 wrist, with weights applied to first half
DrawCylinder(40.0f, 9.0f, 5.0f, 0.5f, 1.0f);
}

// Called to draw scene
void RenderScene(void)
{
// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glViewport(0, 0, windowWidth, windowHeight);

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Validate our shader before first use
if (needsValidation[0])
{
GLint success;

glValidateProgramARB(progObj[0]);
glGetObjectParameterivARB(progObj[0], GL_OBJECT_VALIDATE_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj[0], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in program validation!\n");
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}

needsValidation[0] = GL_FALSE;
}

// Draw objects in the scene
DrawModels();

if (glGetError() != GL_NO_ERROR)
fprintf(stderr, "GL Error!\n");

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
const GLubyte *version;
GLint i;

fprintf(stdout, "Vertex Blending Demo\n\n");

// Make sure required functionality is available!
if (gltIsExtSupported("GL_ARB_vertex_shader") &&
gltIsExtSupported("GL_ARB_shader_objects") &&
gltIsExtSupported("GL_ARB_shading_language_100"))
{
highLevelAvailable = GL_TRUE;
}
if (gltIsExtSupported("GL_ARB_vertex_program"))
{
lowLevelAvailable = GL_TRUE;
}
if (!lowLevelAvailable && !highLevelAvailable)
{
fprintf(stderr, "Neither vertex shader"
" extension is available!\n");
Sleep(2000);
exit(0);
}

// Make sure we have multitexture, cube maps, and texenv add!
version = glGetString(GL_VERSION);
if (((version[0] != '1') || (version[1] != '.') ||
(version[2] < '3') || (version[2] > '9')) && // 1.3+
(!gltIsExtSupported("GL_ARB_multitexture") ||
!gltIsExtSupported("GL_ARB_texture_env_add")))
{
fprintf(stderr, "Neither OpenGL 1.3 nor necessary"
" extensions are available!\n");
Sleep(2000);
exit(0);
}

glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize);

if (lowLevelAvailable)
{
#ifndef __APPLE__
glGenProgramsARB = gltGetExtensionPointer("glGenProgramsARB");
glBindProgramARB = gltGetExtensionPointer("glBindProgramARB");
glProgramStringARB = gltGetExtensionPointer("glProgramStringARB");
glDeleteProgramsARB = gltGetExtensionPointer("glDeleteProgramsARB");
glProgramLocalParameter4fARB = gltGetExtensionPointer("glProgramLocalParameter4fARB");
glProgramLocalParameter4fvARB = gltGetExtensionPointer("glProgramLocalParameter4fvARB");
glVertexAttrib1fARB = gltGetExtensionPointer("glVertexAttrib1fARB");

if (!glGenProgramsARB || !glBindProgramARB ||
!glProgramStringARB || !glDeleteProgramsARB ||
!glProgramLocalParameter4fARB ||
!glProgramLocalParameter4fvARB || !glVertexAttrib1fARB)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}
#endif
}

if (highLevelAvailable)
{
glCreateShaderObjectARB = gltGetExtensionPointer("glCreateShaderObjectARB");
glCreateProgramObjectARB = gltGetExtensionPointer("glCreateProgramObjectARB");
glAttachObjectARB = gltGetExtensionPointer("glAttachObjectARB");
glDetachObjectARB = gltGetExtensionPointer("glDetachObjectARB");
glDeleteObjectARB = gltGetExtensionPointer("glDeleteObjectARB");
glShaderSourceARB = gltGetExtensionPointer("glShaderSourceARB");
glCompileShaderARB = gltGetExtensionPointer("glCompileShaderARB");
glLinkProgramARB = gltGetExtensionPointer("glLinkProgramARB");
glValidateProgramARB = gltGetExtensionPointer("glValidateProgramARB");
glUseProgramObjectARB = gltGetExtensionPointer("glUseProgramObjectARB");
glGetObjectParameterivARB = gltGetExtensionPointer("glGetObjectParameterivARB");
glGetInfoLogARB = gltGetExtensionPointer("glGetInfoLogARB");
glUniform3fvARB = gltGetExtensionPointer("glUniform3fvARB");
glUniformMatrix3fvARB = gltGetExtensionPointer("glUniformMatrix3fvARB");
glUniformMatrix4fvARB = gltGetExtensionPointer("glUniformMatrix4fvARB");
#ifndef __APPLE__
glVertexAttrib1fARB = gltGetExtensionPointer("glVertexAttrib1fARB");
#endif
glGetUniformLocationARB = gltGetExtensionPointer("glGetUniformLocationARB");
glGetAttribLocationARB = gltGetExtensionPointer("glGetAttribLocationARB");

if (!glCreateShaderObjectARB || !glCreateProgramObjectARB ||
!glAttachObjectARB || !glDetachObjectARB || !glDeleteObjectARB ||
!glShaderSourceARB || !glCompileShaderARB || !glLinkProgramARB ||
!glValidateProgramARB || !glUseProgramObjectARB ||
!glGetObjectParameterivARB || !glGetInfoLogARB ||
!glUniformMatrix4fvARB || !glUniformMatrix4fvARB ||
!glUniform3fvARB ||
#ifndef __APPLE__
!glVertexAttrib1fARB ||
#endif
!glGetUniformLocationARB || !glGetAttribLocationARB)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}

useHighLevel = GL_TRUE;
}

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tL/R arrows\tChange sphere of influence\n");
fprintf(stdout, "\tU/D arrows\tChange angle of forearm\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

// Misc.
glShadeModel(GL_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPointSize(10.0f);
glLineWidth(5.0f);

// Texture state
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
glBindTexture(GL_TEXTURE_1D, 0);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
CreatePowMap(1.0, 1.0, 1.0);
glEnable(GL_TEXTURE_1D);

if (lowLevelAvailable)
{
glGenProgramsARB(TOTAL_SHADERS, ids);
// Low-level will always be enabled, but high-level
// will take precedence if they're both enabled
glEnable(GL_VERTEX_PROGRAM_ARB);
}

// Load and compile low- and high-level shaders
for (i = 0; i < TOTAL_SHADERS; i++)
{
PrepareShader(i);
}

// Install first shader
if (lowLevelAvailable)
{
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ids[0]);
}
if (useHighLevel)
{
glUseProgramObjectARB(progObj[0]);
}
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
useBlending = !useBlending;
if (useBlending)
{
glutChangeToMenuEntry(1, "Toggle vertex blending (currently ON)", 1);
}
else
{
glutChangeToMenuEntry(1, "Toggle vertex blending (currently OFF)", 1);
}
break;

case 2:
showBones = !showBones;
if (showBones)
{
glutChangeToMenuEntry(2, "Show bones (currently ON)", 2);
}
else
{
glutChangeToMenuEntry(2, "Show bones (currently OFF)", 2);
}
break;

case 3:
useHighLevel = !useHighLevel;
if (useHighLevel)
{
glutChangeToMenuEntry(3, "Switch to low-level vertex shader", 3);
glUseProgramObjectARB(progObj[0]);
}
else
{
glutChangeToMenuEntry(3, "Switch to high-level vertex shader", 3);
glUseProgramObjectARB(0);
}
break;

default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'x':
cameraPos[0] += 5.0f;
break;
case 'X':
cameraPos[0] -= 5.0f;
break;
case 'y':
cameraPos[1] += 5.0f;
break;
case 'Y':
cameraPos[1] -= 5.0f;
break;
case 'z':
cameraPos[2] += 5.0f;
break;
case 'Z':
cameraPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
sphereOfInfluence -= 0.05f;
if (sphereOfInfluence < 0.05f)
sphereOfInfluence = 0.0f;
break;
case GLUT_KEY_RIGHT:
sphereOfInfluence += 0.05f;
if (sphereOfInfluence > 0.95f)
sphereOfInfluence = 1.0f;
break;
case GLUT_KEY_UP:
elbowBend += 5.0f;
if (elbowBend > 150.0f)
elbowBend = 150.0f;
break;
case GLUT_KEY_DOWN:
elbowBend -= 5.0f;
if (elbowBend < -150.0f)
elbowBend = -150.0f;
break;
default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
windowWidth = w;
windowHeight = h;
}

int main(int argc, char* argv[])
{
GLint i;

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Vertex Blending Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

SetupRC();

// Create the menus
mainMenu = glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Toggle vertex blending (currently ON)", 1);
glutAddMenuEntry("Show bones (currently OFF)", 2);
if (lowLevelAvailable && highLevelAvailable)
{
if (useHighLevel)
{
glutAddMenuEntry("Switch to low-level vertex shader", 3);
}
else
{
glutAddMenuEntry("Switch to high-level vertex shader", 3);
}
}
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMainLoop();

if (glDeleteObjectARB)
{
for (i = 0; i < TOTAL_SHADERS; i++)
{
glDeleteObjectARB(progObj[i]);
glDeleteObjectARB(vShader[i]);
}
}

#ifndef __APPLE__
if (glDeleteProgramsARB)
{
glDeleteProgramsARB(TOTAL_SHADERS, ids);
}
#endif

return 0;
}

Admin
17th September 2008, 08:03 PM
با راست کلیک بر روی صفحه می تونین حالات مختلف توپ رو مشخص کنین.


// ProceduralTex.c
// OpenGL SuperBible, Chapter 23
// Demonstrates procedural texture mapping
// Program by Benjamin Lipchak

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenGL Stuff
#include <stdio.h>

#ifndef __APPLE__
PFNGLPROGRAMSTRINGARBPROC glProgramStringARB;
PFNGLBINDPROGRAMARBPROC glBindProgramARB;
PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB;
PFNGLGENPROGRAMSARBPROC glGenProgramsARB;
PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glProgramLocalParameter4fvARB;
#endif

PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
PFNGLGETHANDLEARBPROC glGetHandleARB;
PFNGLDETACHOBJECTARBPROC glDetachObjectARB;
PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB;
PFNGLATTACHOBJECTARBPROC glAttachObjectARB;
PFNGLLINKPROGRAMARBPROC glLinkProgramARB;
PFNGLVALIDATEPROGRAMARBPROC glValidateProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB;
PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLUNIFORM1FARBPROC glUniform1fARB;
PFNGLUNIFORM1FARBPROC glUniform1iARB;
PFNGLUNIFORM3FVARBPROC glUniform3fvARB;
PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;

GLboolean lowLevelAvailable = GL_FALSE;
GLboolean highLevelAvailable = GL_FALSE;
GLboolean useHighLevel = GL_FALSE;

#define CHECKERBOARD 0
#define BEACHBALL 1
#define TOYBALL 2
#define TOTAL_SHADER_SETS 3

GLuint v_ids[TOTAL_SHADER_SETS]; // low-level shader object names
GLuint f_ids[TOTAL_SHADER_SETS];
GLhandleARB fShader[TOTAL_SHADER_SETS]; // high-level shader object handles
GLhandleARB vShader[TOTAL_SHADER_SETS];
GLhandleARB progObj[TOTAL_SHADER_SETS];
GLboolean needsValidation[TOTAL_SHADER_SETS];
char *shaderNames[TOTAL_SHADER_SETS] = {"checkerboard", "beachball", "toyball"};

GLint whichShader = CHECKERBOARD; // current shader

#define LIGHTPOS_SLOT 0 // locations for low-level program local parameters

GLint windowWidth = 512; // window size
GLint windowHeight = 512;

GLint mainMenu, shaderMenu; // menu handles

GLfloat cameraPos[] = { 50.0f, 50.0f, 150.0f, 1.0f};
GLfloat lightPos[] = { 140.0f, 250.0f, 140.0f, 1.0f};

GLfloat lightRotation = 0.0f;
GLint tess = 75;

#define MAX_INFO_LOG_SIZE 2048

// Load shader from disk into a null-terminated string
GLubyte *LoadShaderText(const char *fileName)
{
GLubyte *shaderText = NULL;
GLint shaderLength = 0;
FILE *fp;

fp = fopen(fileName, "r");
if (fp != NULL)
{
while (fgetc(fp) != EOF)
{
shaderLength++;
}
rewind(fp);
shaderText = (GLubyte *)malloc(shaderLength+1);
if (shaderText != NULL)
{
fread(shaderText, 1, shaderLength, fp);
}
shaderText[shaderLength] = '\0';
fclose(fp);
}

return shaderText;
}

// Compile shaders
void PrepareShader(GLint shaderNum)
{
char fullFileName[255];
GLubyte *shString;

// Create low-level shader objects and specify shader text
if (lowLevelAvailable)
{
GLint errorPos;

#ifdef __APPLE__
sprintf(fullFileName, "%s.vp", shaderNames[shaderNum]);
#else
sprintf(fullFileName, ".\\shaders\\%s.vp", shaderNames[shaderNum]);
#endif
shString = LoadShaderText(fullFileName);
if (!shString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, v_ids[shaderNum]);
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(shString), shString);
free(shString);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
if (errorPos != -1)
{
fprintf(stderr, "Error in low-level vertex shader #%d at position %d!\n", shaderNum, errorPos);
fprintf(stderr, "Error string: %s\n", glGetString(GL_PROGRAM_ERROR_STRING_ARB));
Sleep(5000);
exit(0);
}

#ifdef __APPLE__
sprintf(fullFileName, "%s.fp", shaderNames[shaderNum]);
#else
sprintf(fullFileName, ".\\shaders\\%s.fp", shaderNames[shaderNum]);
#endif
shString = LoadShaderText(fullFileName);
if (!shString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, f_ids[shaderNum]);
glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(shString), shString);
free(shString);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
if (errorPos != -1)
{
fprintf(stderr, "Error in low-level fragment shader #%d at position %d!\n", shaderNum, errorPos);
fprintf(stderr, "Error string: %s\n", glGetString(GL_PROGRAM_ERROR_STRING_ARB));
Sleep(5000);
exit(0);
}
}

// Create high-level shader objects and specify shader text
if (highLevelAvailable)
{
GLcharARB *shStringPtr[1];
GLint success;

#ifdef __APPLE__
sprintf(fullFileName, "%s.vs", shaderNames[shaderNum]);
#else
sprintf(fullFileName, ".\\shaders\\%s.vs", shaderNames[shaderNum]);
#endif
shString = LoadShaderText(fullFileName);
if (!shString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
vShader[shaderNum] = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
shStringPtr[0] = shString;
glShaderSourceARB(vShader[shaderNum], 1, shStringPtr, NULL);
free(shString);

// Compile shaders and check for any errors
glCompileShaderARB(vShader[shaderNum]);
glGetObjectParameterivARB(vShader[shaderNum], GL_OBJECT_COMPILE_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(vShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in high-level vertex shader #%d compilation!\n", shaderNum);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}

#ifdef __APPLE__
sprintf(fullFileName, "%s.fs", shaderNames[shaderNum]);
#else
sprintf(fullFileName, ".\\shaders\\%s.fs", shaderNames[shaderNum]);
#endif
shString = LoadShaderText(fullFileName);
if (!shString)
{
fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
Sleep(5000);
exit(0);
}
fShader[shaderNum] = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
shStringPtr[0] = shString;
glShaderSourceARB(fShader[shaderNum], 1, shStringPtr, NULL);
free(shString);

// Compile shaders and check for any errors
glCompileShaderARB(fShader[shaderNum]);
glGetObjectParameterivARB(fShader[shaderNum], GL_OBJECT_COMPILE_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(fShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in high-level fragment shader #%d compilation!\n", shaderNum);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}
else
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(fShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
//fprintf(stderr, "High-level fragment shader #%d info log: %s\n", shaderNum, infoLog);
}

// Create program object, attach shader, then link
progObj[shaderNum] = glCreateProgramObjectARB();
glAttachObjectARB(progObj[shaderNum], vShader[shaderNum]);
glAttachObjectARB(progObj[shaderNum], fShader[shaderNum]);

glLinkProgramARB(progObj[shaderNum]);
glGetObjectParameterivARB(progObj[shaderNum], GL_OBJECT_LINK_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in high-level program #%d linkage!\n", shaderNum);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}
else
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
//fprintf(stderr, "High-level program #%d info log: %s\n", shaderNum, infoLog);
}

// Program object has changed, so we should revalidate
needsValidation[shaderNum] = GL_TRUE;
}
}

// Called to draw scene objects
void DrawModels(void)
{
GLTVector3 lightPosEye;
GLTMatrix mv;

// Transform light position to eye space
glPushMatrix();
glRotatef(lightRotation, 0.0, 1.0, 0.0);
glGetFloatv(GL_MODELVIEW_MATRIX, mv);
gltTransformPoint(lightPos, mv, lightPosEye);
glPopMatrix();

if (useHighLevel)
{
GLint uniformLoc = glGetUniformLocationARB(progObj[whichShader], "lightPos");
if (uniformLoc != -1)
{
glUniform3fvARB(uniformLoc, 1, lightPosEye);
}
}
else
{
glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_AR B, LIGHTPOS_SLOT, lightPosEye);
}

// Draw sphere
glutSolidSphere(50.0f, tess, tess);
}

// Called to draw scene
void RenderScene(void)
{
// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Validate our shader before first use
if (needsValidation[whichShader])
{
GLint success;

glValidateProgramARB(progObj[whichShader]);
glGetObjectParameterivARB(progObj[whichShader], GL_OBJECT_VALIDATE_STATUS_ARB, &success);
if (!success)
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj[whichShader], MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in program #%d validation!\n", whichShader);
fprintf(stderr, "Info log: %s\n", infoLog);
Sleep(10000);
exit(0);
}

needsValidation[whichShader] = GL_FALSE;
}

// Draw objects in the scene
DrawModels();

if (glGetError() != GL_NO_ERROR)
fprintf(stderr, "GL Error!\n");

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLint i;

fprintf(stdout, "Procedural Texture Mapping Demo\n\n");

// Make sure required functionality is available!
if (gltIsExtSupported("GL_ARB_fragment_shader") &&
gltIsExtSupported("GL_ARB_vertex_shader") &&
gltIsExtSupported("GL_ARB_shader_objects") &&
gltIsExtSupported("GL_ARB_shading_language_100"))
{
highLevelAvailable = GL_TRUE;
}
if (gltIsExtSupported("GL_ARB_fragment_program") &&
gltIsExtSupported("GL_ARB_vertex_program"))
{
lowLevelAvailable = GL_TRUE;
}
if (!lowLevelAvailable && !highLevelAvailable)
{
fprintf(stderr, "Neither set of shader"
" extensions is available!\n");
Sleep(2000);
exit(0);
}

#ifndef __APPLE__
if (lowLevelAvailable)
{
glGenProgramsARB = gltGetExtensionPointer("glGenProgramsARB");
glBindProgramARB = gltGetExtensionPointer("glBindProgramARB");
glProgramStringARB = gltGetExtensionPointer("glProgramStringARB");
glDeleteProgramsARB = gltGetExtensionPointer("glDeleteProgramsARB");
glProgramLocalParameter4fARB = gltGetExtensionPointer("glProgramLocalParameter4fARB");
glProgramLocalParameter4fvARB = gltGetExtensionPointer("glProgramLocalParameter4fvARB");

if (!glGenProgramsARB || !glBindProgramARB ||
!glProgramStringARB || !glDeleteProgramsARB ||
!glProgramLocalParameter4fvARB ||
!glProgramLocalParameter4fARB)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}
}
#endif

if (highLevelAvailable)
{
glCreateShaderObjectARB = gltGetExtensionPointer("glCreateShaderObjectARB");
glCreateProgramObjectARB = gltGetExtensionPointer("glCreateProgramObjectARB");
glAttachObjectARB = gltGetExtensionPointer("glAttachObjectARB");
glDetachObjectARB = gltGetExtensionPointer("glDetachObjectARB");
glDeleteObjectARB = gltGetExtensionPointer("glDeleteObjectARB");
glShaderSourceARB = gltGetExtensionPointer("glShaderSourceARB");
glCompileShaderARB = gltGetExtensionPointer("glCompileShaderARB");
glLinkProgramARB = gltGetExtensionPointer("glLinkProgramARB");
glValidateProgramARB = gltGetExtensionPointer("glValidateProgramARB");
glUseProgramObjectARB = gltGetExtensionPointer("glUseProgramObjectARB");
glGetObjectParameterivARB = gltGetExtensionPointer("glGetObjectParameterivARB");
glGetInfoLogARB = gltGetExtensionPointer("glGetInfoLogARB");
glUniform1fARB = gltGetExtensionPointer("glUniform1fARB");
glUniform1iARB = gltGetExtensionPointer("glUniform1iARB");
glUniform3fvARB = gltGetExtensionPointer("glUniform3fvARB");
glGetUniformLocationARB = gltGetExtensionPointer("glGetUniformLocationARB");

if (!glCreateShaderObjectARB || !glCreateProgramObjectARB ||
!glAttachObjectARB || !glDetachObjectARB || !glDeleteObjectARB ||
!glShaderSourceARB || !glCompileShaderARB || !glLinkProgramARB ||
!glValidateProgramARB || !glUseProgramObjectARB ||
!glGetObjectParameterivARB || !glGetInfoLogARB ||
!glUniform3fvARB || !glUniform1fARB ||
!glUniform1iARB || !glGetUniformLocationARB)
{
fprintf(stderr, "Not all entrypoints were available!\n");
Sleep(2000);
exit(0);
}

useHighLevel = GL_TRUE;
}

fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tR/L arrows\t+/- rotate light\n\n");
fprintf(stdout, "\tU/D arrows\t+/- increase/decrease tesselation\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");

// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Misc. state
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);

if (lowLevelAvailable)
{
glGenProgramsARB(TOTAL_SHADER_SETS, v_ids);
glGenProgramsARB(TOTAL_SHADER_SETS, f_ids);
// Low-level will always be enabled, but high-level
// will take precedence if they're both enabled
glEnable(GL_VERTEX_PROGRAM_ARB);
glEnable(GL_FRAGMENT_PROGRAM_ARB);
}

// Load and compile low- and high-level shaders
for (i = 0; i < TOTAL_SHADER_SETS; i++)
{
PrepareShader(i);
}

// Install first shader
if (lowLevelAvailable)
{
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, v_ids[0]);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, f_ids[0]);
}
if (useHighLevel)
{
glUseProgramObjectARB(progObj[whichShader]);
}
}

void ProcessMenu(int value)
{
switch(value)
{
case 1:
useHighLevel = !useHighLevel;
if (useHighLevel)
{
glutChangeToMenuEntry(2, "Switch to low-level shaders", 1);
glUseProgramObjectARB(progObj[whichShader]);
}
else
{
glutChangeToMenuEntry(2, "Switch to high-level shaders", 1);
glUseProgramObjectARB(0);
}
break;

default:
whichShader = value - 2;
{
char menuEntry[128];
sprintf(menuEntry, "Choose shader set (currently \"%s\")", shaderNames[whichShader]);
glutSetMenu(mainMenu);
glutChangeToSubMenu(1, menuEntry, shaderMenu);
}
if (lowLevelAvailable)
{
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, v_ids[whichShader]);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, f_ids[whichShader]);
}
if (useHighLevel)
{
glUseProgramObjectARB(progObj[whichShader]);
}
break;
}

// Refresh the Window
glutPostRedisplay();
}

void KeyPressFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'x':
cameraPos[0] += 5.0f;
break;
case 'X':
cameraPos[0] -= 5.0f;
break;
case 'y':
cameraPos[1] += 5.0f;
break;
case 'Y':
cameraPos[1] -= 5.0f;
break;
case 'z':
cameraPos[2] += 5.0f;
break;
case 'Z':
cameraPos[2] -= 5.0f;
break;
case 'q':
case 'Q':
case 27 : /* ESC */
exit(0);
}

// Refresh the Window
glutPostRedisplay();
}

void SpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
lightRotation -= 5.0f;
break;
case GLUT_KEY_RIGHT:
lightRotation += 5.0f;
break;
case GLUT_KEY_UP:
tess += 5;
break;
case GLUT_KEY_DOWN:
tess -= 5;
if (tess < 5) tess = 5;
break;
default:
break;
}

// Refresh the Window
glutPostRedisplay();
}

void ChangeSize(int w, int h)
{
windowWidth = w;
windowHeight = h;
glViewport(0, 0, windowWidth, windowHeight);
}

int main(int argc, char* argv[])
{
GLint i;

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Lighting Demo");
glutReshapeFunc(ChangeSize);
glutKeyboardFunc(KeyPressFunc);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

SetupRC();

// Create the menus
shaderMenu = glutCreateMenu(ProcessMenu);
for (i = 0; i < TOTAL_SHADER_SETS; i++)
{
char menuEntry[128];
sprintf(menuEntry, "\"%s\"", shaderNames[i]);
glutAddMenuEntry(menuEntry, 2+i);
}

mainMenu = glutCreateMenu(ProcessMenu);
{
char menuEntry[128];
sprintf(menuEntry, "Choose fragment shader (currently \"%s\")", shaderNames[0]);
glutAddSubMenu(menuEntry, shaderMenu);
}
if (lowLevelAvailable && highLevelAvailable)
{
if (useHighLevel)
{
glutAddMenuEntry("Switch to low-level shaders", 1);
}
else
{
glutAddMenuEntry("Switch to high-level shaders", 1);
}
}
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMainLoop();

if (glDeleteObjectARB)
{
for (i = 0; i < TOTAL_SHADER_SETS; i++)
{
glDeleteObjectARB(progObj[i]);
glDeleteObjectARB(vShader[i]);
glDeleteObjectARB(fShader[i]);
}
}

#ifndef __APPLE__
if (glDeleteProgramsARB)
{
glDeleteProgramsARB(TOTAL_SHADER_SETS, v_ids);
glDeleteProgramsARB(TOTAL_SHADER_SETS, f_ids);
}
#endif

return 0;
}

Admin
17th September 2008, 08:05 PM
با کیبورد میشه شی مشخص در تصویر رو چرخوند.


/**************************************************
* LightTorus.c
*
* Program to demonstrate how to add lighting
* and material properties to a torus.
* This program extends the program WrapTorus.
*
* The triangles or quadrilaterals are wrapped around the
* torus in a single long strip. See figure 13 in chapter I
* in the book mentioned below.
*
*
* Author: Samuel R. Buss
*
* Software accompanying the book
* 3D Computer Graphics: A Mathematical Introduction with OpenGL,
* by S. Buss, Cambridge University Press, 2003.
*
* Software is "as-is" and carries no warranty. It may be used without
* restriction, but if you modify it, please change the filenames to
* prevent confusion between different versions.
* Bug reports: Sam Buss, sbuss@ucsd.edu.
* Web page: http://math.ucsd.edu/~sbuss/MathCG
*
* USAGES: There are a number of keyboard commands that control
* the animation. They must be typed into the graphics window,
* and are listed below:
*
* CONTROLLING RESOLUTION OF THE TORUS MESH
* Press "W" to increase the number wraps.
* Press "w" to decrease the number wraps.
* Press "N" to increase the number of segments per wrap.
* Press "n" to decrease the number of segments per wrap.
* Press "q" to toggle between quadrangles and triangles.
*
* CONTROLLING THE ANIMATION:
* Press the "a" key to toggle the animation off and on.
* Press the "s" key to perform a single step of the animation.
* The left and right arrow keys controls the
* rate of rotation around the y-axis.
* The up and down arrow keys increase and decrease the rate of
* rotation around the x-axis. In order to reverse rotational
* direction you must zero or reset the torus ("0" or "r").
* Press the "r" key to reset the torus back to initial
* position, with no rotation.
* Press "0" (zero) to zero the rotation rates.
*
* CONTROLLING LIGHTS
* Press '1' or '2' to toggle the first or second light off and on.
* Press 'f' to toggle between flat and smooth shading.
* Press 'l' to toggle local modes on and off (local viewer and positional light,
* or non-local viewer and directional light).
*
* COMMANDS SHOWING OPENGL FEATURES:
* Pressing "p" toggles between wireframe and polygon mode.
* Pressing "f" key toggles between flat and smooth shading.
*
**/

#include <stdlib.h>
#include "LightTorus.h"
#include <math.h>
#include <limits.h>
#include <GL/glut.h> // OpenGL Graphics Utility Library

const float PI2 = 2.0f*3.1415926535;

GLenum runMode = GL_TRUE;

GLenum shadeModel = GL_FLAT; // Toggles between GL_FLAT and GL_SMOOTH
GLenum polygonMode = GL_LINE; // Toggles between GL_LINE and GL_FILL

// Variables controlling the animation
float RotX = 0.0f; // Rotational position around x-axis
float RotY = 0.0f; // Rotational position around y-axis
float RotIncrementX = 0.0; // Rotational increment, x-axis
float RotIncrementY = 0.0; // Rotational increment, y-axis
const float RotIncFactor = 1.5; // Factor change in rot rate per key stroke

// Variables controlling the fineness of the polygonal mesh
int NumWraps = 10;
int NumPerWrap = 8;

// Variables controlling the size of the torus
float MajorRadius = 3.0;
float MinorRadius = 1.0;

// Mode flags
int QuadMode = 1; // Quad/Triangle toggling
GLenum LocalMode = GL_TRUE; // Local viewer/non-local viewer mode
int Light0Flag = 1; // Is light #0 on?
int Light1Flag = 1; // Is light #1 on?

// Lighting values
float ambientLight[4] = {0.6, 0.6, 0.6, 1.0};
float Lt0amb[4] = {0.8, 0.8, 0.16, 1.0};
float Lt0diff[4] = {1.0, 1.0, 0.2, 1.0};
float Lt0spec[4] = {1.0, 1.0, 0.2, 1.0};
float Lt0pos[4] = {1.7*4.0, 0.0, 0.0, 1.0}; // 4 = MajorRadius + MinorRadius

float Lt1amb[4] = {0.0, 0.0, 0.5, 1.0};
float Lt1diff[4] = {0.0, 0.0, 0.5, 1.0};
float Lt1spec[4] = {0.0, 0.0, 1.0, 1.0};
float Lt1pos[4] = {0.0, 1.2*4.0, 0.0, 1.0};

// Material values
float Noemit[4] = {0.0, 0.0, 0.0, 1.0};
float Matspec[4] = {1.0, 1.0, 1.0, 1.0};
float Matnonspec[4] = {0.4, 0.05, 0.4, 1.0};
float Matshiny = 16.0;

// glutKeyboardFunc is called below to set this function to handle
// all "normal" key presses.
void myKeyboardFunc( unsigned char key, int x, int y )
{
switch ( key ) {
case 'a':
runMode = !runMode;
break;
case 's':
runMode = GL_TRUE;
updateScene();
runMode = GL_FALSE;
break;
case 27: // Escape key
exit(1);
case 'r': // Reset the animation (resets everything)
ResetAnimation();
break;
case '0': // Zero the rotation rates
ZeroRotation();
break;
case 'f': // Shade mode toggles from flat to smooth
ShadeModelToggle();
break;
case 'p': // Polygon mode toggles between fill and line
FillModeToggle();
break;
case 'w': // Decrement number of wraps around torus
WrapLess();
break;
case 'W': // Increment number of wraps around torus
WrapMore();
break;
case 'n': // Decrement number of polys per wrap
NumPerWrapLess();
break;
case 'N': // Increment number of polys per wrap
NumPerWrapMore();
break;
case 'q': // Toggle between triangles and Quadrilaterals
QuadTriangleToggle();
break;
case 'l': // Toggle between local and non-local viewer ('l' is for 'local')
LocalToggle();
break;
case '1': // Toggle light #0 on and off
Light0Toggle();
break;
case '2': // Toggle light #1 on and off
Light1Toggle();
break;
}
}

// glutSpecialFunc is called below to set this function to handle
// all "special" key presses. See glut.h for the names of
// special keys.
void mySpecialKeyFunc( int key, int x, int y )
{
switch ( key ) {
case GLUT_KEY_UP:
// Either increase upward rotation, or slow downward rotation
KeyUp();
break;
case GLUT_KEY_DOWN:
// Either increase downwardward rotation, or slow upward rotation
KeyDown();
break;
case GLUT_KEY_LEFT:
// Either increase left rotation, or slow down rightward rotation.
KeyLeft();
break;
case GLUT_KEY_RIGHT:
// Either increase right rotation, or slow down leftward rotation.
KeyRight();
break;
}
}

// The routines below are coded so that the only way to change from
// one direction of rotation to the opposite direction is to first
// reset the animation,

void KeyUp() {
if ( RotIncrementX == 0.0 ) {
RotIncrementX = -0.1; // Initially, one-tenth degree rotation per update
}
else if ( RotIncrementX < 0.0f) {
RotIncrementX *= RotIncFactor;
}
else {
RotIncrementX /= RotIncFactor;
}
}

void KeyDown() {
if ( RotIncrementX == 0.0 ) {
RotIncrementX = 0.1; // Initially, one-tenth degree rotation per update
}
else if ( RotIncrementX > 0.0f) {
RotIncrementX *= RotIncFactor;
}
else {
RotIncrementX /= RotIncFactor;
}
}

void KeyLeft() {
if ( RotIncrementY == 0.0 ) {
RotIncrementY = -0.1; // Initially, one-tenth degree rotation per update
}
else if ( RotIncrementY < 0.0) {
RotIncrementY *= RotIncFactor;
}
else {
RotIncrementY /= RotIncFactor;
}
}

void KeyRight()
{
if ( RotIncrementY == 0.0 ) {
RotIncrementY = 0.1; // Initially, one-tenth degree rotation per update
}
else if ( RotIncrementY > 0.0) {
RotIncrementY *= RotIncFactor;
}
else {
RotIncrementY /= RotIncFactor;
}
}


// Resets position and sets rotation rate back to zero.
void ResetAnimation() {
RotX = RotY = RotIncrementX = RotIncrementY = 0.0;
}

// Sets rotation rates back to zero.
void ZeroRotation() {
RotIncrementX = RotIncrementY = 0.0;
}

// Toggle between smooth and flat shading
void ShadeModelToggle() {
if ( shadeModel == GL_FLAT ) {
shadeModel = GL_SMOOTH;
}
else {
shadeModel = GL_FLAT;
}
}

// Toggle between line mode and fill mode for polygons.
void FillModeToggle() {
if ( polygonMode == GL_LINE ) {
polygonMode = GL_FILL;
}
else {
polygonMode = GL_LINE;
}
}

// Toggle quadrilaterial and triangle mode
void QuadTriangleToggle() {
QuadMode = 1-QuadMode;
}

// Toggle from local to global mode
void LocalToggle() {
LocalMode = !LocalMode;
if ( LocalMode ) {
Lt0pos[3] = Lt1pos[3] = 1.0; // Put lights back at finite location.
}
else {
Lt0pos[3] = Lt1pos[3] = 0.0; // Put lights at infinity too.
}
}

// The next two routines toggle the lights on and off
void Light0Toggle() {
Light0Flag = 1-Light0Flag;
}

void Light1Toggle() {
Light1Flag = 1-Light1Flag;
}


// Increment number of wraps
void WrapMore() {
NumWraps++;
}

// Decrement number of wraps
void WrapLess() {
if (NumWraps>4) {
NumWraps--;
}
}

// Increment number of segments per wrap
void NumPerWrapMore() {
NumPerWrap++;
}

// Decrement number segments per wrap
void NumPerWrapLess() {
if (NumPerWrap>4) {
NumPerWrap--;
}
}

/*
* issue vertex command for segment number j of wrap number i.
*/
void putVert(int i, int j) {
float wrapFrac = (j%NumPerWrap)/(float)NumPerWrap;
float phi = PI2*wrapFrac;
float theta = PI2*(i%NumWraps+wrapFrac)/(float)NumWraps;
float sinphi = sin(phi);
float cosphi = cos(phi);
float sintheta = sin(theta);
float costheta = cos(theta);
float y = MinorRadius*sinphi;
float r = MajorRadius + MinorRadius*cosphi;
float x = sintheta*r;
float z = costheta*r;
glNormal3f(sintheta*cosphi, sinphi, costheta*cosphi);
glVertex3f(x,y,z);
}


void updateScene( void )
{
int i,j;

// Clear the redering window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glShadeModel( shadeModel ); // Set the shading to flat or smooth.
glPolygonMode(GL_FRONT_AND_BACK, polygonMode); // Set to be "wire" or "solid"
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode);

// Set up lights
if ( Light0Flag==1 || Light1Flag==1 ) {
// Emissive spheres have no other color.
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Noemit);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Noemit);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0);
}
if ( Light0Flag==1 ) {
glPushMatrix();
glTranslatef(Lt0pos[0], Lt0pos[1], Lt0pos[2]);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Lt0spec);
glutSolidSphere(0.2,5,5);
glPopMatrix();
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, Lt0pos);
}
else {
glDisable(GL_LIGHT0);
}
if ( Light1Flag==1 ) {
glPushMatrix();
glTranslatef(Lt1pos[0], Lt1pos[1], Lt1pos[2]);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Lt1spec);
glutSolidSphere(0.2,5,5);
glPopMatrix();
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_POSITION, Lt1pos);
}
else {
glDisable(GL_LIGHT1);
}

// Torus Materials
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Matnonspec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Matspec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Matshiny);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit);

glPushMatrix(); // Save to use again next time.

// Update the orientation of the torus, if the animation is running.
if ( runMode ) {
RotY += RotIncrementY;
if ( fabs(RotY)>360.0 ) {
RotY -= 360.0*((int)(RotY/360.0));
}
RotX += RotIncrementX;
if ( fabs(RotX)>360.0 ) {
RotX -= 360.0*((int)(RotX/360.0));
}
}
// Set the orientation.
glRotatef( RotX, 1.0, 0.0, 0.0);
glRotatef( RotY, 0.0, 1.0, 0.0);

// Draw the torus
glColor3f( 1.0, 0.5, 1.0 );

glBegin( QuadMode==1 ? GL_QUAD_STRIP : GL_TRIANGLE_STRIP );

for (i=0; i<NumWraps; i++ ) {
for (j=0; j<NumPerWrap; j++) {
putVert(i,j);
putVert(i+1,j);
}
}
putVert(0,0);
putVert(1,0);

glEnd();


// Draw the reference pyramid
glTranslatef( -MajorRadius-MinorRadius-0.3, 0.0, 0.0);
glScalef( 0.2f, 0.2f, 0.2f );
glColor3f( 1.0f, 1.0f, 0.0f );
glBegin(GL_TRIANGLE_STRIP);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glVertex3f( 1.0, 0.0, 0.0);
glVertex3f( 0.0, sqrt(2.0), 0.0);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glEnd();

glPopMatrix(); // Restore to original matrix as set in resizeWindow()

// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}

// Initialize OpenGL
void initRendering()
{
glEnable( GL_DEPTH_TEST );

glEnable(GL_LIGHTING); // Enable lighting calculations
glEnable(GL_LIGHT0); // Turn on lights (unnecessary here, since also in Animate()
glEnable(GL_LIGHT1);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight); // Ambient light

// Light 0 (Position is set in updateScene)
glLightfv(GL_LIGHT0, GL_AMBIENT, Lt0amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, Lt0diff);
glLightfv(GL_LIGHT0, GL_SPECULAR, Lt0spec);

// Light 1 (Position is set in updateScene)
glLightfv(GL_LIGHT1, GL_AMBIENT, Lt1amb);
glLightfv(GL_LIGHT1, GL_DIFFUSE, Lt1diff);
glLightfv(GL_LIGHT1, GL_SPECULAR, Lt1spec);

}

// Called when the window is resized
// Sets up the projection view matrix (somewhat poorly, however)
void resizeWindow(int w, int h)
{
float aspectRatio;
glViewport( 0, 0, w, h ); // View port uses whole window
h = (w == 0) ? 1 : h;
aspectRatio = (float)w/(float)h;

// Set up the proection view matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// Move system 10 units away to be able to view from the origin.
glTranslatef(0.0, 0.0, -10.0);

// Tilt system 15 degrees downward in order to view from above
// the xy-plane.
glRotatef(15.0, 1.0,0.0,0.0);
}


// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

// Window position (from top corner), and size (width and hieght)
glutInitWindowPosition( 10, 60 );
glutInitWindowSize( 620, 160 );
glutCreateWindow( "Light Torus demo" );

// Initialize OpenGL rendering modes
initRendering();
resizeWindow(620,160);

// Set up callback functions for key presses
glutKeyboardFunc( myKeyboardFunc );
glutSpecialFunc( mySpecialKeyFunc );

// Set up the callback function for resizing windows
glutReshapeFunc( resizeWindow );

// Call this for background processing
glutIdleFunc( updateScene );
// Call this whenever window needs redrawing
glutDisplayFunc( updateScene );

// Start the main loop. glutMainLoop never returns.
glutMainLoop( );

return(0); // This line is never reached.
}

Admin
17th September 2008, 08:06 PM
برنامه ی ستاره ها ..!


/* Copyright (c) Mark J. Kilgard, 1994. */

/**
* (c) Copyright 1993, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <GL/glut.h>

#undef PI /* Some systems may have this defined. */
#define PI 3.141592657

enum {
NORMAL = 0,
WEIRD = 1
};

enum {
STREAK = 0,
CIRCLE = 1
};

#define MAXSTARS 400
#define MAXPOS 10000
#define MAXWARP 10
#define MAXANGLES 6000

typedef struct _starRec {
GLint type;
float x[2], y[2], z[2];
float offsetX, offsetY, offsetR, rotation;
} starRec;

GLenum doubleBuffer;
GLint windW = 300, windH = 300;

GLenum flag = NORMAL;
GLint starCount = MAXSTARS / 2;
float speed = 1.0;
GLint nitro = 0;
starRec stars[MAXSTARS];
float sinTable[MAXANGLES];

float
Sin(float angle)
{
return (sinTable[(GLint) angle]);
}

float
Cos(float angle)
{
return (sinTable[((GLint) angle + (MAXANGLES / 4)) % MAXANGLES]);
}

void
NewStar(GLint n, GLint d)
{
if (rand() % 4 == 0) {
stars[n].type = CIRCLE;
} else {
stars[n].type = STREAK;
}
stars[n].x[0] = (float) (rand() % MAXPOS - MAXPOS / 2);
stars[n].y[0] = (float) (rand() % MAXPOS - MAXPOS / 2);
stars[n].z[0] = (float) (rand() % MAXPOS + d);
stars[n].x[1] = stars[n].x[0];
stars[n].y[1] = stars[n].y[0];
stars[n].z[1] = stars[n].z[0];
if (rand() % 4 == 0 && flag == WEIRD) {
stars[n].offsetX = (float) (rand() % 100 - 100 / 2);
stars[n].offsetY = (float) (rand() % 100 - 100 / 2);
stars[n].offsetR = (float) (rand() % 25 - 25 / 2);
} else {
stars[n].offsetX = 0.0;
stars[n].offsetY = 0.0;
stars[n].offsetR = 0.0;
}
}

void
RotatePoint(float *x, float *y, float rotation)
{
float tmpX, tmpY;

tmpX = *x * Cos(rotation) - *y * Sin(rotation);
tmpY = *y * Cos(rotation) + *x * Sin(rotation);
*x = tmpX;
*y = tmpY;
}

void
MoveStars(void)
{
float offset;
GLint n;

offset = speed * 60.0;

for (n = 0; n < starCount; n++) {
stars[n].x[1] = stars[n].x[0];
stars[n].y[1] = stars[n].y[0];
stars[n].z[1] = stars[n].z[0];
stars[n].x[0] += stars[n].offsetX;
stars[n].y[0] += stars[n].offsetY;
stars[n].z[0] -= offset;
stars[n].rotation += stars[n].offsetR;
if (stars[n].rotation > MAXANGLES) {
stars[n].rotation = 0.0;
}
}
}

GLenum
StarPoint(GLint n)
{
float x0, y0;

x0 = stars[n].x[0] * windW / stars[n].z[0];
y0 = stars[n].y[0] * windH / stars[n].z[0];
RotatePoint(&x0, &y0, stars[n].rotation);
x0 += windW / 2.0;
y0 += windH / 2.0;

if (x0 >= 0.0 && x0 < windW && y0 >= 0.0 && y0 < windH) {
return GL_TRUE;
} else {
return GL_FALSE;
}
}

void
ShowStar(GLint n)
{
float x0, y0, x1, y1, width;
GLint i;

x0 = stars[n].x[0] * windW / stars[n].z[0];
y0 = stars[n].y[0] * windH / stars[n].z[0];
RotatePoint(&x0, &y0, stars[n].rotation);
x0 += windW / 2.0;
y0 += windH / 2.0;

if (x0 >= 0.0 && x0 < windW && y0 >= 0.0 && y0 < windH) {
if (stars[n].type == STREAK) {
x1 = stars[n].x[1] * windW / stars[n].z[1];
y1 = stars[n].y[1] * windH / stars[n].z[1];
RotatePoint(&x1, &y1, stars[n].rotation);
x1 += windW / 2.0;
y1 += windH / 2.0;

glLineWidth(MAXPOS / 100.0 / stars[n].z[0] + 1.0);
glColor3f(1.0, (MAXWARP - speed) / MAXWARP, (MAXWARP - speed) / MAXWARP);
if (fabs(x0 - x1) < 1.0 && fabs(y0 - y1) < 1.0) {
glBegin(GL_POINTS);
glVertex2f(x0, y0);
glEnd();
} else {
glBegin(GL_LINES);
glVertex2f(x0, y0);
glVertex2f(x1, y1);
glEnd();
}
} else {
width = MAXPOS / 10.0 / stars[n].z[0] + 1.0;
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
for (i = 0; i < 8; i++) {
float x = x0 + width * Cos((float) i * MAXANGLES / 8.0);
float y = y0 + width * Sin((float) i * MAXANGLES / 8.0);
glVertex2f(x, y);
};
glEnd();
}
}
}

void
UpdateStars(void)
{
GLint n;

glClear(GL_COLOR_BUFFER_BIT);

for (n = 0; n < starCount; n++) {
if (stars[n].z[0] > speed || (stars[n].z[0] > 0.0 && speed < MAXWARP)) {
if (StarPoint(n) == GL_FALSE) {
NewStar(n, MAXPOS);
}
} else {
NewStar(n, MAXPOS);
}
}
}

void
ShowStars(void)
{
GLint n;

glClear(GL_COLOR_BUFFER_BIT);

for (n = 0; n < starCount; n++) {
if (stars[n].z[0] > speed || (stars[n].z[0] > 0.0 && speed < MAXWARP)) {
ShowStar(n);
}
}
}

static void
Init(void)
{
float angle;
GLint n;

srand((unsigned int) time(NULL));

for (n = 0; n < MAXSTARS; n++) {
NewStar(n, 100);
}

angle = 0.0;
for (n = 0; n <= MAXANGLES; n++) {
sinTable[n] = sin(angle);
angle += PI / (MAXANGLES / 2.0);
}

glClearColor(0.0, 0.0, 0.0, 0.0);

glDisable(GL_DITHER);
}

void
Reshape(int width, int height)
{
windW = width;
windH = height;

glViewport(0, 0, windW, windH);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-0.5, windW + 0.5, -0.5, windH + 0.5);
glMatrixMode(GL_MODELVIEW);
}

/* ARGSUSED1 */
static void
Key(unsigned char key, int x, int y)
{
switch (key) {
case ' ':
flag = (flag == NORMAL) ? WEIRD : NORMAL;
break;
case 't':
nitro = 1;
break;
case 27:
exit(0);
}
}

void
Idle(void)
{
MoveStars();
UpdateStars();
if (nitro > 0) {
speed = (float) (nitro / 10) + 1.0;
if (speed > MAXWARP) {
speed = MAXWARP;
}
if (++nitro > MAXWARP * 10) {
nitro = -nitro;
}
} else if (nitro < 0) {
nitro++;
speed = (float) (-nitro / 10) + 1.0;
if (speed > MAXWARP) {
speed = MAXWARP;
}
}
glutPostRedisplay();
}

void
Display(void)
{
ShowStars();
if (doubleBuffer) {
glutSwapBuffers();
} else {
glFlush();
}
}

void
Visible(int state)
{
if (state == GLUT_VISIBLE) {
glutIdleFunc(Idle);
} else {
glutIdleFunc(NULL);
}
}

static void
Args(int argc, char **argv)
{
GLint i;

doubleBuffer = GL_TRUE;

for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-sb") == 0) {
doubleBuffer = GL_FALSE;
} else if (strcmp(argv[i], "-db") == 0) {
doubleBuffer = GL_TRUE;
}
}
}

int
main(int argc, char **argv)
{
GLenum type;

glutInitWindowSize(windW, windH);
glutInit(&argc, argv);
Args(argc, argv);


type = GLUT_RGB;
type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE;
glutInitDisplayMode(type);
glutCreateWindow("Stars");

Init();

glutReshapeFunc(Reshape);
glutKeyboardFunc(Key);
glutVisibilityFunc(Visible);
glutDisplayFunc(Display);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}

Admin
17th September 2008, 08:07 PM
نوشته رو می تونین با موس بکشین تا بچرخه ..!


/* Copyright (c) Mark J. Kilgard, 1994. */

/* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. */

/* New GLUT 3.0 glutGetModifiers() functionality used to make Shift-Left
mouse scale the dinosaur's size. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h> /* for cos(), sin(), and sqrt() */
#include <GL/glut.h>
#include "trackball.h"

typedef enum {
RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE,
LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE, DINOSAUR
} displayLists;

GLfloat angle = -150; /* in degrees */
GLboolean doubleBuffer = GL_TRUE, iconic = GL_FALSE, keepAspect = GL_FALSE;
int spinning = 0, moving = 0;
int beginx, beginy;
int W = 300, H = 300;
float curquat[4];
float lastquat[4];
GLdouble bodyWidth = 3.0;
int newModel = 1;
int scaling;
float scalefactor = 1.0;
/* *INDENT-OFF* */
GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5},
{11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16},
{8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2},
{1, 2} };
GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9},
{15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10},
{13, 9}, {11, 11}, {9, 11} };
GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0},
{12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} };
GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15},
{9.6, 15.25}, {9, 15.25} };
GLfloat lightZeroPosition[] = {10.0, 4.0, 10.0, 1.0};
GLfloat lightZeroColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */
GLfloat lightOnePosition[] = {-1.0, -2.0, 1.0, 0.0};
GLfloat lightOneColor[] = {0.6, 0.3, 0.2, 1.0}; /* red-tinted */
GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0};
/* *INDENT-ON* */

void
extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize,
GLdouble thickness, GLuint side, GLuint edge, GLuint whole)
{
static GLUtriangulatorObj *tobj = NULL;
GLdouble vertex[3], dx, dy, len;
int i;
int count = (int) (dataSize / (2 * sizeof(GLfloat)));

if (tobj == NULL) {
tobj = gluNewTess(); /* create and initialize a GLU
polygon tesselation object */
gluTessCallback(tobj, GLU_BEGIN, glBegin);
gluTessCallback(tobj, GLU_VERTEX, glVertex2fv); /* semi-tricky

*/
gluTessCallback(tobj, GLU_END, glEnd);
}
glNewList(side, GL_COMPILE);
glShadeModel(GL_SMOOTH); /* smooth minimizes seeing
tessellation */
gluBeginPolygon(tobj);
for (i = 0; i < count; i++) {
vertex[0] = data[i][0];
vertex[1] = data[i][1];
vertex[2] = 0;
gluTessVertex(tobj, vertex, data[i]);
}
gluEndPolygon(tobj);
glEndList();
glNewList(edge, GL_COMPILE);
glShadeModel(GL_FLAT); /* flat shade keeps angular hands
from being * * "smoothed" */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= count; i++) {
/* mod function handles closing the edge */
glVertex3f(data[i % count][0], data[i % count][1], 0.0);
glVertex3f(data[i % count][0], data[i % count][1], thickness);
/* Calculate a unit normal by dividing by Euclidean
distance. We * could be lazy and use
glEnable(GL_NORMALIZE) so we could pass in * arbitrary
normals for a very slight performance hit. */
dx = data[(i + 1) % count][1] - data[i % count][1];
dy = data[i % count][0] - data[(i + 1) % count][0];
len = sqrt(dx * dx + dy * dy);
glNormal3f(dx / len, dy / len, 0.0);
}
glEnd();
glEndList();
glNewList(whole, GL_COMPILE);
glFrontFace(GL_CW);
glCallList(edge);
glNormal3f(0.0, 0.0, -1.0); /* constant normal for side */
glCallList(side);
glPushMatrix();
glTranslatef(0.0, 0.0, thickness);
glFrontFace(GL_CCW);
glNormal3f(0.0, 0.0, 1.0); /* opposite normal for other side

*/
glCallList(side);
glPopMatrix();
glEndList();
}

void
makeDinosaur(void)
{
extrudeSolidFromPolygon(body, sizeof(body), bodyWidth,
BODY_SIDE, BODY_EDGE, BODY_WHOLE);
extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4,
ARM_SIDE, ARM_EDGE, ARM_WHOLE);
extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2,
LEG_SIDE, LEG_EDGE, LEG_WHOLE);
extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2,
EYE_SIDE, EYE_EDGE, EYE_WHOLE);
glNewList(DINOSAUR, GL_COMPILE);
glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor);
glCallList(BODY_WHOLE);
glPushMatrix();
glTranslatef(0.0, 0.0, bodyWidth);
glCallList(ARM_WHOLE);
glCallList(LEG_WHOLE);
glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4);
glCallList(ARM_WHOLE);
glTranslatef(0.0, 0.0, -bodyWidth / 4);
glCallList(LEG_WHOLE);
glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1);
glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor);
glCallList(EYE_WHOLE);
glPopMatrix();
glEndList();
}

void
recalcModelView(void)
{
GLfloat m[4][4];

glPopMatrix();
glPushMatrix();
build_rotmatrix(m, curquat);
glMultMatrixf(&m[0][0]);
if (scalefactor == 1.0) {
glDisable(GL_NORMALIZE);
} else {
glEnable(GL_NORMALIZE);
}
glScalef(scalefactor, scalefactor, scalefactor);
glTranslatef(-8, -8, -bodyWidth / 2);
newModel = 0;
}

void
showMessage(GLfloat x, GLfloat y, GLfloat z, char *message)
{
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(x, y, z);
glScalef(.02, .02, .02);
while (*message) {
glutStrokeCharacter(GLUT_STROKE_ROMAN, *message);
message++;
}
glEnable(GL_LIGHTING);
glPopMatrix();
}

void
redraw(void)
{
if (newModel)
recalcModelView();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCallList(DINOSAUR);
showMessage(2, 7.1, 4.1, "Spin me.");
glutSwapBuffers();
}

void
myReshape(int w, int h)
{
glViewport(0, 0, w, h);
W = w;
H = h;
}

void
mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
spinning = 0;
glutIdleFunc(NULL);
moving = 1;
beginx = x;
beginy = y;
if (glutGetModifiers() & GLUT_ACTIVE_SHIFT) {
scaling = 1;
} else {
scaling = 0;
}
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
moving = 0;
}
}

void
animate(void)
{
add_quats(lastquat, curquat, curquat);
newModel = 1;
glutPostRedisplay();
}

void
motion(int x, int y)
{
if (scaling) {
scalefactor = scalefactor * (1.0 + (((float) (beginy - y)) / H));
beginx = x;
beginy = y;
newModel = 1;
glutPostRedisplay();
return;
}
if (moving) {
trackball(lastquat,
(2.0 * beginx - W) / W,
(H - 2.0 * beginy) / H,
(2.0 * x - W) / W,
(H - 2.0 * y) / H
);
beginx = x;
beginy = y;
spinning = 1;
glutIdleFunc(animate);
}
}

GLboolean lightZeroSwitch = GL_TRUE, lightOneSwitch = GL_TRUE;

void
controlLights(int value)
{
switch (value) {
case 1:
lightZeroSwitch = !lightZeroSwitch;
if (lightZeroSwitch) {
glEnable(GL_LIGHT0);
} else {
glDisable(GL_LIGHT0);
}
break;
case 2:
lightOneSwitch = !lightOneSwitch;
if (lightOneSwitch) {
glEnable(GL_LIGHT1);
} else {
glDisable(GL_LIGHT1);
}
break;
#ifdef GL_MULTISAMPLE_SGIS
case 3:
if (glIsEnabled(GL_MULTISAMPLE_SGIS)) {
glDisable(GL_MULTISAMPLE_SGIS);
} else {
glEnable(GL_MULTISAMPLE_SGIS);
}
break;
#endif
case 4:
glutFullScreen();
break;
case 5:
exit(0);
break;
}
glutPostRedisplay();
}

void
vis(int visible)
{
if (visible == GLUT_VISIBLE) {
if (spinning)
glutIdleFunc(animate);
} else {
if (spinning)
glutIdleFunc(NULL);
}
}

int
main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
trackball(curquat, 0.0, 0.0, 0.0, 0.0);
glutCreateWindow("dinospin");
glutDisplayFunc(redraw);
glutReshapeFunc(myReshape);
glutVisibilityFunc(vis);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutCreateMenu(controlLights);
glutAddMenuEntry("Toggle right light", 1);
glutAddMenuEntry("Toggle left light", 2);
if (glutGet(GLUT_WINDOW_NUM_SAMPLES) > 0) {
glutAddMenuEntry("Toggle multisampling", 3);
glutSetWindowTitle("dinospin (multisample capable)");
}
glutAddMenuEntry("Full screen", 4);
glutAddMenuEntry("Quit", 5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
makeDinosaur();
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
gluPerspective( /* field of view in degree */ 40.0,
/* aspect ratio */ 1.0,
/* Z near */ 1.0, /* Z far */ 40.0);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.0, 0.0, 30.0, /* eye is at (0,0,30) */
0.0, 0.0, 0.0, /* center is at (0,0,0) */
0.0, 1.0, 0.); /* up is in positive Y direction */
glPushMatrix(); /* dummy push so we can pop on model
recalc */
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightOneColor);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glLineWidth(2.0);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}

Admin
17th September 2008, 08:09 PM
اینم یه برنامه ی بازی به زبان OpenGl

خواستم یه نمونه بازی بذارم که بدونین بازی هم میشه به این شکل نوشت.

موفق باشید

Admin
17th September 2008, 08:10 PM
جهان کره ها ..!
با کیبورد می تونین در این دنیا بگردین و لذت ببرین.


// SphereWorld.c
// OpenGL SuperBible
// Demonstrates an immersive 3D environment using actors
// and a camera. This version adds lights and material properties
// and shadows.
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>

#define NUM_SPHERES 30
GLTFrame spheres[NUM_SPHERES];
GLTFrame frameCamera;

// Light and material Data
GLfloat fLightPos[4] = { -100.0f, 100.0f, 50.0f, 1.0f }; // Point source
GLfloat fNoLight[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat fLowLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat fBrightLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

GLTMatrix mShadowMatrix;

#define GROUND_TEXTURE 0
#define TORUS_TEXTURE 1
#define SPHERE_TEXTURE 2
#define NUM_TEXTURES 3
GLuint textureObjects[NUM_TEXTURES];

const char *szTextureFiles[] = {"grass.tga", "wood.tga", "orb.tga"};


//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLTVector3 vPoints[3] = {{ 0.0f, -0.4f, 0.0f },
{ 10.0f, -0.4f, 0.0f },
{ 5.0f, -0.4f, -5.0f }};
int iSphere;
int i;

// Grayish background
glClearColor(fLowLight[0], fLowLight[1], fLowLight[2], fLowLight[3]);

// Clear stencil buffer with zero, increment by one whenever anybody
// draws into it. When stencil function is enabled, only write where
// stencil value is zero. This prevents the transparent shadow from drawing
// over itself
glStencilOp(GL_INCR, GL_INCR, GL_INCR);
glClearStencil(0);
glStencilFunc(GL_EQUAL, 0x0, 0x01);

// Cull backs of polygons
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE_ARB);

// Setup light parameters
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fNoLight);
glLightfv(GL_LIGHT0, GL_AMBIENT, fLowLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

// Calculate shadow matrix
gltMakeShadowMatrix(vPoints, fLightPos, mShadowMatrix);

// Mostly use material tracking
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMateriali(GL_FRONT, GL_SHININESS, 128);

gltInitFrame(&frameCamera); // Initialize the camera

// Randomly place the sphere inhabitants
for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
{
gltInitFrame(&spheres[iSphere]); // Initialize the frame

// Pick a random location between -20 and 20 at .1 increments
spheres[iSphere].vLocation[0] = (float)((rand() % 400) - 200) * 0.1f;
spheres[iSphere].vLocation[1] = 0.0f;
spheres[iSphere].vLocation[2] = (float)((rand() % 400) - 200) * 0.1f;
}

// Set up texture maps
glEnable(GL_TEXTURE_2D);
glGenTextures(NUM_TEXTURES, textureObjects);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);


for(i = 0; i < NUM_TEXTURES; i++)
{
GLubyte *pBytes;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;

glBindTexture(GL_TEXTURE_2D, textureObjects[i]);

// Load this texture map
pBytes = gltLoadTGA(szTextureFiles[i], &iWidth, &iHeight, &iComponents, &eFormat);
gluBuild2DMipmaps(GL_TEXTURE_2D, iComponents, iWidth, iHeight, eFormat, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

}

////////////////////////////////////////////////////////////////////////
// Do shutdown for the rendering context
void ShutdownRC(void)
{
// Delete the textures
glDeleteTextures(NUM_TEXTURES, textureObjects);
}


///////////////////////////////////////////////////////////
// Draw the ground as a series of triangle strips
void DrawGround(void)
{
GLfloat fExtent = 20.0f;
GLfloat fStep = 1.0f;
GLfloat y = -0.4f;
GLint iStrip, iRun;
GLfloat s = 0.0f;
GLfloat t = 0.0f;
GLfloat texStep = 1.0f / (fExtent * .075f);

glBindTexture(GL_TEXTURE_2D, textureObjects[GROUND_TEXTURE]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

for(iStrip = -fExtent; iStrip <= fExtent; iStrip += fStep)
{
t = 0.0f;
glBegin(GL_TRIANGLE_STRIP);

for(iRun = fExtent; iRun >= -fExtent; iRun -= fStep)
{
glTexCoord2f(s, t);
glNormal3f(0.0f, 1.0f, 0.0f); // All Point up
glVertex3f(iStrip, y, iRun);

glTexCoord2f(s + texStep, t);
glNormal3f(0.0f, 1.0f, 0.0f); // All Point up
glVertex3f(iStrip + fStep, y, iRun);

t += texStep;
}
glEnd();
s += texStep;
}
}

///////////////////////////////////////////////////////////////////////
// Draw random inhabitants and the rotating torus/sphere duo
void DrawInhabitants(GLint nShadow)
{
static GLfloat yRot = 0.0f; // Rotation angle for animation
GLint i;

if(nShadow == 0)
{
yRot += 0.5f;
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
else
glColor4f(1.0f, 1.0f, 1.0f, .10f); // Shadow color


// Draw the randomly located spheres
glBindTexture(GL_TEXTURE_2D, textureObjects[SPHERE_TEXTURE]);
for(i = 0; i < NUM_SPHERES; i++)
{
glPushMatrix();
gltApplyActorTransform(&spheres[i]);
gltDrawSphere(0.3f, 21, 11);
glPopMatrix();
}

glPushMatrix();
glTranslatef(0.0f, 0.1f, -2.5f);

glPushMatrix();
glRotatef(-yRot * 2.0f, 0.0f, 1.0f, 0.0f);
glTranslatef(1.0f, 0.0f, 0.0f);
gltDrawSphere(0.1f,21, 11);
glPopMatrix();

if(nShadow == 0)
{
// Torus alone will be specular
glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
}

glRotatef(yRot, 0.0f, 1.0f, 0.0f);
glBindTexture(GL_TEXTURE_2D, textureObjects[TORUS_TEXTURE]);
gltDrawTorus(0.35, 0.15, 61, 37);
glMaterialfv(GL_FRONT, GL_SPECULAR, fNoLight);
glPopMatrix();
}


// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glPushMatrix();
gltApplyCameraTransform(&frameCamera);

// Position light before any other transformations
glLightfv(GL_LIGHT0, GL_POSITION, fLightPos);

// Draw the ground
glColor3f(1.0f, 1.0f, 1.0f);
DrawGround();

// Draw shadows first
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_STENCIL_TEST);
glPushMatrix();
glMultMatrixf(mShadowMatrix);
DrawInhabitants(1);
glPopMatrix();
glDisable(GL_STENCIL_TEST);
glDisable(GL_BLEND);
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);

// Draw inhabitants normally
DrawInhabitants(0);

glPopMatrix();

// Do the buffer Swap
glutSwapBuffers();
}



// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
gltMoveFrameForward(&frameCamera, 0.1f);

if(key == GLUT_KEY_DOWN)
gltMoveFrameForward(&frameCamera, -0.1f);

if(key == GLUT_KEY_LEFT)
gltRotateFrameLocalY(&frameCamera, 0.1);

if(key == GLUT_KEY_RIGHT)
gltRotateFrameLocalY(&frameCamera, -0.1);

// Refresh the Window
glutPostRedisplay();
}


///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(3,TimerFunction, 1);
}

void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL SphereWorld Demo + Texture Maps");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);

SetupRC();
glutTimerFunc(33, TimerFunction, 1);

glutMainLoop();

ShutdownRC();

return 0;
}

Admin
17th September 2008, 08:11 PM
تونل ..!
با کیبورد در تونل پیش برین.


// Tunnel.c
// Demonstrates mipmapping and using texture objects
// OpenGL SuperBible
// Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools

// Rotation amounts
static GLfloat zPos = -60.0f;

// Texture objects
#define TEXTURE_BRICK 0
#define TEXTURE_FLOOR 1
#define TEXTURE_CEILING 2
#define TEXTURE_COUNT 3
GLuint textures[TEXTURE_COUNT];
const char *szTextureFiles[TEXTURE_COUNT] = { "brick.tga", "floor.tga", "ceiling.tga" };



///////////////////////////////////////////////////////////////////////////////
// Change texture filter for each texture object
void ProcessMenu(int value)
{
GLint iLoop;

for(iLoop = 0; iLoop < TEXTURE_COUNT; iLoop++)
{
glBindTexture(GL_TEXTURE_2D, textures[iLoop]);

switch(value)
{
case 0:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;

case 1:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;

case 2:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
break;

case 3:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
break;

case 4:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
break;

case 5:
default:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
break;
}
}

// Trigger Redraw
glutPostRedisplay();
}


//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the texture objects.
void SetupRC()
{
GLubyte *pBytes;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;
GLint iLoop;

// Black background
glClearColor(0.0f, 0.0f, 0.0f,1.0f);

// Textures applied as decals, no lighting or coloring effects
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

// Load textures
glGenTextures(TEXTURE_COUNT, textures);
for(iLoop = 0; iLoop < TEXTURE_COUNT; iLoop++)
{
// Bind to next texture object
glBindTexture(GL_TEXTURE_2D, textures[iLoop]);

// Load texture, set filter and wrap modes
pBytes = gltLoadTGA(szTextureFiles[iLoop],&iWidth, &iHeight, &iComponents, &eFormat);
gluBuild2DMipmaps(GL_TEXTURE_2D, iComponents, iWidth, iHeight, eFormat, GL_UNSIGNED_BYTE, pBytes);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

// Don't need original texture data any more
free(pBytes);
}
}

///////////////////////////////////////////////////
// Shutdown the rendering context. Just deletes the
// texture objects
void ShutdownRC(void)
{
glDeleteTextures(TEXTURE_COUNT, textures);
}


///////////////////////////////////////////////////
// Respond to arrow keys, move the viewpoint back
// and forth
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
zPos += 1.0f;

if(key == GLUT_KEY_DOWN)
zPos -= 1.0f;

// Refresh the Window
glutPostRedisplay();
}

/////////////////////////////////////////////////////////////////////
// Change viewing volume and viewport. Called when window is resized
void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

fAspect = (GLfloat)w/(GLfloat)h;

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Produce the perspective projection
gluPerspective(90.0f,fAspect,1,120);


glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLfloat z;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Save the matrix state and do the rotations
glPushMatrix();
// Move object back and do in place rotation
glTranslatef(0.0f, 0.0f, zPos);

// Floor
for(z = 60.0f; z >= 0.0f; z -= 10)
{
glBindTexture(GL_TEXTURE_2D, textures[TEXTURE_FLOOR]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-10.0f, -10.0f, z);

glTexCoord2f(1.0f, 0.0f);
glVertex3f(10.0f, -10.0f, z);

glTexCoord2f(1.0f, 1.0f);
glVertex3f(10.0f, -10.0f, z - 10.0f);

glTexCoord2f(0.0f, 1.0f);
glVertex3f(-10.0f, -10.0f, z - 10.0f);
glEnd();

// Ceiling
glBindTexture(GL_TEXTURE_2D, textures[TEXTURE_CEILING]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-10.0f, 10.0f, z - 10.0f);

glTexCoord2f(1.0f, 1.0f);
glVertex3f(10.0f, 10.0f, z - 10.0f);

glTexCoord2f(1.0f, 0.0f);
glVertex3f(10.0f, 10.0f, z);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(-10.0f, 10.0f, z);
glEnd();


// Left Wall
glBindTexture(GL_TEXTURE_2D, textures[TEXTURE_BRICK]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-10.0f, -10.0f, z);

glTexCoord2f(1.0f, 0.0f);
glVertex3f(-10.0f, -10.0f, z - 10.0f);

glTexCoord2f(1.0f, 1.0f);
glVertex3f(-10.0f, 10.0f, z - 10.0f);

glTexCoord2f(0.0f, 1.0f);
glVertex3f(-10.0f, 10.0f, z);
glEnd();


// Right Wall
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(10.0f, 10.0f, z);

glTexCoord2f(1.0f, 1.0f);
glVertex3f(10.0f, 10.0f, z - 10.0f);

glTexCoord2f(1.0f, 0.0f);
glVertex3f(10.0f, -10.0f, z - 10.0f);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(10.0f, -10.0f, z);
glEnd();
}

// Restore the matrix state
glPopMatrix();

// Buffer swap
glutSwapBuffers();
}


//////////////////////////////////////////////////////
// Program entry point
int main(int argc, char *argv[])
{
// Standard initialization stuff
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("Tunnel");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);

// Add menu entries to change filter
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("GL_NEAREST",0);
glutAddMenuEntry("GL_LINEAR",1);
glutAddMenuEntry("GL_NEAREST_MIPMAP_NEAREST",2);
glutAddMenuEntry("GL_NEAREST_MIPMAP_LINEAR", 3);
glutAddMenuEntry("GL_LINEAR_MIPMAP_NEAREST", 4);
glutAddMenuEntry("GL_LINEAR_MIPMAP_LINEAR", 5);
glutAttachMenu(GLUT_RIGHT_BUTTON);

// Startup, loop, shutdown
SetupRC();
glutMainLoop();
ShutdownRC();

return 0;
}

Admin
17th September 2008, 08:12 PM
// Pyramid.c
// Demonstrates Simple Texture Mapping
// OpenGL SuperBible
// Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;


// Change viewing volume and viewport. Called when window is resized
void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

fAspect = (GLfloat)w/(GLfloat)h;

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Produce the perspective projection
gluPerspective(35.0f, fAspect, 1.0, 40.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the lighting for
// the scene.
void SetupRC()
{
GLubyte *pBytes;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;

// Light values and coordinates
GLfloat whiteLight[] = { 0.05f, 0.05f, 0.05f, 1.0f };
GLfloat sourceLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat lightPos[] = { -10.f, 5.0f, 5.0f, 1.0f };

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_AMBIENT,sourceLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Black blue background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

// Load texture
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
pBytes = gltLoadTGA("Stone.tga", &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_2D);
}

// Respond to arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

xRot = (GLfloat)((const int)xRot % 360);
yRot = (GLfloat)((const int)yRot % 360);

// Refresh the Window
glutPostRedisplay();
}


// Called to draw scene
void RenderScene(void)
{
GLTVector3 vNormal;
GLTVector3 vCorners[5] = { { 0.0f, .80f, 0.0f }, // Top 0
{ -0.5f, 0.0f, -.50f }, // Back left 1
{ 0.5f, 0.0f, -0.50f }, // Back right 2
{ 0.5f, 0.0f, 0.5f }, // Front right 3
{ -0.5f, 0.0f, 0.5f }}; // Front left 4

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the matrix state and do the rotations
glPushMatrix();
// Move object back and do in place rotation
glTranslatef(0.0f, -0.25f, -4.0f);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Draw the Pyramid
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
// Bottom section - two triangles
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3fv(vCorners[2]);

glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[4]);

glTexCoord2f(0.0f, 1.0f);
glVertex3fv(vCorners[1]);


glTexCoord2f(1.0f, 1.0f);
glVertex3fv(vCorners[2]);

glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vCorners[3]);

glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[4]);

// Front Face
gltGetNormalVector(vCorners[0], vCorners[4], vCorners[3], vNormal);
glNormal3fv(vNormal);
glTexCoord2f(0.5f, 1.0f);
glVertex3fv(vCorners[0]);
glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[4]);
glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vCorners[3]);

// Left Face
gltGetNormalVector(vCorners[0], vCorners[1], vCorners[4], vNormal);
glNormal3fv(vNormal);
glTexCoord2f(0.5f, 1.0f);
glVertex3fv(vCorners[0]);
glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[1]);
glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vCorners[4]);

// Back Face
gltGetNormalVector(vCorners[0], vCorners[2], vCorners[1], vNormal);
glNormal3fv(vNormal);
glTexCoord2f(0.5f, 1.0f);
glVertex3fv(vCorners[0]);

glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[2]);

glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vCorners[1]);

// Right Face
gltGetNormalVector(vCorners[0], vCorners[3], vCorners[2], vNormal);
glNormal3fv(vNormal);
glTexCoord2f(0.5f, 1.0f);
glVertex3fv(vCorners[0]);
glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vCorners[3]);
glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vCorners[2]);
glEnd();


// Restore the matrix state
glPopMatrix();

// Buffer swap
glutSwapBuffers();
}



int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Textured Pyramid");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 08:14 PM
// Toon.c
// OpenGL SuperBible
// Demonstrates Cell/Toon shading with a 1D texture
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>

// Draw a torus (doughnut), using the current 1D texture for light shading
void toonDrawTorus(GLfloat majorRadius, GLfloat minorRadius,
int numMajor, int numMinor, GLTVector3 vLightDir)
{
GLTMatrix mModelViewMatrix;
GLTVector3 vNormal, vTransformedNormal;
double majorStep = 2.0f*GLT_PI / numMajor;
double minorStep = 2.0f*GLT_PI / numMinor;
int i, j;

// Get the modelview matrix
glGetFloatv(GL_MODELVIEW_MATRIX, mModelViewMatrix);

// Normalize the light vector
gltNormalizeVector(vLightDir);

// Draw torus as a series of triangle strips
for (i=0; i<numMajor; ++i)
{
double a0 = i * majorStep;
double a1 = a0 + majorStep;
GLfloat x0 = (GLfloat) cos(a0);
GLfloat y0 = (GLfloat) sin(a0);
GLfloat x1 = (GLfloat) cos(a1);
GLfloat y1 = (GLfloat) sin(a1);

glBegin(GL_TRIANGLE_STRIP);
for (j=0; j<=numMinor; ++j)
{
double b = j * minorStep;
GLfloat c = (GLfloat) cos(b);
GLfloat r = minorRadius * c + majorRadius;
GLfloat z = minorRadius * (GLfloat) sin(b);

// First point
vNormal[0] = x0*c;
vNormal[1] = y0*c;
vNormal[2] = z/minorRadius;
gltNormalizeVector(vNormal);
gltRotateVector(vNormal, mModelViewMatrix, vTransformedNormal);

// Texture coordinate is set by intensity of light
glTexCoord1f(gltVectorDotProduct(vLightDir, vTransformedNormal));
glVertex3f(x0*r, y0*r, z);

// Second point
vNormal[0] = x1*c;
vNormal[1] = y1*c;
vNormal[2] = z/minorRadius;
gltNormalizeVector(vNormal);
gltRotateVector(vNormal, mModelViewMatrix, vTransformedNormal);

// Texture coordinate is set by intensity of light
glTexCoord1f(gltVectorDotProduct(vLightDir, vTransformedNormal));
glVertex3f(x1*r, y1*r, z);
}
glEnd();
}
}


// Called to draw scene
void RenderScene(void)
{
// Rotation angle
static GLfloat yRot = 0.0f;

// Where is the light coming from
GLTVector3 vLightDir = { -1.0f, 1.0f, 1.0f };

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -2.5f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
toonDrawTorus(0.35f, 0.15f, 50, 25, vLightDir);
glPopMatrix();

// Do the buffer Swap
glutSwapBuffers();

// Rotate 1/2 degree more each frame
yRot += 0.5f;
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Load a 1D texture with toon shaded values
// Green, greener...
GLbyte toonTable[4][3] = { { 0, 32, 0 },
{ 0, 64, 0 },
{ 0, 128, 0 },
{ 0, 192, 0 }};

// Bluish background
glClearColor(0.0f, 0.0f, .50f, 1.0f );
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, 4, 0, GL_RGB, GL_UNSIGNED_BYTE, toonTable);

glEnable(GL_TEXTURE_1D);
}

///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}



void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Toon/Cell Shading Demo");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(33, TimerFunction, 1);

SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 08:15 PM
// MultiTexture.c
// OpenGL SuperBible
// Demonstrates an immersive 3D environment using actors
// and a camera.
// This version shows off multitexture and cube mapping
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
#include <math.h>

#define NUM_SPHERES 30
GLTFrame spheres[NUM_SPHERES];
GLTFrame frameCamera;

// Light and material Data
GLfloat fLightPos[4] = { -100.0f, 100.0f, 50.0f, 1.0f }; // Point source
GLfloat fNoLight[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat fLowLight[] = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat fBrightLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

#define GROUND_TEXTURE 0
#define SPHERE_TEXTURE 1
#define WOOD_TEXTURE 2
#define CUBE_MAP 3
#define NUM_TEXTURES 4
GLuint textureObjects[NUM_TEXTURES];

const char *szTextureFiles[] = {"grass.tga", "orb.tga", "wood.tga"};

const char *szCubeFaces[6] = { "right.tga", "left.tga", "up.tga", "down.tga", "backward.tga", "forward.tga" };

GLenum cube[6] = { GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z };


// Need pointer on Windows
#ifdef WIN32
PFNGLACTIVETEXTUREPROC glActiveTexture = NULL;
#endif

//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
int iSphere;
int i;

#ifdef WIN32
glActiveTexture = (PFNGLACTIVETEXTUREPROC)gltGetExtensionPointer("glActiveTexture");
#endif

// Grayish background
glClearColor(fLowLight[0], fLowLight[1], fLowLight[2], fLowLight[3]);

// Cull backs of polygons
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);

// Setup light parameters
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fNoLight);
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
glLightfv(GL_LIGHT0, GL_AMBIENT, fLowLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

// Mostly use material tracking
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMateriali(GL_FRONT, GL_SHININESS, 128);

gltInitFrame(&frameCamera); // Initialize the camera

// Randomly place the sphere inhabitants
for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
{
gltInitFrame(&spheres[iSphere]); // Initialize the frame

// Pick a random location between -20 and 20 at .1 increments
spheres[iSphere].vLocation[0] = (float)((rand() % 400) - 200) * 0.1f;
spheres[iSphere].vLocation[1] = 0.0f;
spheres[iSphere].vLocation[2] = (float)((rand() % 400) - 200) * 0.1f;
}

// Set up texture maps
glEnable(GL_TEXTURE_2D);
glGenTextures(NUM_TEXTURES, textureObjects);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

// Load regular textures
for(i = 0; i < CUBE_MAP; i++)
{
GLubyte *pBytes;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;

glBindTexture(GL_TEXTURE_2D, textureObjects[i]);

// Load this texture map
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
pBytes = gltLoadTGA(szTextureFiles[i], &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}


glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_CUBE_MAP);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureObjects[CUBE_MAP]);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);

glBindTexture(GL_TEXTURE_CUBE_MAP, textureObjects[CUBE_MAP]);

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);


// Load Cube Map images
for(i = 0; i < 6; i++)
{
GLubyte *pBytes;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;

// Load this texture map
// glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE);
pBytes = gltLoadTGA(szCubeFaces[i], &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(cube[i], 0, iComponents /*GL_COMPRESSED_RGB*/, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBytes);
free(pBytes);
}


}

////////////////////////////////////////////////////////////////////////
// Do shutdown for the rendering context
void ShutdownRC(void)
{
// Delete the textures
glDeleteTextures(NUM_TEXTURES, textureObjects);
}


///////////////////////////////////////////////////////////
// Draw the ground as a series of triangle strips
void DrawGround(void)
{
GLfloat fExtent = 20.0f;
GLfloat fStep = 1.0f;
GLfloat y = -0.4f;
GLint iStrip, iRun;
GLfloat s = 0.0f;
GLfloat t = 0.0f;
GLfloat texStep = 1.0f / (fExtent * .075f);

glBindTexture(GL_TEXTURE_2D, textureObjects[GROUND_TEXTURE]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

for(iStrip = -fExtent; iStrip <= fExtent; iStrip += fStep)
{
t = 0.0f;
glBegin(GL_TRIANGLE_STRIP);

for(iRun = fExtent; iRun >= -fExtent; iRun -= fStep)
{
glTexCoord2f(s, t);
glNormal3f(0.0f, 1.0f, 0.0f); // All Point up
glVertex3f(iStrip, y, iRun);

glTexCoord2f(s + texStep, t);
glNormal3f(0.0f, 1.0f, 0.0f); // All Point up
glVertex3f(iStrip + fStep, y, iRun);

t += texStep;
}
glEnd();
s += texStep;
}
}

///////////////////////////////////////////////////////////////////////
// Draw random inhabitants and the rotating torus/sphere duo
void DrawInhabitants(void)
{
static GLfloat yRot = 0.0f; // Rotation angle for animation
GLint i;

yRot += 0.5f;
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

// Draw the randomly located spheres
glBindTexture(GL_TEXTURE_2D, textureObjects[SPHERE_TEXTURE]);
for(i = 0; i < NUM_SPHERES; i++)
{
glPushMatrix();
gltApplyActorTransform(&spheres[i]);
gltDrawSphere(0.3f, 21, 11);
glPopMatrix();
}

glPushMatrix();
glTranslatef(0.0f, 0.1f, -2.5f);

// Torus alone will be specular
glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Bind to Wood, first texture
glBindTexture(GL_TEXTURE_2D, textureObjects[WOOD_TEXTURE]);

glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_CUBE_MAP);

glActiveTexture(GL_TEXTURE0);

gltDrawTorus(0.35, 0.15, 41, 17);

glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_CUBE_MAP);
glActiveTexture(GL_TEXTURE0);

glMaterialfv(GL_FRONT, GL_SPECULAR, fNoLight);
glPopMatrix();
}


// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();
gltApplyCameraTransform(&frameCamera);

// Position light before any other transformations
glLightfv(GL_LIGHT0, GL_POSITION, fLightPos);

// Draw the ground
glColor3f(1.0f, 1.0f, 1.0f);
DrawGround();

// Draw inhabitants
DrawInhabitants();

glPopMatrix();

// Do the buffer Swap
glutSwapBuffers();
}



// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
gltMoveFrameForward(&frameCamera, 0.1f);

if(key == GLUT_KEY_DOWN)
gltMoveFrameForward(&frameCamera, -0.1f);

if(key == GLUT_KEY_LEFT)
gltRotateFrameLocalY(&frameCamera, 0.1);

if(key == GLUT_KEY_RIGHT)
gltRotateFrameLocalY(&frameCamera, -0.1);

// Refresh the Window
glutPostRedisplay();
}


///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(3,TimerFunction, 1);
}

void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;

glViewport(0, 0, w, h);

fAspect = (GLfloat)w / (GLfloat)h;

// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Set the clipping volume
gluPerspective(35.0f, fAspect, 1.0f, 50.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL SphereWorld Demo + Multitexture");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);

SetupRC();
glutTimerFunc(33, TimerFunction, 1);

glutMainLoop();

ShutdownRC();

return 0;
}

Admin
17th September 2008, 08:16 PM
// TexGen.c
// OpenGL SuperBible
// Demonstrates OpenGL Texture Coordinate Generation
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/gltools.h" // gltools library

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

GLuint toTextures[2]; // Two texture objects
int iRenderMode = 3; // Sphere Mapped is default

///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
{
// Projection plane
GLfloat zPlane[] = { 0.0f, 0.0f, 1.0f, 0.0f };

// Store render mode
iRenderMode = value;

// Set up textgen based on menu selection
switch(value)
{
case 1:
// Object Linear
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGenfv(GL_S, GL_OBJECT_PLANE, zPlane);
glTexGenfv(GL_T, GL_OBJECT_PLANE, zPlane);
break;

case 2:
// Eye Linear
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGenfv(GL_S, GL_EYE_PLANE, zPlane);
glTexGenfv(GL_T, GL_EYE_PLANE, zPlane);
break;

case 3:
default:
// Sphere Map
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
break;
}

glutPostRedisplay(); // Redisplay
}



///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Switch to orthographic view for background drawing
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0f, 1.0f, 0.0f, 1.0f);

glMatrixMode(GL_MODELVIEW);
glBindTexture(GL_TEXTURE_2D, toTextures[1]); // Background texture

// We will specify texture coordinates
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);

// No depth buffer writes for background
glDepthMask(GL_FALSE);

// Background image
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(0.0f, 0.0f);

glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, 0.0f);

glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);

glTexCoord2f(0.0f, 1.0f);
glVertex2f(0.0f, 1.0f);
glEnd();

// Back to 3D land
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);

// Turn texgen and depth writing back on
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glDepthMask(GL_TRUE);

// May need to swtich to stripe texture
if(iRenderMode != 3)
glBindTexture(GL_TEXTURE_2D, toTextures[0]);

// Save the matrix state and do the rotations
glPushMatrix();
glTranslatef(0.0f, 0.0f, -2.0f);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);

// Draw the tours
gltDrawTorus(0.35, 0.15, 61, 37);

// Restore the matrix state
glPopMatrix();

// Display the results
glutSwapBuffers();
}

///////////////////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLbyte *pBytes; // Texture bytes
GLint iComponents, iWidth, iHeight; // Texture sizes
GLenum eFormat; // Texture format

glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// White background
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );

// Decal texture environment
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

// Two textures
glGenTextures(2, toTextures);

///////////////////////////////////////////
// Load the main texture
glBindTexture(GL_TEXTURE_2D, toTextures[0]);
pBytes = gltLoadTGA("stripes.tga", &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, (void *)pBytes);
free(pBytes);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);

///////////////////////////////////////////
// Load environment map
glBindTexture(GL_TEXTURE_2D, toTextures[1]);
pBytes = gltLoadTGA("Environment.tga", &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, (void *)pBytes);
free(pBytes);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);

// Turn on texture coordiante generation
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);

// Sphere Map will be the default
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
}

/////////////////////////////////////////////////////
// Handle arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

if(key > 356.0f)
xRot = 0.0f;

if(key < -1.0f)
xRot = 355.0f;

if(key > 356.0f)
yRot = 0.0f;

if(key < -1.0f)
yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}


//////////////////////////////////////////////////////////
// Reset projection and light position
void ChangeSize(int w, int h)
{
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

fAspect = (GLfloat) w / (GLfloat) h;
gluPerspective(45.0f, fAspect, 1.0f, 225.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////////////////////////////////
// Program Entry Point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Texture Coordinate Generation");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();

// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Object Linear",1);
glutAddMenuEntry("Eye Linear",2);
glutAddMenuEntry("Sphere Map",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMainLoop();

// Don't forget the texture objects
glDeleteTextures(2, toTextures);

return 0;
}

Admin
17th September 2008, 08:17 PM
// Bezlit.c
// OpenGL SuperBible
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools

// The number of control points for this curve
GLint nNumPoints = 3;

GLfloat ctrlPoints[3][3][3]= {{{ -4.0f, 0.0f, 4.0f},
{ -2.0f, 4.0f, 4.0f},
{ 4.0f, 0.0f, 4.0f }},

{{ -4.0f, 0.0f, 0.0f},
{ -2.0f, 4.0f, 0.0f},
{ 4.0f, 0.0f, 0.0f }},

{{ -4.0f, 0.0f, -4.0f},
{ -2.0f, 4.0f, -4.0f},
{ 4.0f, 0.0f, -4.0f }}};


// This function is used to superimpose the control points over the curve
void DrawPoints(void)
{
int i,j; // Counting variables

// Set point size larger to make more visible
glPointSize(5.0f);

// Loop through all control points for this example
glBegin(GL_POINTS);
for(i = 0; i < nNumPoints; i++)
for(j = 0; j < 3; j++)
glVertex3fv(ctrlPoints[i][j]);
glEnd();
}



// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the modelview matrix stack
glMatrixMode(GL_MODELVIEW);
glPushMatrix();

// Rotate the mesh around to make it easier to see
glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
glRotatef(60.0f, 1.0f, 0.0f, 0.0f);


// Sets up the bezier
// This actually only needs to be called once and could go in
// the setup function
glMap2f(GL_MAP2_VERTEX_3, // Type of data generated
0.0f, // Lower u range
10.0f, // Upper u range
3, // Distance between points in the data
3, // Dimension in u direction (order)
0.0f, // Lover v range
10.0f, // Upper v range
9, // Distance between points in the data
3, // Dimension in v direction (order)
&ctrlPoints[0][0][0]); // array of control points

// Enable the evaluator
glEnable(GL_MAP2_VERTEX_3);

// Use higher level functions to map to a grid, then evaluate the
// entire thing.

// Map a grid of 10 points from 0 to 10
glMapGrid2f(10,0.0f,10.0f,10,0.0f,10.0f);

// Evaluate the grid, using lines
glEvalMesh2(GL_FILL,0,10,0,10);

// Restore the modelview matrix
glPopMatrix();


// Dispalay the image
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values and coordinates
GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat lightPos[] = { 20.0f, 0.0f, 0.0f, 0.0f };

// Clear Window to white
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );

glEnable(GL_DEPTH_TEST); // Hidden surface removal

// Enable lighting
glEnable(GL_LIGHTING);

// Setup light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);

// Position and turn on the light
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Automatically generate normals for evaluated surfaces
glEnable(GL_AUTO_NORMAL);

// Draw in Blue
glColor3f(0.0f, 0.0f, 1.0f);
}


void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glOrtho(-10.0f, 10.0f, -10.0f, 10.0f, -10.0f, 10.0f);

// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Lit 3D Bezier Surface");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 08:18 PM
// Bezier.c
// OpenGL SuperBible
// Demonstrates OpenGL evaluators to draw bezier curve
// Program by Richard S. Wright Jr.

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools


// The number of control points for this curve
GLint nNumPoints = 4;

GLfloat ctrlPoints[4][3]= {{ -4.0f, 0.0f, 0.0f}, // End Point
{ -6.0f, 4.0f, 0.0f}, // Control Point
{ 6.0f, -4.0f, 0.0f}, // Control Point
{ 4.0f, 0.0f, 0.0f }}; // End Point

// This function is used to superimpose the control points over the curve
void DrawPoints(void)
{
int i; // Counting variable

// Set point size larger to make more visible
glPointSize(5.0f);

// Loop through all control points for this example
glBegin(GL_POINTS);
for(i = 0; i < nNumPoints; i++)
glVertex2fv(ctrlPoints[i]);
glEnd();
}



// Called to draw scene
void RenderScene(void)
{
int i;

// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Sets up the bezier
// This actually only needs to be called once and could go in
// the setup function
glMap1f(GL_MAP1_VERTEX_3, // Type of data generated
0.0f, // Lower u range
100.0f, // Upper u range
3, // Distance between points in the data
nNumPoints, // number of control points
&ctrlPoints[0][0]); // array of control points

// Enable the evaluator
glEnable(GL_MAP1_VERTEX_3);

// Use a line strip to "connect-the-dots"
glBegin(GL_LINE_STRIP);
for(i = 0; i <= 100; i++)
{
// Evaluate the curve at this point
glEvalCoord1f((GLfloat) i);
}
glEnd();

// Use higher level functions to map to a grid, then evaluate the
// entire thing.
// Put these two functions in to replace above loop

// Map a grid of 100 points from 0 to 100
//glMapGrid1d(100,0.0,100.0);

// Evaluate the grid, using lines
//glEvalMesh1(GL_LINE,0,100);

// Draw the Control Points
DrawPoints();

// Flush drawing commands
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Clear Window to white
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );

// Draw in Blue
glColor3f(0.0f, 0.0f, 1.0f);
}

///////////////////////////////////////
// Set 2D Projection
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

gluOrtho2D(-10.0f, 10.0f, -10.0f, 10.0f);

// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("2D Bezier Curve");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 08:19 PM
برنامه ی Select کردن اشیا.


// Planets.c
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>

struct Rectangle
{
int top;
int bottom;
int left;
int right;
};

///////////////////////////
// Object Names
#define TORUS 1
#define SPHERE 2

struct Rectangle boundingRect; // Bounding rectangle
GLuint selectedObject = 0; // Who is selected
float fAspect; // Display aspect ratio


#if !defined(M_PI)
#define M_PI 3.14159265f
#endif

///////////////////////////////////////////////////////////
// Draw a torus (doughnut)
// at z = 0... torus aligns with xy plane
void DrawTorus(int numMajor, int numMinor)
{
float majorRadius = 0.35F;
float minorRadius = 0.15F;
double majorStep = 2.0F*M_PI / numMajor;
double minorStep = 2.0F*M_PI / numMinor;
int i, j;
float c, r, z;

glEnable(GL_NORMALIZE);
for (i=0; i<numMajor; ++i)
{
double a0 = i * majorStep;
double a1 = a0 + majorStep;
GLfloat x0 = (GLfloat) cos(a0);
GLfloat y0 = (GLfloat) sin(a0);
GLfloat x1 = (GLfloat) cos(a1);
GLfloat y1 = (GLfloat) sin(a1);

glBegin(GL_TRIANGLE_STRIP);
for (j=0; j<=numMinor; ++j)
{
double b = j * minorStep;
c = (float) cos(b);
r = minorRadius * c + majorRadius;
z = minorRadius * (GLfloat) sin(b);

glTexCoord2f((float)i/(float)numMajor, (float)j/(float)numMinor);
glNormal3f(x0*c, y0*c, z/minorRadius);
glVertex3f(x0*r, y0*r, z);

glTexCoord2f((float)(i+1)/(float)numMajor, (float)j/(float)numMinor);
glNormal3f(x1*c, y1*c, z/minorRadius);
glVertex3f(x1*r, y1*r, z);
}
glEnd();
}
glDisable(GL_NORMALIZE);
}


///////////////////////////////////////////////////////////
// Just draw a sphere of some given radius
void DrawSphere(float radius)
{
GLUquadricObj *pObj;
pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);
gluSphere(pObj, radius, 26, 13);
gluDeleteQuadric(pObj);
}


///////////////////////////////////////////////////////////
// Render the torus and sphere
void DrawObjects(void)
{
// Save the matrix state and do the rotations
glMatrixMode(GL_MODELVIEW);
glPushMatrix();

// Translate the whole scene out and into view
glTranslatef(-0.75f, 0.0f, -2.5f);

// Initialize the names stack
glInitNames();
glPushName(0);

// Set material color, Yellow
// torus
glColor3f(1.0f, 1.0f, 0.0f);
glLoadName(TORUS);
glPassThrough((GLfloat)TORUS);
DrawTorus(40, 20);


// Draw Sphere
glColor3f(0.5f, 0.0f, 0.0f);
glTranslatef(1.5f, 0.0f, 0.0f);
glLoadName(SPHERE);
glPassThrough((GLfloat)SPHERE);
DrawSphere(0.5f);

// Restore the matrix state
glPopMatrix(); // Modelview matrix
}

///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Draw the objects in the scene
DrawObjects();

// If something is selected, draw a bounding box around it
if(selectedObject != 0)
{
int viewport[4];

// Get the viewport
glGetIntegerv(GL_VIEWPORT, viewport);

// Remap the viewing volume to match window coordinates (approximately)
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
glOrtho(viewport[0], viewport[2], viewport[3], viewport[1], -1, 1);
glMatrixMode(GL_MODELVIEW);

glDisable(GL_LIGHTING);
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINE_LOOP);
glVertex2i(boundingRect.left, boundingRect.top);
glVertex2i(boundingRect.left, boundingRect.bottom);
glVertex2i(boundingRect.right, boundingRect.bottom);
glVertex2i(boundingRect.right, boundingRect.top);
glEnd();
glEnable(GL_LIGHTING);
}

glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);

glutSwapBuffers();
}



///////////////////////////////////////////////////////////
// Go into feedback mode and draw a rectangle around the object
#define FEED_BUFF_SIZE 32768
void MakeSelection(int nChoice)
{
// Space for the feedback buffer
static GLfloat feedBackBuff[FEED_BUFF_SIZE];

// Storage for counters, etc.
int size,i,j,count;

// Initial minimum and maximum values
boundingRect.right = boundingRect.bottom = -999999.0f;
boundingRect.left = boundingRect.top = 999999.0f;

// Set the feedback buffer
glFeedbackBuffer(FEED_BUFF_SIZE,GL_2D, feedBackBuff);

// Enter feedback mode
glRenderMode(GL_FEEDBACK);

// Redraw the scene
DrawObjects();

// Leave feedback mode
size = glRenderMode(GL_RENDER);

// Parse the feedback buffer and get the
// min and max X and Y window coordinates
i = 0;
while(i < size)
{
// Search for appropriate token
if(feedBackBuff[i] == GL_PASS_THROUGH_TOKEN)
if(feedBackBuff[i+1] == (GLfloat)nChoice)
{
i+= 2;
// Loop until next token is reached
while(i < size && feedBackBuff[i] != GL_PASS_THROUGH_TOKEN)
{
// Just get the polygons
if(feedBackBuff[i] == GL_POLYGON_TOKEN)
{
// Get all the values for this polygon
count = (int)feedBackBuff[++i]; // How many vertices
i++;

for(j = 0; j < count; j++) // Loop for each vertex
{
// Min and Max X
if(feedBackBuff[i] > boundingRect.right)
boundingRect.right = feedBackBuff[i];

if(feedBackBuff[i] < boundingRect.left)
boundingRect.left = feedBackBuff[i];
i++;

// Min and Max Y
if(feedBackBuff[i] > boundingRect.bottom)
boundingRect.bottom = feedBackBuff[i];

if(feedBackBuff[i] < boundingRect.top)
boundingRect.top = feedBackBuff[i];
i++;
}
}
else
i++; // Get next index and keep looking
}
break;
}
i++;
}
}


///////////////////////////////////////////////////////////
// Process the selection, which is triggered by a right mouse
// click at (xPos, yPos).
#define BUFFER_LENGTH 64
void ProcessSelection(int xPos, int yPos)
{
// Space for selection buffer
static GLuint selectBuff[BUFFER_LENGTH];

// Hit counter and viewport storage
GLint hits, viewport[4];

// Setup selection buffer
glSelectBuffer(BUFFER_LENGTH, selectBuff);

// Get the viewport
glGetIntegerv(GL_VIEWPORT, viewport);

// Switch to projection and save the matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();

// Change render mode
glRenderMode(GL_SELECT);

// Establish new clipping volume to be unit cube around
// mouse cursor point (xPos, yPos) and extending two pixels
// in the vertical and horizontal direction
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);

// Apply perspective matrix
gluPerspective(60.0f, fAspect, 1.0, 425.0);

// Draw the scene
DrawObjects();

// Collect the hits
hits = glRenderMode(GL_RENDER);

// Restore the projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();

// Go back to modelview for normal rendering
glMatrixMode(GL_MODELVIEW);

// If a single hit occurred, display the info.
if(hits == 1)
{
MakeSelection(selectBuff[3]);
if(selectedObject == selectBuff[3])
selectedObject = 0;
else
selectedObject = selectBuff[3];
}

glutPostRedisplay();
}



///////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the lighting for
// the scene.
void SetupRC()
{
// Lighting values
GLfloat dimLight[] = { 0.1f, 0.1f, 0.1f, 1.0f };
GLfloat sourceLight[] = { 0.65f, 0.65f, 0.65f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };

// Light values and coordinates
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
//glEnable(GL_CULL_FACE); // Do not calculate insides

// Enable lighting
glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,dimLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);

// Enable color tracking
glEnable(GL_COLOR_MATERIAL);

// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Gray background
glClearColor(0.60f, 0.60f, 0.60f, 1.0f );
glLineWidth(2.0f);
}


///////////////////////////////////////////////////////////
// Set viewport and projection
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Calculate aspect ratio of the window
fAspect = (GLfloat)w/(GLfloat)h;

// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Field of view of 45 degrees, near and far planes 1.0 and 425
gluPerspective(60.0f, fAspect, 1.0, 425.0);

// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

///////////////////////////////////////////////////////////
// Process the mouse click
void MouseCallback(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
ProcessSelection(x, y);
}

///////////////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Select an Object");
glutReshapeFunc(ChangeSize);
glutMouseFunc(MouseCallback);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}

Admin
17th September 2008, 08:20 PM
// GLPalette.c
// OpenGL SuperBible,
// Program by Richard S. Wright Jr.
// This program demonstrates creation and use of a 332 palette for OpenGL
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include "resource.h"

// Palette Handle
HPALETTE hPalette = NULL;


static LPCTSTR lpszAppName = "GLPalette";

// Declaration for Window procedure
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);

// Set Pixel Format function - forward declaration
void SetDCPixelFormat(HDC hDC);


BYTE* gltResourceBMPBits(UINT nResource, int *nWidth, int *nHeight)
{
HINSTANCE hInstance; // Instance Handle
HANDLE hBitmap; // Handle to bitmap resource
BITMAPINFO bmInfo;
BYTE *pData;

// Find the bitmap resource
hInstance = GetModuleHandle(NULL);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(nResource));

if(hBitmap == NULL)
return NULL;

GetObject(hBitmap,sizeof(BITMAPINFO),&bmInfo);
DeleteObject(hBitmap);

hBitmap = LoadResource(hInstance,
FindResource(hInstance,MAKEINTRESOURCE(nResource), RT_BITMAP));

if(hBitmap == NULL)
return NULL;

pData = (BYTE *)LockResource(hBitmap);
pData += sizeof(BITMAPINFO)-1;

*nWidth = bmInfo.bmiHeader.biWidth; //bm.bmWidth;
*nHeight = bmInfo.bmiHeader.biHeight;//bm.bmHeight;

return pData;
}


void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat nRange = 100.0f;
GLfloat fAspect;

// Prevent a divide by zero
if(h == 0)
h = 1;

fAspect = (GLfloat)w/(GLfloat)h;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);

// Reset coordinate system
glLoadIdentity();

// Setup perspective for viewing
gluPerspective(17.5f,fAspect,60,300);

// Viewing transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -250.0f);
}


void RenderScene(void)
{
static float fX = 0.0f;
static float fY = 0.0f;
float fSize = 20.0f;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

fX += 0.15f;
fY += 0.1f;

if(fX > 360.0f)
fX = 0.15f;

if(fY > 360.0f)
fY = 0.1f;

glPushMatrix();
glRotatef(fX, 1.0f, 0.0f, 0.0f);
glRotatef(fY, 0.0f, 1.0f, 0.0f);

// Front face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-fSize, -fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize,-fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(fSize,fSize, fSize);
glEnd();

// Back face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(fSize,fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize,-fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glEnd();

// Top Face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glEnd();


// Bottom Face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, -fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, -fSize, fSize);
glEnd();


// Left hand side of cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-fSize, -fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glEnd();


// Right hand side of cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, -fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(fSize, fSize, -fSize);
glEnd();

glPopMatrix();
}


void SetupRC(void)
{
BYTE *pBytes;
int nWidth, nHeight;

glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);

glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);

// Load the texture
pBytes = gltResourceBMPBits(IDB_MONA, &nWidth, &nHeight);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);
}


// If necessary, creates a 3-3-2 palette for the device context listed.
HPALETTE GetOpenGLPalette(HDC hDC)
{
HPALETTE hRetPal = NULL; // Handle to palette to be created
PIXELFORMATDESCRIPTOR pfd; // Pixel Format Descriptor
LOGPALETTE *pPal; // Pointer to memory for logical palette
int nPixelFormat; // Pixel format index
int nColors; // Number of entries in palette
int i; // Counting variable
BYTE RedRange,GreenRange,BlueRange;
// Range for each color entry (7,7,and 3)


// Get the pixel format index and retrieve the pixel format description
nPixelFormat = GetPixelFormat(hDC);
DescribePixelFormat(hDC, nPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

// Does this pixel format require a palette? If not, do not create a
// palette and just return NULL
if(!(pfd.dwFlags & PFD_NEED_PALETTE))
return NULL;

// Number of entries in palette. 8 bits yeilds 256 entries
nColors = 1 << pfd.cColorBits;

// Allocate space for a logical palette structure plus all the palette entries
pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) +nColors*sizeof(PALETTEENTRY));

// Fill in palette header
pPal->palVersion = 0x300; // Windows 3.0
pPal->palNumEntries = nColors; // table size

// Build mask of all 1's. This creates a number represented by having
// the low order x bits set, where x = pfd.cRedBits, pfd.cGreenBits, and
// pfd.cBlueBits.
RedRange = (1 << pfd.cRedBits) -1;
GreenRange = (1 << pfd.cGreenBits) - 1;
BlueRange = (1 << pfd.cBlueBits) -1;

// Loop through all the palette entries
for(i = 0; i < nColors; i++)
{
// Fill in the 8-bit equivalents for each component
pPal->palPalEntry[i].peRed = (i >> pfd.cRedShift) & RedRange;
pPal->palPalEntry[i].peRed = (unsigned char)(
(double) pPal->palPalEntry[i].peRed * 255.0 / RedRange);

pPal->palPalEntry[i].peGreen = (i >> pfd.cGreenShift) & GreenRange;
pPal->palPalEntry[i].peGreen = (unsigned char)(
(double)pPal->palPalEntry[i].peGreen * 255.0 / GreenRange);

pPal->palPalEntry[i].peBlue = (i >> pfd.cBlueShift) & BlueRange;
pPal->palPalEntry[i].peBlue = (unsigned char)(
(double)pPal->palPalEntry[i].peBlue * 255.0 / BlueRange);

pPal->palPalEntry[i].peFlags = (unsigned char) NULL;
}


// Create the palette
hRetPal = CreatePalette(pPal);

// Go ahead and select and realize the palette for this device context
SelectPalette(hDC,hRetPal,FALSE);
RealizePalette(hDC);

// Free the memory used for the logical palette structure
free(pPal);

// Return the handle to the new palette
return hRetPal;
}


// Select the pixel format for a given device context
void SetDCPixelFormat(HDC hDC)
{
int nPixelFormat;

static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // Size of this structure
1, // Version of this structure
PFD_DRAW_TO_WINDOW | // Draw to Window (not to bitmap)
PFD_SUPPORT_OPENGL | // Support OpenGL calls in window
PFD_DOUBLEBUFFER, // Double buffered mode
PFD_TYPE_RGBA, // RGBA Color mode
8, // Want 8 bit color
0,0,0,0,0,0, // Not used to select mode
0,0, // Not used to select mode
0,0,0,0,0, // Not used to select mode
16, // Size of depth buffer
0, // Not used to select mode
0, // Not used to select mode
PFD_MAIN_PLANE, // Draw in main plane
0, // Not used to select mode
0,0,0 }; // Not used to select mode

// Choose a pixel format that best matches that described in pfd
nPixelFormat = ChoosePixelFormat(hDC, &pfd);

// Set the pixel format for the device context
SetPixelFormat(hDC, nPixelFormat, &pfd);
}



// Entry point of all Windows programs
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg; // Windows message structure
WNDCLASS wc; // Windows class structure
HWND hWnd; // Storeage for window handle


// Register Window style
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);

// No need for background brush for OpenGL window
wc.hbrBackground = NULL;

wc.lpszMenuName = NULL;
wc.lpszClassName = lpszAppName;

// Register the window class
if(RegisterClass(&wc) == 0)
return FALSE;


// Create the main application window
hWnd = CreateWindow(
lpszAppName,
lpszAppName,

// OpenGL requires WS_CLIPCHILDREN and WS_CLIPSIBLINGS
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,

// Window position and size
100, 100,
250, 250,
NULL,
NULL,
hInstance,
NULL);

// If window was not created, quit
if(hWnd == NULL)
return FALSE;


// Display the window
ShowWindow(hWnd,SW_SHOW);
UpdateWindow(hWnd);

// Process application messages until the application closes
while( GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return msg.wParam;
}



// Window procedure, handles all messages for this program
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
static HGLRC hRC; // Permenant Rendering context
static HDC hDC; // Private GDI Device context

switch (message)
{
// Window creation, setup for OpenGL
case WM_CREATE:
// Store the device context
hDC = GetDC(hWnd);

// Select the pixel format
SetDCPixelFormat(hDC);

// Create the rendering context and make it current
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);

// Create the palette
hPalette = GetOpenGLPalette(hDC);

// Create a timer that fires 30 times a second
SetTimer(hWnd,33,1,NULL);

SetupRC();

break;

// Window is being destroyed, cleanup
case WM_DESTROY:
// Kill the timer that we created
KillTimer(hWnd,101);

// Deselect the current rendering context and delete it
wglMakeCurrent(hDC,NULL);
wglDeleteContext(hRC);

// Delete the palette
if(hPalette != NULL)
DeleteObject(hPalette);

// Tell the application to terminate after the window
// is gone.
PostQuitMessage(0);
break;

// Window is resized.
case WM_SIZE:
// Call our function which modifies the clipping
// volume and viewport
ChangeSize(LOWORD(lParam), HIWORD(lParam));
break;

// The painting function. This message sent by Windows
// whenever the screen needs updating.
case WM_PAINT:
{
// Call OpenGL drawing code
RenderScene();

// Call function to swap the buffers
SwapBuffers(hDC);
}
break;


// Windows is telling the application that it may modify
// the system palette. This message in essance asks the
// application for a new palette.
case WM_QUERYNEWPALETTE:
// If the palette was created.
if(hPalette)
{
int nRet;

// Selects the palette into the current device context
SelectPalette(hDC, hPalette, FALSE);

// Map entries from the currently selected palette to
// the system palette. The return value is the number
// of palette entries modified.
nRet = RealizePalette(hDC);

// Repaint, forces remap of palette in current window
InvalidateRect(hWnd,NULL,FALSE);

return nRet;
}
break;


// This window may set the palette, even though it is not the
// currently active window.
case WM_PALETTECHANGED:
// Don't do anything if the palette does not exist, or if
// this is the window that changed the palette.
if((hPalette != NULL) && ((HWND)wParam != hWnd))
{
// Select the palette into the device context
SelectPalette(hDC,hPalette,FALSE);

// Map entries to system palette
RealizePalette(hDC);

// Remap the current colors to the newly realized palette
UpdateColors(hDC);
return 0;
}
break;


default: // Passes it on if unproccessed
return (DefWindowProc(hWnd, message, wParam, lParam));

}

return (0L);
}

kimeya
23rd November 2008, 02:48 PM
کاوه جان من سورسها رو چطوری بگیرم.

Admin
24th November 2008, 04:35 AM
کاوه جان من سورسها رو چطوری بگیرم.

سورس ها به صورت کد قرار داده شده اند.

شما با دیدن نمونه ی برنامه ، می تونید سورس اون رو کپی کنید و در کامپایلر خودتون اجرا کنید..!

البته Include ها رو از یاد نبری ..! ;)

Victor007
16th October 2009, 09:05 PM
سلام
کسی از دوستان میتونه منبعی رو برای یادگیری مقدماتی OpenGL معزفی کنه ؟

Admin
16th October 2009, 09:39 PM
سلام
کسی از دوستان میتونه منبعی رو برای یادگیری مقدماتی opengl معزفی کنه ؟

من در این مورد کتابی به زبان اصلی دارم.

اگه به دردتون می خوره بگید آپلود کنم.

موفق باشید

Victor007
17th October 2009, 09:34 AM
اگر لطف کنید و اپلود کنید ممنون می شم

mehdijalili
15th January 2010, 12:34 AM
باسلام و تشکر از مطالب مفیدتان من برنامه های جنابعالی را در محیط borland c اجرا می کنم به جای اینکلود های تعریفی چه بنویسم و کدام ها را اضافه کنم

mehdijalili
15th January 2010, 12:40 AM
سلام من تو borland می خوام برنامه رو اجرا کنم به جای
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenG#include
چی بنویسم

Admin
16th January 2010, 09:47 AM
سلام دوست من ...

همون طور که در این بخش گفته شد شما باید Include های مربوط به برنامه رو به جای اون بخش اولی قرار بدهید.

Include های برنامه شامل موارد زیر هستن که همگی رو شما در اول برنامه تون وارد کنید و بعد کامپایل کنید...





#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>






البته من همه رو میگم وارد کنید که حتما برنامه Include ی کم نداشته باشه.

و گر نه در حالت عادی به Include های زیر نیاز خواهید داشت.



#include <graphics.h>
#include <stdlib.h>
#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>





در ضمن برای کامپایل شدن برنامه حتما باید فایل های GLUT رو در مسیر برنامه ی Visual C++ کپی کرده باشید...

موفق باشید ;)

mehdijalili
16th January 2010, 03:44 PM
سلام با تشکر من مشکل قبلیم حل شد فقط یه خطا دارم و اینه
#error BGI graphics not supported under Windows

به نظر شما این خطا از کجاست:-?

Admin
16th January 2010, 03:47 PM
فایل های glut شما درسته ؟

درست کپی کردی ؟

Admin
16th January 2010, 03:54 PM
روی Include ها این رو یه بار حذف کن ببین درست میشه ؟


#include <windows.h> // use as needed for your system

mehdijalili
16th January 2010, 03:59 PM
فایل های glut شما درسته ؟

درست کپی کردی ؟

من فایلهای glu32.dll
glut.dll
opengl32.dll
glut32.dll
اینها dll ها

h.GLAUX
GL.h
GLU.h
. ...
اگه لطف کنید اون فایل های مورد نیاز رو لینک بدید ممنون می شم یا پستشو ذکر کنید

mehdijalili
16th January 2010, 04:02 PM
روی Include ها این رو یه بار حذف کن ببین درست میشه ؟


#include <windows.h> // use as needed for your system

نه آقا مصطفی حل نشد همون error می ده

Admin
16th January 2010, 05:17 PM
من فایلهای glu32.dll
glut.dll
opengl32.dll
glut32.dll
اینها dll ها

h.GLAUX
GL.h
GLU.h
. ...
اگه لطف کنید اون فایل های مورد نیاز رو لینک بدید ممنون می شم یا پستشو ذکر کنید

فایل های مربوطه همین ها هستن که خودتون گفتید ...
اینها رو درست کپی کردین پس ...

در ضمن برنامه ای که دارین اجرا می کنین کدوم یکیشونه ؟

Admin
16th January 2010, 05:19 PM
البته این رو در نظر داشته باشید که گاها ایرادات جزئی خود کامپایلر از برنامه میگیره که باید تو متن برنامه ها دقت بیشتری داشته باشین.

ولی برای تست اولین برنامه ای که گذاشتم رو خودتون کامپایل کنید ... اگه مشکلی نداشت باید بقیه رو هم کامپایل کنه مگر اینکه مشکلاتی در متن برنامه باشه و اگه کامپایل نکرد ایراد در فایلهای مربوط به OpenGL هست.

موفق باشید

mehdijalili
16th January 2010, 05:42 PM
من برنامه حرکت در تونل و دنیای کره ها رو کامپایل کردم همش از فایل graphics.h ایراد میده
من دیگه موندم !!!!!

mehdijalili
16th January 2010, 05:49 PM
ضمنا من برنامه ها تو borland C اجرا می کنم

ضمنا اگر یه بازی کوچک سه بعدی دارین خیلی گیر اونم ممنون می شم کمکم کنید

Admin
16th January 2010, 08:58 PM
این پست همین تاپیک یه بازیه کوچیکه ...

http://njavan.com/forum/showpost.php?p=2584&postcount=55

این پست هم مثل یه بازی می مونه.

من جهان کره ها رو روی Visual اجرا کردم مشکلی نداشته.

http://njavan.com/forum/showpost.php?p=2585&postcount=56

ایرادات جزئی به نظر من از کامپایلره ...

روی Visual هم یه تستی بزنید
موفق باشید

mehdijalili
16th January 2010, 09:06 PM
این پست همین تاپیک یه بازیه کوچیکه ...

http://njavan.com/forum/showpost.php?p=2584&postcount=55
موفق باشید

سلام مجدد آقا مصطفی منظورم از یک بازی ساده یک بازی یک فایلی باشه که با همین
include های استاندارد کار کنه در حد شلیک یک گلوله و یا حرکت با کی بورد (یک توپ در یک صفحه)
شرمنده زیاد مزاحم می شم

Admin
16th January 2010, 09:44 PM
به اینها هم نگاهی بندازین...

برنامه ی چینش آجر بر روی هم و ساخت دیوار ...

http://njavan.com/forum/showpost.php?p=2514&postcount=14

برنامه ی اتم ... كه چرخش مولكولها به صورت انیمیشن رو به دور هسته نمایش می ده.

http://njavan.com/forum/showpost.php?p=2556&postcount=32

برنامه ای كه گردش زمین و ماه رو به دور خورشید نمایش داده با جلوه های نور پردازی و سه بعدی

http://njavan.com/forum/showpost.php?p=2559&postcount=35

برنامه چرخش اتم ها به دور هسته ... به همراه امكانات زوم و چرخش سریع اتم ها.

http://njavan.com/forum/showpost.php?p=2564&postcount=39

تونل ..!
با کیبورد در تونل پیش برین و مثل یه بازی می مونه ...

http://njavan.com/forum/showpost.php?p=2586&postcount=57

چند نمونه از این تاپیک رو براتون گذاشتم که بدونین توی نمونه های قرار داده شده همه چی هست و میشه اینها رو به شکل دلخواه هم در آورد.

موفق باشید

mehdijalili
17th January 2010, 04:11 PM
:">سلام مجدد من برنامه های قبل رو تو borland اجرا کردم ایراد نمی ده اما تونل و کره و دو سه تای دیگه رو که اجرا می کنم از graphic.h ایراد می ده اگه ممکن خودتون هم تو borland اجرا کنید نتیجه ببینید چی میشه اگه شد لینک کامپایلر borland ر و برام بزارین یل لینک graphics.h رو

خیلی ممنون

Admin
18th January 2010, 01:12 PM
:">سلام مجدد من برنامه های قبل رو تو borland اجرا کردم ایراد نمی ده اما تونل و کره و دو سه تای دیگه رو که اجرا می کنم از graphic.h ایراد می ده اگه ممکن خودتون هم تو borland اجرا کنید نتیجه ببینید چی میشه اگه شد لینک کامپایلر borland ر و برام بزارین یل لینک graphics.h رو

خیلی ممنون

دوست من ...

اگر ممکنه برنامه ها رو توی Visual Studio C++ یک بار دیگه تست بزن

موفق باشی

sara dehkordi
19th January 2010, 09:08 AM
سلام و خسته نباشيد:
واقعا ممنون از مطالب خوبتون.من در مورد روش نورپردازي راديوسيتي يك پروژه دارم.الان بايد يك تصوير مش بندي شده را با توابع openGL نورپردازي كنم.اما نمي دونم چطور يك تصوير و مختصات ناحيه هايش را در ويژوال بيارم.
تصويرم شامل يك چهار ديواريه كه با 3DMAX درست كردم.حالا بايد با فرمول راديوسيتي نورپردازيش كنم .
خواهش ميكنم...خواهش ميكنم..كمكم كنيد
ممنون

Admin
19th January 2010, 09:37 AM
سلام و خسته نباشيد:
واقعا ممنون از مطالب خوبتون.من در مورد روش نورپردازي راديوسيتي يك پروژه دارم.الان بايد يك تصوير مش بندي شده را با توابع openGL نورپردازي كنم.اما نمي دونم چطور يك تصوير و مختصات ناحيه هايش را در ويژوال بيارم.
تصويرم شامل يك چهار ديواريه كه با 3DMAX درست كردم.حالا بايد با فرمول راديوسيتي نورپردازيش كنم .
خواهش ميكنم...خواهش ميكنم..كمكم كنيد
ممنون

واقعیتش تا اونجا که من OpenGL کار کردم و اطلاع دارم این برنامه نویسی گرافیکی ربطی به 3D-Max نداره ...

چرا که تمامی کارهای گرافیکی انجام شده کد نویسی است ... و از قالب های آماده ی 3DMax استفاده ای نشده ...

اگر هم می شه استفاده کرد من در اون حد کار نکردم ;)

Admin
19th January 2010, 09:40 AM
به عنوان مثال شما این برنامه رو نگاه کنید ...

چند کره با موقعیت های مختصاتی متفاوت در صفحه قرار داده شده اند و عملیات نور پردازی به منبعیت خورشید روی اونها صورت گرفته ...

http://njavan.com/forum/showpost.php?p=2559&postcount=35

Admin
19th January 2010, 09:43 AM
برنامه ی بالا دو بعدی بود ...

اینم لینک سه بعدیش ....

http://njavan.com/forum/showpost.php?p=2559&postcount=35

که مانند چرخش کره های منظومه شمسی به دور خورشید می مونه.

به این هم نگاه کنید ...

http://njavan.com/forum/showpost.php?p=2570&postcount=44

عملیات نور پردازی توسط چیزی شبیه لامپ به دور شیء الماسی شکل.
در این برنامه تمامی جوارح به درستی نمایش داده شده و نور واقعی انعکاس می شود.

Admin
19th January 2010, 09:44 AM
اینم برنامه ی تاثیر نور با رنگ های مختلف روی اشیاء می باشد ...

http://njavan.com/forum/showpost.php?p=2571&postcount=45

sara dehkordi
20th January 2010, 09:03 AM
حتما شما درست ميگين...آخه اين چيزيه كه از من خواستن تصوير در 3Dmax و....
حالا ميتونم من اين چهار ديواريما با كد نويسي پس درست كنم؟
مي شه لطفا شما كمكم كنيد؟

ممنونم كه جوابما ميدين:)

Admin
20th January 2010, 02:30 PM
حتما شما درست ميگين...آخه اين چيزيه كه از من خواستن تصوير در 3Dmax و....
حالا ميتونم من اين چهار ديواريما با كد نويسي پس درست كنم؟
مي شه لطفا شما كمكم كنيد؟

ممنونم كه جوابما ميدين:)

واقعیتش من خیلی وقتیه که برنامه نویسی کار نکردم و چیز زیادی یادم نمونده ...

اما می تونین از برنامه های موجودی که خودم گذاشتم هم استفاده کنید.

یکی از برنامه ها اتفاقا برنامه دیواره که می تونین سورس رو برداشته و در Visual C++ اجرا کنید.

موفق باشید

Victor007
24th January 2010, 12:17 PM
سلام@};-
میشه تا فایلهای glu32.dll
glut.dll
opengl32.dll
glut32.dll
اینها dll ها
h.GLAUX
GL.h
GLU.h
که رو در سایت بزارید و بگید کجاها باید کپی بشن ؟

kamale
31st January 2010, 10:45 PM
سلام و صد سلام.لطفا اگه زحمتی نیست ین برنامه ها رو به من برسونید.
( رسم خط،دایره، بیضی به روش نقطه میانی و dda. ممنون میشم.@};-8->

zanbooor_2006
29th May 2010, 07:22 AM
salam
yefekri be ma ham bokon agha mostafa
barnameye creensaver ba opengl
mer30

zanbooor_2006
29th May 2010, 07:29 AM
"#include "stdafx.h
"#include "stdafx.h
این دو کد برای من خطا میده. ببخشید می تونید دلیلش رو بگید؟

zanbooor_2006
29th May 2010, 07:36 AM
ببخشید من رشته ام کامپیوتره استادمون گفته که یک برنامه ی Screen Savar طراحی کنیم ؛ این برنامه ها رو تازه نوشتین؟ اگه نشون استاد بدم تابلو نمی شه؟ {i dont want to see}

آبجی
29th May 2010, 02:53 PM
ببخشید من رشته ام کامپیوتره استادمون گفته که یک برنامه ی screen savar طراحی کنیم ؛ این برنامه ها رو تازه نوشتین؟ اگه نشون استاد بدم تابلو نمی شه؟ {i dont want to see}

دوست گرامی لطفا در زدن پست دقت کنید تا مجبور به حذف ان نشویم .

در مورد اینکه نوشتید تازه نوشته شده این برنامه ها باید بگم که خیر این برنامه ها سال 2008 نوشته شده و در شهریور ماه روی سایت گذاشته شده .

موفق باشید .

sima.z
4th June 2010, 09:56 AM
سلام خدمت مدیران سایت

من در برنامه openglمشکلی که دارم اینه که بعد از اجرای هر برنامه ای این پیغام خطاا رو میده

Linking c:\bc5\bin\file name.exe

Error: ‘c:\bc5\lib\Glut.lib’ contains invalid OMF record.type 0X21

مطمعنم که برنامه مشکلی نداره چون قبلا" در کامپیوتر دیگر اجرا شده

فایلهای opengl هم قبلا" در کامپیوتر دیگری استفاده کردم و نصب کردم

اگر لطف کنید مشکل من رو حل کنید سپاسگذارم

Admin
4th June 2010, 10:17 AM
Linking c:\bc5\bin\file name.exe

Error: ‘c:\bc5\lib\Glut.lib’ contains invalid OMF record.type 0X21


سلام

فایل های Glut رو که در سیستم قبلی اجرا کرده بودید رو در همین سیستم هم نصب کردید ؟
فکر می کنم درست نصب نشده باشن که این چنین ارور میده.

یا اینکه شما پروژه رو مجددا روی سیستم گذاشتی و مستقیما اجرا می کنی ... درسته ؟

اگه سورس پروژه رو در پروژه ی جدیدی که ایجاد می کنی قرار بدی و دوباره تست بزنی فکر می کنم مشکل رفع بشه

alip30c
4th June 2010, 08:35 PM
سلام خدمت مدیران سایت

من در برنامه openglمشکلی که دارم اینه که بعد از اجرای هر برنامه ای این پیغام خطاا رو میده

Linking c:\bc5\bin\file name.exe

Error: ‘c:\bc5\lib\Glut.lib’ contains invalid OMF record.type 0X21

مطمعنم که برنامه مشکلی نداره چون قبلا" در کامپیوتر دیگر اجرا شده

فایلهای opengl هم قبلا" در کامپیوتر دیگری استفاده کردم و نصب کردم

اگر لطف کنید مشکل من رو حل کنید سپاسگذارم


سلام
فکر کنم باید فایل glut.dll توی windows/system32 پیست کنین.

dodor
4th June 2010, 08:56 PM
سلام دوست من!


Copy glut.h to c:\bc5\include\GL.
Copy glut.dll and glut32.dll to c:\windows\system
Again, do not copy the .lib files anywhere as they are for MSVC++.
Go to a DOS prompt and type the following:

cd \bc5\lib
implib glut.lib c:\windows\system\glut.dll
implib glut32.lib c:\windows\system\glut32.dll


موفق باشید.

jojepanbeyi
26th December 2010, 12:52 PM
شرح:
ابتدا روز هست و خورشيد از سمت چپ ميياد و آسمون روشن ميشه ، سپس خورشيد به سمت راست ميره و آسمون تيره ميشه و بعد از ناپديد شدن خورشيد آسمون تاريك و ستاره ها نمايان ميشند.





#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax,maxx,maxy;
int poly[16];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "f:\\borlandc\\bgi");
/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
cleardevice();
setbkcolor(9);
rectangle(0, 0, getmaxx(), getmaxy());

/************************** draw (chaman)********************************/
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
/* putpixel(200,420,6);
setfillstyle(1,6);
fillellipse(200, 400,10 , 50);
/************************** draw (khorshid) ***********************/
/******** step 1 **************/
setfillstyle(1,14);
fillellipse(20, 200,20,20);
/*********** step 2 *************/
delay(3500);
cleardevice();
setbkcolor(9);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,10);
fillpoly(8, poly);
setfillstyle(1,14);
fillellipse(300,50,20,20);
/****************************** step 3 *********************************/
delay(3500);
cleardevice();
setbkcolor(1);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
setfillstyle(1,14);
fillellipse(620, 200,20 , 20);
/***************** step 4 *************/
delay(3500);
cleardevice();
setbkcolor(0);
rectangle(0, 0, getmaxx(), getmaxy());
poly[0] = 0;
poly[1] = 500;
poly[2] = 1;
poly[3] = 460;
poly[4] = 150;
poly[5] = 420;
poly[6] = 200;
poly[7] = 450;
poly[8] = 350;
poly[9] = 420;
poly[10] = 400;
poly[11] = 450;
poly[12] = 550;
poly[13] = 420;
poly[14] = 680;
poly[15] =480;
setfillstyle(1,2);
fillpoly(8, poly);
/*********************** star ************************/
putpixel(100,100,15);
putpixel(150,180,15);
putpixel(250,180,15);
putpixel(150,280,15);
putpixel(350,280,15);
putpixel(350,80,15);
putpixel(150,80,15);
putpixel(500,280,15);
putpixel(350,280,15);
putpixel(550,280,15);
putpixel(600,180,15);
setfillstyle(1,15);
fillellipse(300, 50,5 , 25);
// arc(300, 100, 290, 140, 30);
/****************************** clean up *****************************/
getch();
closegraph();
return 0;
}
سلام دوست عزیز این کد کاری که شما گفتید نمیکنه[negaran]

zy
3rd February 2011, 10:28 AM
سلام چرا وقتی من این برنامه ها را در c++ می نویسم نمی تواند windowseوسه تای بعد آن را باز کند به همین دلیل از تمام خطوط برنامه ایراد می گیرد حالا باید دچکار کنم؟

gahramanihamed
1st November 2011, 10:18 PM
سلام و خسته نباشید راستش من هنوز
نتونستم هیچ کدوم از برنامه هارو اجرا کنم فقط تو نتپد کپی میکنم
برا آینده
و ممنونم
دنبال یه برنامه تو open GL میگردم که تیر و کمان رو رسم کنه و کمان پرتاب بشه و در حین پرتاب طریقه راه رفتن نمایش داده بشه
ممنون میشم اگه سورس کاملش رو برام آپلود کنید
موفق و موید باشید

majid1605
13th November 2011, 08:54 PM
من توی پرژه از کد زیر واسه معرف هدر فایلها استفاده کردم



#include <windows.h>
#include <gl/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#pragma comment(lib,"OPENGL32.LIB")
#pragma comment(lib,"glut32.lib")
#pragma comment(lib,"GLU32.LIB")
#pragma comment(lib,"GLAUX.LIB")


ولی به این هدر فایل کامپایلر گیر میده


#include <GL/glut.h>

کسی میدونه مشکل چیه ؟ از VS 2010 استفاده می کنم.


Cannot open include file: 'GL/glut.h': No such file or directory

متن پیغام کامپایلر
می خوام بدونم این هدر فایل جداست
کسی اون داره بهم بده

یه سوال دیگه آخرین نسخه Opengl چنده منظورم کتابخونه است نه درایور و از کجا می تونم گیرش بیارم توی سایت اصلی چیزی نتونستم پیدا کنم

Admin
13th November 2011, 09:08 PM
کسی میدونه مشکل چیه ؟ از vs 2010 استفاده می کنم.


سلام
ایراد اینه که توابع glut رو بر روی کامپایلر درست نصب نکردین .!

meysam_gbt
4th December 2011, 02:05 PM
salam khaste nabashid mishe ye barname sade zamin fotbal baraye man befrestid mamnon misham

tanhay
26th January 2012, 11:13 PM
سلام،جناب مهندس اول از هم تشكر ميكنم از سايت بسيار خوبت
و خسته نباشيد ميگم خدمتت كه واقعا روي مطالب زحمت كشيده ايد. يه سوال داشتم از خدمتتون اميدوارم زود جوابمو بدي چون اصلا وقت ندارم به خاطر اينكه بايد يه برنامه ايي رو تحويل بدم
منظور از نوشتن دو خط زير در برنامه ها چيست ؟به جاي ..ژ.. چه بايد بنويسيم لطفا راهنمايي كنيد باتشكر.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit

nilda_15
21st April 2012, 10:18 AM
سلام،جناب مهندس اول از هم تشكر ميكنم از سايت بسيار خوبت
و خسته نباشيد ميگم خدمتت كه واقعا روي مطالب زحمت كشيده ايد. يه سوال داشتم از خدمتتون اميدوارم زود جوابمو بدي چون اصلا وقت ندارم به خاطر اينكه بايد يه برنامه ايي رو تحويل بدم
منظور از نوشتن دو خط زير در برنامه ها چيست ؟به جاي ..ژ.. چه بايد بنويسيم لطفا راهنمايي كنيد باتشكر.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // OpenGL toolkit
سلام
منم همین مشکل رو دارم بایدچکار کنم برنامه درست اجرا بشه؟؟؟؟

Admin
21st April 2012, 11:10 AM
سلام
منم همین مشکل رو دارم بایدچکار کنم برنامه درست اجرا بشه؟؟؟؟

سلام ...

همون طور که در این بخش قبلا گفته شده شما باید Include های مربوط به برنامه رو به جای اون بخش اولی قرار بدهید.

Include های برنامه شامل موارد زیر هستن که همگی رو شما در اول برنامه تون وارد کنید و بعد کامپایل کنید...





#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>






البته من همه رو میگم وارد کنید که حتما برنامه Include ی کم نداشته باشه.

و گر نه در حالت عادی به Include های زیر نیاز خواهید داشت.



#include <graphics.h>
#include <stdlib.h>
#include "stdafx.h"
#include <windows.h> // use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>





در ضمن برای کامپایل شدن برنامه حتما باید فایل های GLUT رو در مسیر برنامه ی Visual C++ کپی کرده باشید...

موفق باشید ;)

nilda_15
21st April 2012, 11:30 AM
این فایل روgraphics.h ندارم میشه واسم پیوست کنین هرچی اینکلود وابسته به این هست
آخه خودم از این سایت دانلود کردم http://www.koders.com/cpp/fid2F91A91DAEC5EB83872CCFE65F574F3271AE5018.aspx
ولی تیکه به تیکه اینکلود جدید میخواد
ممنون و شرمنده

Admin
21st April 2012, 11:44 AM
این فایل روgraphics.h ندارم میشه واسم پیوست کنین هرچی اینکلود وابسته به این هست
آخه خودم از این سایت دانلود کردم http://www.koders.com/cpp/fid2F91A91...271AE5018.aspx
ولی تیکه به تیکه اینکلود جدید میخواد
ممنون و شرمنده

نیازی به اون نیست.
در پست بعدی توابع Glut رو کامل میذارم هم دانلود کنین هم یاد بگیرین کجا کپیش کنین.

موفق باشید

Admin
21st April 2012, 12:02 PM
فایل های glut رو براتون در این پست اتچ میکنم ...

به این صورت اقدام کنید ...

پس از دانلود فایل اتچ شده فایل های داخل پوشه را بصورت زیر در آدرس هایی که گفتم روی ویندوز کپی کنید و اگه درست نرم افزار رو نصب کرده باشید و کد رو اجرا کنید نباید مشکلی داشته باشید.

فایل glut.h رو در پوشه ی C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl کپی کنید.
فایل glut32.lib رو در پوشه ی C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib کپی کنید.
فایل glut32.dll رو در پوشه ی C:\Windows\System32 کپی کنید.

همین سه فایل رو کپی کنید و اجرا کنید برنامه رو.

توجه داشته باشید که این تغییرات مخصوص ویژوال C++ هست.

موفق باشی

stella_pbs
16th May 2012, 04:51 PM
سلام دوستان من يه پروژه دارم ميخواستم بهم كمك كنيد مرحله 1 : با استفاده از الگوریتم های رسم دایره و مستطیل و تبدیلات هندسی، شکل یک ماهواره را به صورت زیر رسم نمایید. ( مانند enterprise.gif )


مرحله 2: انیمیشن زیر را طوری بسازید که ماهواره شما دور سیاره ای در مرکز تصویر بچرخد. ( مانند enterprise2.gif)


مرحله 3: از توابع دید دو بعدی به نحوی استفاده کنید که انیمیشن خروجی به صورت زیر تبدیل شود. (مانند enterprise3.gif )
*راهنمایی: پنجره برش را روی یک لوزی حرکت دهید.



*برای دیدن تصاویر متحرک به 3 فایل تصویری ضمیمه شده مراجعه نمایید.

stella_pbs
16th May 2012, 04:53 PM
شكلاش هر كاري كردم نمياد اگ كسي ميتونه كمك كنه براش email ميكنم مرسي

Ahmad_T
3rd June 2012, 06:45 PM
سلام
دوستان من 3 تا برنامه كوچيك دارم (از همين فروم گرفتم اما يكم تغيير دادم) كسي هست كه اينا را واسم كامپايل كنه و فايل exe اونها را به من بده
كارم فوريه تا 17 بيشتر وقت ندارم كه ارائه بدم

Ahmad_T
4th June 2012, 10:19 AM
كسي نبود؟؟؟؟؟؟[negaran]

majid1605
5th June 2012, 02:28 PM
خودتون چرا کامپایل نمی کنید ؟

rayarasool
12th June 2012, 01:20 PM
من یه سوال دارم
چرا فقط اینا c++ اند
جاوا بذارین
میشه کسای دیگه هم بذارن
اصلا کسی جاوا می خونه
[soal]

1344
12th June 2012, 03:55 PM
واقعا عالی بودن ممنون...
به من که خیلی کمک کرد..[tashvigh][golrooz]

roya26
6th July 2012, 10:50 PM
با سلام و خسته نباشید خدمت مدیر و سایر دوستان
من یه برنامه باید بنویسم که یه ستاره ای هست که باید با حرکت ماوس بچرخه و همینطور از یه مکان مختصاتی بتونه به یه مکان دیگه بره و در آخر بشه اونو بزرگ و کوچیک کرد .
من توی قسمت حرکت با ماوسش موندم نمی دونم چجوری بنویسمش ، ممنون می شم راهنماییم کنید . چون واقعا گیر کردم [gerye]

soroush_tayyebi
7th July 2012, 04:13 PM
با سلام و خسته نباشید خدمت مدیر و سایر دوستان
من یه برنامه باید بنویسم که یه ستاره ای هست که باید با حرکت ماوس بچرخه و همینطور از یه مکان مختصاتی بتونه به یه مکان دیگه بره و در آخر بشه اونو بزرگ و کوچیک کرد .
من توی قسمت حرکت با ماوسش موندم نمی دونم چجوری بنویسمش ، ممنون می شم راهنماییم کنید . چون واقعا گیر کردم [gerye]
دانشجو پرندی ؟‌ :دی
کدت رو برام بفرست شاید تونستم کمکت کنم :)
اینم میلم :‌
soroush@tinamo.ir

roya26
11th July 2012, 11:57 PM
دانشجو پرندی ؟‌ :دی
کدت رو برام بفرست شاید تونستم کمکت کنم :)
اینم میلم :‌
soroush@tinamo.ir

ممنون
نه داانشجو نیستم برنامه رو برای کسی می خواستم بنویسم که کنسل شد [shademan]

ehsan_mr67
27th July 2012, 02:27 PM
سلام دوستان
من می خوام یکی از این برنامه ها رو کامپایل کنم .چه نرم افزاری باید داشته باشم و تو چه ویندوزی باید کار کنم ممنون میشم اگه کمک کنید!

بهار خانوم
13th November 2012, 10:32 PM
خیلی تشکر باحالن[cheshmak][cheshmak]

barhaman
13th January 2013, 05:00 PM
سلام خسته نباشید میشه برای من سورس این دوتا برنامه رو با c++در ویژال استودیوopenGl بزارید

1- یک مربع و مثلث که همزمان با چرخش حول مراکز خودشان بزرگ و کوچک شود؟
2-شبیه سازی حرکت یک آدمک در هنگام راه رفتن ؟
ممنون میشم

فقط خیلی فوریه[dooa] خواهشا زود جواب بدین

sahar-s
4th February 2013, 07:31 PM
سلام خسته نباشید میشه برای من سورس این دوتا برنامه رو با c++در ویژال استودیوopenGl بزارید

1- یک مربع و مثلث که همزمان با چرخش حول مراکز خودشان بزرگ و کوچک شود؟
2-شبیه سازی حرکت یک آدمک در هنگام راه رفتن ؟
ممنون میشم

فقط خیلی فوریه[dooa] خواهشا زود جواب بدین

منم شدیدا به این دو تا برنامه نیاز دارم[dooa]
خواهشا کمک کنید [narahat]
این ها که برای شما خیلی ساده هستند

ali65509
11th April 2013, 08:43 PM
سلام خسته نباشید
خواهشا کد برنامه حرکت سه بعدی وتصادفی توپ در صفحه را بزارید.
باتشکر از زحمت و توجهتون.

- - - به روز رسانی شده - - -

سلام خسته نباشید
خواهشا کد برنامه حرکت سه بعدی وتصادفی توپ در صفحه را بزارید.
باتشکر از زحمت و توجهتون.

ali65509
13th April 2013, 12:47 PM
کسی نبود جواب بدهد؟

- - - به روز رسانی شده - - -

کسی نبود جواب بدهد؟

uni34
19th May 2013, 01:42 PM
سلام چی میشه واسه منم یه برنامه گرافیکی بذارین که "با حروف فارسی بشه تسکرین سیور درست کرد"
[narahat]

uni34
19th May 2013, 03:08 PM
سلام چی میشه واسه منم یه برنامه گرافیکی بذارین که "با حروف فارسی بشه اسکرین سیور درست کرد"
کمکم کنیدددددددددددددددددددددد ددددددد

uni34
19th May 2013, 03:15 PM
لطفآ کسی جواب بده اگه کسی برنامه اسکرین سیور باحروف فارسی داره واسم ایمیل کنه
uni.sama34@yahoo.com

مرضیه پرهیزکار
3rd June 2013, 06:00 PM
سلام خسته نباشید .
ببخشیید چطور میشه اسممو با اشکال هندسی طراحی کنم . لطفا کمکم کنین ممنونم

faezeh-d
8th April 2014, 08:39 PM
سلام ممنون از مطالب خیلی خوبتون. من می خواستم برنامه آونگ را بنویسم یا یک گوی بذارم که حرکت آونگ را داشته باشه ولی نتونستم می شه کمکم کنید. چرخش باید با چه فرمولی به صورت نیم دایره باشه؟[soal][soal]

استفاده از تمامی مطالب سایت تنها با ذکر منبع آن به نام سایت علمی نخبگان جوان و ذکر آدرس سایت مجاز است

استفاده از نام و برند نخبگان جوان به هر نحو توسط سایر سایت ها ممنوع بوده و پیگرد قانونی دارد