一 新建一工程,设保存为OpenGLApp.dpr,窗口为Form1
二 在Form1中加入Panel1和Button1,unit1.pas代码为
unit Unit1;
interface
uses
Windows,messages,Sysutils,classes,graphics,controls,Forms,Dialogs,OpenGL,Exectrs,Stdctrls;
type
TForm1=class(TForm)
Panel1:TPanel;
Button1:TButton;
procedure FormCreate(Sender:TObject);
procedure PanelResize(Sender:TObject);
procedure FormDestroy(Sender:TObject);
procedure FormKeyPress(Sender:TObject;var key:char);
procedure Button1Click(Sender:TObject);
private
rc:HGLRC;
dc:HDC;
ElapsedTime,AppStart,LastTime:dword;
procedure glDraw;
procedure Idle(Sender:TObject;var Done:boolean);
public
end;
var
Form1:TForm1;
implementation
{$R *.DFM}
procedure TForm1.glDraw()
begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0,0,-4);
glRotatef(ElapsedTime/10,0,1,0);
glBegin(GL_TRIANGLES);
glColor3f(1,00); glVertex(-1,-1,0);
glColor3f(0,10); glVertex(1,-1,0);
glColor3f(0,0,1); glVertex(0,1,0);
glEnd()
end;
//OpenGL初始化
procedure glInit()
begin
glClearColor(0.0,0.0,0.0,0.0);
glShadeModal(GL_SMOOTH);
glClearDepth(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glHint(GL_DEPSPECTIVE_CORRECTION_HINT,GL_NICEST);
end;
procedure TForm1.FormCreate(Sender:TObject);
var pfd:TPIXELFormatDescriptor;
pf:integer;
begin
dc :=GetDC(Panel1.Handle);
pfd.nSize :=sizeof(pfd); //让Panel1获取句柄
pfd.dwFlags:=PFD_DRAW_TO_WINOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER or 0);
pfd.ColorBits :=32;
pf :=ChoosePixelFormat(dc,@pfd);
SetPixelFormat(dc,pf,@pfd);
rc :=wglCreateContext(dc);
wglMakeCurrent(dc,rc);
glInit;
PanelResize(Sender);
AppStart :=GetTickCount();
Application.OnIdle :=Idle;
end;
procedure TForm1.FormDestroy(Sender:TObject);
begin
wglMakeCurrent(0,0);
wglDeleteContext(rc);
end;
procedure TForm1.Idle(Sender:TObject;var Done:Boolean);
begin
Done :=False;
LastTime :=ElapsedTime;
ElapsedTime :=GetTickCount()-AppStart;
glDraw();
SwapBuffers(DC);
end;
procedure TForm1.Resize(Sender:TObject);
begin
glVewport(0,0,Penel1.Width,panel1.Height);
glMatrixMod(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,0,Panel1.Width/Panel1.Height,1,0,500.0);
glMatrixMode(GL_MODEVIEW);
end;
procedure TForm1.FormKeyPress(Sender:TObject;var Key:char);
begin
if key=#27 then
Close;
end;
procedure TForm1.Button1Click(Sender:TObject);
begin
Close;
end;
end.