Overview

OpenGL is a usefull collection of classes for creating OpenGL projects in FreePascal. It wraps the most common OpenGL objects (such as RenderContext, Textures, VertexArray, FrameBuffer, …) into simple classes. Also it comes with some data types all around graphic programming.

  1. dglOpenGL and dglOpenGLES
  2. The render context
  3. OpenGL object classes
    1. TglcArrayBuffer
    2. TglcBitmap
    3. TglcFrameBufferObject
    4. TglcShaderProgram
    5. TglcVertexArrayObject
  4. Helper classes
    1. TglcCamera
    2. TglcLight and TglcMaterial
  5. Helper types

Links

1. dglOpenGL and dglOpenGLES

The files dglOpenGL.pas and dglOpenGLES.pas contains all necessary constants, types and functions to make calls to the OpenGL or OpenGLES library. Also it cares about dynamically loading the needed function pointers from the library. If you want to write pure OpenGL code, this two files is all you need. The rest of this project is just to make your live easier.

dglOpenGL.pas and gdlOpenGLES.pas are maintained by the Delphi OpenGL Community.

2. The render context

The render context class is used to create a OpenGL render context. It is the first step you have to do before you continue writing your OpenGL App.

First we need to know wich context class we have to create, because every operation system (e.g. Windows, Linux) and every UI service (e.g. X11, Gtk2) has it’s own way to create a render context. Luckily this projects has a simple way to do this.

var ContextClass: TglcContextClass;
ContextClass := TglcContext.GetPlatformClass();

The second think we need is a suitable pixel format descriptor that will change the pixel format of our device context to our needs. This is as simple as the last step.

var cpfs: TglcContextPixelFormatSettings;
cpfs := ContextClass.MakePF();

Now we can create our context object. This will not create the render context! The context objects is a simple object to manage the render context. The render context will be created later.

var Context: TglcContext;
Context := ContextClass.Create(aWinControl, cpfs);

Now everything is ready to use. We can create our render context.

!Note: This step can be done in a separate thread, if yout want to do some offscreen rendering. But be carefull the render context can only be used in the thread were it was created.

Context.BuildContext();

Congratulation, you have created a valid render context and can start normal rendering now. After you are finished you should cleanup everything. Never mind if you forget to do this, the TglcContext will care about that for you.

Context.CloseContext();

Last step: you have to free the context object.

FreeAndNil(Context);

3. OpenGL object classes

3.1. TglcArrayBuffer

Array buffers, also known as vertex buffer objects, are used to store vertex data in video memory. So you can render your geometry very fast. Before you upload your data to the video memory you need to define what data you want to upload. We will define a vertex that has a three dimensional position, a two dimensional texture position and a three dimensional normal vector.

type
  TVertex = packed record
    pos: TgluVector3f; // vertex position
    tex: TgluVector2f; // texture coordinates
    nor: TgluVector3f; // normal vector
  end;
  PVertex = ^TVertex;

Once you have defined your data, you can create a array buffer and upload your data to the video memory. In this example we use indexed vertex rendering. Each vertex is only stored once in our vertex array and then we will define an index array that describes wich vertices have to be rendered.

var
  VertexBuffer: TglcArrayBuffer;
  IndexBuffer: TglcArrayBuffer;
  p: Pointer;
 
  { create our buffer objects }
  VertexBuffer := TglcArrayBuffer.Create(TglcBufferTarget.btArrayBuffer);
  IndexBuffer := TglcArrayBuffer.Create(TglcBufferTarget.btElementArrayBuffer);
 
  { write vertex data to vertex buffer }
  vBuffer.Bind;
 
  // allocate 4 * sizeof(TVertex) bytes of video memory and set it's usage to StaticDraw
  vBuffer.BufferData(4, SizeOf(TVertex), TglcBufferUsage.buStaticDraw, nil);
 
  // memory map video memory to our application
  p := vBuffer.MapBuffer(TglcBufferAccess.baWriteOnly);
 
  // write our data to the mapped video memory
  try
    PVertex(p).pos := gluVertex3f(0.0, 0.0, 0.0);
    PVertex(p).tex := gluVertex2f(0.0, 0.5);
    PVertex(p).nor := gluVertex3f(0.0, 1.0, 0.0);
    inc(p, SizeOf(TVertex));
 
    { ... more vertices following }
 
  finally
    vBuffer.UnmapBuffer;
    vBuffer.Unbind;
  end;
 
  { write indices to index buffer }
  iBuffer.Bind;
  iBuffer.BufferData(4, SizeOf(GLuint), TglcBufferUsage.buStaticDraw, nil);
  p := iBuffer.MapBuffer(TglcBufferAccess.baWriteOnly);
  try
    PGLuint(p) := 0;
    inc(p, sizeof(GLuint));
 
    { ... more indices following }
 
  finally
    iBuffer.UnmapBuffer;
    iBuffer.Unbind;
  end;

All data is uploaded. Know we can render our vertices using one of the glDraw methods. Before you call glDraw you must tell OpenGL where the vertex data is stored.

// use array buffers to draw primitive
VertexBuffer.Bind;
IndexBuffer.Bind;
try
  // tell OpenGL where to find the vertex position
  // 3 float values, starting at offset 0
  glEnableClientState(GL_VERTEX_ARRAY);
  glVertexPointer(3, GL_FLOAT, SizeOf(TVertex), Pointer(0));
 
  // tell OpenGL where to find the texture coordinates
  // 2 float values, starting at offset 12 (= 3 * sizeof(GLfloat))
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glTexCoordPointer(2, GL_FLOAT, SizeOf(TVertex), Pointer(12));
 
  // tell OpenGL where to find the normal vector
  // normal vector starting at offset 20 (= 5 * sozeof(GLfloat))
  glEnableClientState(GL_NORMAL_ARRAY);
  glNormalPointer(GL_FLOAT, SizeOf(TVertex), Pointer(20));
 
  // tell OpenGL to use our index array for indexed rendering
  glEnableClientState(GL_INDEX_ARRAY);
  glIndexPointer(GL_INT, 0, nil);
 
  glDrawElements(GL_QUADS, iBuffer.DataCount, GL_UNSIGNED_INT, nil);
 
  glDisableClientState(GL_INDEX_ARRAY);
  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  glDisableClientState(GL_NORMAL_ARRAY);
finally
  IndexBuffer.Unbind;
  VertexBuffer.Unbind;
end;

That’s it. Don’t forget to free your buffer objects when you’re done.

pasccal
FreeAndNil(VertexBuffer);
FreeAndNil(IndexBuffer);

3.2. TglcBitmap

TglcBitmap objects are used to manage and render textures. To simple load and render a texture you need to create two objects. TglcBitmapData to load a texture from file and convert it to the format you want to use in your texture and TglcBitmap2D to manage a OpenGL texture object, upload and download texture data and of course render your texture. Sounds simple, doesn’t it?

// create our texture object
var Texture: TglcBitmap2D;
Texture := TglcBitmap2D.Create;
 
// load texture data to texture object
var TextureData: TglcBitmapData;
TextureData := TglcBitmapData.Create;
try
  TextureData.LoadFromFile('./my-texture.png');
  // convert your TextureData if it is not supported by OpenGL
  if (TextureData.Format <> TextureData.FormatDescriptor.OpenGLFormat) then
  TextureData.ConvertTo(TextureData.FormatDescriptor.OpenGLFormat);
  Texture.UploadData(TextureData);
finally
  FreeAndNil(TextureData);
end;

As you can see, you can destroy the TextureData object once the data is uploaded to your texture. The memory is not used any longer. Also you can do all operations to TextureData in a separate thread to have a nice load balancing and reduce render glitches.

3.3. TglcFrameBufferObject

Frame buffer objects are mostly used to do some offscreen rendering. You simply create a frame buffer object, attach some color and depth buffers to it and then render some stuff. Attached buffers can be of type render buffer or texture buffer. Render buffers are just a simple buffer OpenGL stores some needed data in (like a depth buffer). A texture buffer instead can be used as a normal texture after you have rendered something to the frame buffer object. Sounds complicated, but it’s easier as you imagine.

var
  fbo: TglcFrameBufferObject;
  tex: TglcTextureBuffer;
  buf: TglcRenderBuffer;
 
fbo := TglcFrameBufferObject.Create;
try
  // set the size of the frame buffer object
  fbo.SetSize(800, 600);
 
  // creating texture buffer and attach it as color buffer
  tex := TglcTextureBuffer.Create(TglcFormat.fmRGBA, TglcInternalFormat.ifRGBA16F);
  fbo.AddBuffer(tex, TglcAttachment.atColor0, true);
 
  // creating render buffer and attach it as depth buffer
  buf := TglcRenderBuffer.Create(TglcInternalFormat.ifDepthComponent);
  fbo.AddBuffer(buf, TglcAttachment.atDepth, true);
 
  // render to frame buffer object
  fbo.Bind;
  { ... do some rendering }
  fbo.Unbind;
 
  // use texture buffer
  tex.Bind;
  { ... do some rendering }
  tex.Unbind;
finally
  FreeAndNil(fbo);
end;

3.4. TglcShader

What would an OpenGL application be without fancy shaders? TglcShader helps you to load and use shaders in your application. The simplest example of using the shader classes is to load a shader and then use it for rendering.

Shader Code:

/* ShaderObject: GL_VERTEX_SHADER */
#version 330
layout(location = 0) in vec3 inPos;
void main(void)
{
    gl_Position = vec4(inPos, 1.0);
}
 
/* ShaderObject: GL_FRAGMENT_SHADER */
#version 330
out vec4 outColor;
void main(void)
{
    outColor = vec4(1.0, 0.0, 0.0, 1.0);
}

Application Code:

var Shader: TglcShaderProgram;
{ 'Log' is a callback to write log outputs to. So you can detect errors while compiling your shader. }
Shader := TglcShaderProgram.Create(@Log);
Shader.LoadFromFile('./my-shader-file.glsl');
Shader.Compile;
Shader.Enable;
{ ... do some rendering }
Shader.Disable;

As mentioned before this is a really simple example. TglcShaderProgram has some more usefull features, like settings uniform variables, binding attribute locations or completely build your shader step by step programmatically linking differend TglcShaderObjects into the TglcShaderProgram.

3.5. TglcVertexArrayObject

Vertex array objects are used to store all information about vertex buffer objects and index buffer objects. Instad of telling OpenGL all these information in every render loop, they are stored in a single objects and can be activated by simply binding the vertex array object.

var
vbo: TglcArrayBuffer;
vao: TglcVertexArrayObject;
{ ... create VBO and fill with data }
vao := TglcVertexArrayObject.Create;
bao.BindArrayBuffer(vbo, true);
vao.VertexAttribPointer(LAYOUT_LOCATION_POS, 3, GL_FLOAT, False, SizeOf(TVertex), GLint(@PVertex(nil)^.pos));
vao.VertexAttribPointer(LAYOUT_LOCATION_TEX, 2, GL_FLOAT, False, SizeOf(TVertex), GLint(@PVertex(nil)^.tex));
vao.Bind;
{ ... render vertices using glDrawXXX }
vao.Unbind;

4. Helper Classes

4.1. TglcCamera

TglcCamera is a quite simple class. It wrapps the model view matrix into a usefull class and provide some methods to manipulate the model view matrix such as Tilt, Turn or Move.

var Camera: TglcCamera;
 
Camera := TglcCamera.Create;
Camera.Perspective(45, 0.01, 100, 800/600); // define perspective view
Camera.Move(gluVector(2, 3, -5)); // move 2 right, 3 up and 5 back
Camera.Tilt(-25); // turn 25 degrees down
Camera.Turn(-10); // turn 10 degrees left
Camera.Activate; // activate camera
 
{ ... do normal rendering }

4.2. TglcLight and TglcMaterial

TglcLight and TglcMaterial are simple class wrappers of OpenGL light and material. Just to manage them in a object oriented way. TglcLight is specialized in 3 different classes:

  • TglcLightGlobal – for global lightning
  • TglcLightPoint – for point lights
  • TglcLightSpot – for spot lights

You can use the Bind and Unbind methods to activate and deactivate a light or material.

5. Helper Types

  • glcTypes – Contains a list of all OpenGL enum used in this project.
  • gluMatrix – Contains some usefull methods to work with matrices. gluMatrixEx is a extended version of gluMatrix using freepascal type helpers to add member methods to the matrix types.
  • gluVector – Contains some usefull methods to work with vectors. gluVectorEx is a extended version of gluVector using freepascal type helpers to add member methods to the vector types.
  • gluQuaternion – Contains some usefull methods to deal with quaternions.

Leave a Reply

Your email address will not be published. Required fields are marked *