我正在尝试用Delphi和OpenGL创建一些基本的应用程序。我需要在屏幕上绘制一些2D图像。
下面是我的代码:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, OpenGL;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
GLContext : HGLRC;
glDC: HDC;
errorCode: GLenum;
openGLReady: Boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
pfd: TPixelFormatDescriptor;
FormatIndex: Integer;
begin
FillChar(pfd,SizeOf(pfd),0);
with pfd do
begin
nSize := SizeOf(pfd);
nVersion := 1; {The current version of the desccriptor is 1}
dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL;
iPixelType := PFD_TYPE_RGBA;
cColorBits := 24; {support 24-bit color}
cDepthBits := 32; {depth of z-axis}
iLayerType := PFD_MAIN_PLANE;
end;
glDC := getDC(handle);
FormatIndex := ChoosePixelFormat(glDC,@pfd);
SetPixelFormat(glDC,FormatIndex,@pfd);
GLContext := wglCreateContext(glDC);
wglMakeCurrent(glDC,GLContext);
OpenGLReady := true;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle,0);
wglDeleteContext(GLContext);
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
if not openGLReady then
exit;
{background}
glClearColor(0.1,0.0,0.1,0.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity; // Reset The View
glTranslatef(0.0, 0, 0.0);
glRotateF (360, 0.0, 0.0, 1.0);
glBegin( GL_POLYGON ); // start drawing a polygon
glColor3f( 1.0, 0.0, 0.0);
glVertex3f( 0.0, 0.5, 0.0 ); // Top
glColor3f(0.0, 1.0, 0.0);
glVertex3f( 0.5, -0.5, 0.0 ); // Bottom Right
glColor3f(0.0, 0.0, 1.0);
glVertex3f( -0.5, -0.5, 0.0 ); // Bottom Left
glEnd;
glFlush;
{error checking}
errorCode:=glGetError;
if errorCode<>GL_NO_ERROR then
raise Exception.Create('Error in Paint'#13+gluErrorString(errorCode));
SwapBuffers(wglGetCurrentDC);
glFlush();
end;
procedure TForm1.FormResize(Sender: TObject);
begin
if not openGLReady then
exit;
glViewPort(0,0,ClientWidth,ClientHeight);
glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0);
errorCode := glGetError;
if errorCode<>GL_NO_ERROR then
raise Exception.Create('FormResize:'+gluErrorString(errorCode));
end;
procedure GLInit;
begin
// set viewing projection
glMatrixMode(GL_PROJECTION);
glFrustum(-0.1, 0.1, -0.1, 0.1, 0.3, 15.0);
// position viewer
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
end;
end.
一切都正常,没有错误,但最后我没有得到一个深绿色的表格,表格保持不变(灰色)。
这有什么不对吗?
我已经启动应用程序从IDE和作为独立的应用程序。我正在使用Delphi 10.4和Windows 10。我已经检查和opengl32.dll是在System32文件夹。
1条答案
按热度按时间eqzww0vc1#
您的代码中有几个问题。首先,您从未调用
GLInit
过程,因此从未设置投影矩阵。此外,GLInit
使用glFrustum
,而窗体大小调整处理程序使用glOrtho
。您需要哪个?我找到了一个非常老的OpenGL示例应用程序,我做了几十年前,你可能会学习(在这里稍微现代化的形式):
但是,请注意形容词 old。现在,您根本不应该使用固定管道API。