Tag Archives: free pascal

This tag indicates that the content is about the Free Pascal compiler, it may be a news article, a tutorial chapter, a project entry or something else. Most Free Pascal content is also related to SDL2 here.

Dungeon Monkey Unlimited

Short description

Dungeon Monkey Unlimited is a turn-based, rouge-like role-playing game where you can explore ancient worlds with benign graphics.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Dungeon Monkey Unlimited
  • Author: Joseph Hewitt; graphics obtained from the David Gervais and rltiles sets.
  • Latest version: 1.001
  • Release date: September 20 2010.
  • Pascal compiler: Free Pascal
  • SDL Version: 1.2
  • Further libraries: Only those that come with the FPC compiler
  • License: GPL
  • Open source: Yes
  • Official website: www.gearheadrpg.com

GearHead 2

Short description

GearHead 2, successor of GearHead: Arena, is a turn-based, rouge-like role-playing game where you can explore futuristic worlds with benign graphics.

Showcase and Basic Data

(no showcase screenshots provided)

  • Project name: GearHead 2
  • Author: Joseph Hewitt, plus the work of several contributors
  • Latest version: 0.628
  • Release date: The first public release was August 23 2005; the most recent was June 1 2010. After I’ve updated GearHead-1 to my satisfaction I plan to do some revisions to this one as well.
  • Pascal compiler: Free Pascal
  • SDL Version: 1.2
  • Further libraries: Only those that come with the FPC compiler
  • License: LGPL
  • Open source: Yes
  • Official website: www.gearheadrpg.com

GearHead: Arena

Short description

GearHead: Arena (also known as GearHead 1) is a turn-based, rouge-like role-playing game where you can explore futuristic worlds with benign graphics.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: GearHead: Arena, also known as GearHead 1
  • Author: Joseph Hewitt, plus the work of several contributors
  • Latest version: 1.201
  • Release date: The first public release was May 10 2002; the most recent was March 3 2016. After version 1.100 I stopped development for nine years before returning to update the program earlier this year.
  • Pascal compiler: Free Pascal
  • SDL Version: 1.2
  • Further libraries: Only those that come with the FPC compiler
  • License: LGPL
  • Open source: Yes
  • Official website: www.gearheadrpg.com

 

OpenGL Logo

SDL 2.0 meets modern OpenGL

Good news, Chapter 10 has been released right now! You ever wondered what to do if you would like to create 3d graphics for a game or application? – Well, you go for modern OpenGL. And SDL 2.0 is probably the best and most convenient way to go for modern OpenGL nowadays, even professionals typically use SDL as powerful assistant for their OpenGL applications.  Learn more about the strong relationship between SDL and OpenGL in Chapter 10. – And learn how it’s done, of course ;-).

Chapter 3 got a short explanation now on how to copy the source code of a chapter. In the SDL 1.2 chapters the source code  was shipped for each chapter as Pascal file. Nowadays it is much more convenient to grab the source code (or just the desired parts) by copying it directly from the chapter’s source code boxes (in the browser) and paste it whereever it is needed.

The transfer of the old website has been finished. Nearly the complete content is in some way or another transfered to the new page. For example, all tutorial pages (even the old ones) are still available. Some downloads are integrated at the corresponding tutorial pages now, so they are not lost. Some pages are gone, these are Downloads, Tables and Links. These pages are of no benefit anymore since their information are now provided at the corresponding place instead of separate pages. Nevertheless, links trying to access these pages are redirected to the main page to prevent broken links.

No One’s Space got greenlit. This means that this Free Pascal/SDL game will be available in Steam for purchase soon. It demonstrates the power of Free Pascal and SDL.

Small update of some subdomain settings. Subdomain links work again.

SDL2 and modern OpenGL 3.0+

Last updated on March 5th, 2023

This chapter will introduce you on how to combine the SDL library with the famous Open Graphics Library (OpenGL).

What is OpenGL?

OpenGL is the first choice when it comes to platform independent 2d and 3d graphics programming. The emphasis is on graphics programming only though!

Why and when to combine SDL and OpenGL?

SDL is an excellent choice if you need platform independent 2d graphics. OpenGL is capable of 2d graphics, too, but why using the more complicated library if you could use the easy to use SDL library? – And by the way, underneath SDL is actually using OpenGL (or similar libraries depending upon the system) to achieve its hardware accelerated 2d graphics.

However, if your project needs 3d graphics, which isn’t covered by SDL, you can set up your system for this quite easy with SDL. The setup of an OpenGL environment is very easy and platform independent with SDL. Without SDL you would’ve to write different code to set up OpenGL for each operating system. In fact, even professional developers use SDL to set up their OpenGL applications.

Furthermore, since OpenGL is a pure graphics library, any other task is further done by SDL (e.g. keyboard handling, sound,…).

At this point I’d like to quote Klaus Vor der Landwehr (professional developer) from Turtle-Games, who described the relation of SDL and OpenGL in a very clear way.

Although the graphics are often in the foreground, it is for me as a game programmer only one aspect of many with which I have to deal. And the graphics do not even require the most work. OpenAL for example costs much more time and effort if you want to build a 3D sound channel management. And there are many other interfaces. Here is a list of categories in which SDL has been a great help:

  • multiple displays
  • window management
  • Event handling
  • keyboard
  • mouse
  • joystick
  • game controller
  • force feedback
  • threads
  • timers

… for Windows, Mac and Linux.

Source: Pascal Game Development Community.

What exactly is modern OpenGL?

As of version 2.0 of OpenGL, the so-called fixed pipeline has been replaced by a programmable pipeline (modern OpenGL). In general, the pipeline makes your input data appear on the screen in a hardware accelerated manner by using your graphics card. For the fixed pipeline it was easy to draw something to the screen but, as the name suggests, it was quite fixed and unflexible. The programmable pipeline which is controlled by a newly introduced shader (script) language is far more flexible, though, the ease is gone :-D.

Anyway, some people refer to OpenGL version 3.0 and up as modern OpenGL. This is because a lot of typical functionality was deprecated as of this version. The backwards compatibility is gone.

In this chapter I will demonstrate how to use SDL 3.0 and up to set up a modern OpenGL environment using some basic shaders. I based the description heavily on an excellent C++ tutorial over at opengl-tutorial.org and their second chapter. You may look for further OpenGL stuff there or have a look at this WikiBook OpenGL Introduction (C++). I’m not aware of OpenGL tutorials for Free Pascal or Delphi treating modern OpenGL (let me know if you know).

OpenGL Pascal units (headers)

Similar to SDL 2.0, you need specific units which translate and connect your code to the OpenGL library. There is a native OpenGL unit GL which covers the main functionality of OpenGL. Additionally for modern OpenGL you need the unit GLext which covers the functionality up to OpenGL version 4.0. These units are shipped right along with the Free Pascal compiler.

In case you are interested in support of OpenGL version 4.4, you should look into the dglOpenGL.pas. This unit is not shipped natively along with the Free Pascal compiler.

Let the fun begin

Let’s have a look at the code:

program chap10_SDL2;
uses Classes, SysUtils, SDL2, GL, GLext;

const
  vertexShaderFile = 'VertexShader.txt';
  fragmentShaderFile = 'FragmentShader.txt';
  triangleData: array[0..8] of GLfloat = ( -1.0, -1.0, 0.0,
                                            1.0, -1.0, 0.0,
                                            0.0,  1.0, 0.0  );

var
sdlWindow1: PSDL_Window;
sdlGLContext1: TSDL_GLContext;
i: Word;
VertexArrayID: GLuint;
triangleVBO: GLuint;

VertexShaderID: GLuint;
VertexShaderCode: PGLchar;
FragmentShaderID: GLuint;
FragmentShaderCode: PGLchar;
ShaderCode: TStringList;
ProgramID: GLuint;
compilationResult: GLint = GL_FALSE;
InfoLogLength: GLint;
ErrorMessageArray: array of GLChar;

begin
  if SDL_Init( SDL_INIT_VIDEO ) < 0 then HALT;

  //get an OpenGL window and create OpenGL context
  sdlWindow1 := SDL_CreateWindow( 'OpenGL window', 50, 50, 500, 500, SDL_WINDOW_OPENGL );
  if sdlWindow1 = nil then HALT;

  sdlGLContext1 := SDL_GL_CreateContext( sdlWindow1 );
  if @sdlGLContext1 = nil then HALT;

  //init OpenGL and load extensions
  if Load_GL_VERSION_4_0 = false then
    if Load_GL_VERSION_3_3 = false then
      if Load_GL_VERSION_3_2 = false then
        if Load_GL_VERSION_3_0 = false then
        begin
          writeln(' ERROR: OpenGL 3.0 or higher needed. '); readln;
          HALT;
        end;

  //print out OpenGL vendor, version and shader version
  writeln( 'Vendor: ' + glGetString( GL_VENDOR ) );
  writeln( 'OpenGL Version: ' + glGetString( GL_VERSION ) );
  writeln( 'Shader Version: ' + glGetString( GL_SHADING_LANGUAGE_VERSION ) );

  //create Vertex Array Object (VAO)
  glGenVertexArrays( 1, @VertexArrayID );
  glBindVertexArray( VertexArrayID );

  //creating Vertex Buffer Object (VBO)
  glGenBuffers( 1, @triangleVBO );
  glBindBuffer( GL_ARRAY_BUFFER, triangleVBO );
  glBufferData( GL_ARRAY_BUFFER, SizeOf( triangleData ), @triangleData, GL_STATIC_DRAW );

  //creating shaders
  VertexShaderID := glCreateShader( GL_VERTEX_SHADER );
  FragmentShaderID := glCreateShader( GL_FRAGMENT_SHADER );

  //load shader code and get PChars
  ShaderCode := TStringList.Create;
  ShaderCode.LoadFromFile( VertexShaderFile );
  VertexShaderCode := ShaderCode.GetText;
  if VertexShaderCode = nil then HALT;
  ShaderCode.LoadFromFile( FragmentShaderFile );
  FragmentShaderCode := ShaderCode.GetText;
  if FragmentShaderCode = nil then HALT;
  ShaderCode.Free;

  //compiling and error checking vertex shader
  write('Compiling and error checking Vertex Shader... ' );
  glShaderSource( VertexShaderID, 1, @VertexShaderCode, nil );
  glCompileShader( VertexShaderID );

  glGetShaderiv( VertexShaderID, GL_COMPILE_STATUS, @compilationResult );
  glGetShaderiv( VertexShaderID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

  //compiling and error checking fragment shader
  write('Compiling and error checking Fragment Shader... ' );
  glShaderSource( FragmentShaderID, 1, @FragmentShaderCode, nil );
  glCompileShader( FragmentShaderID );

  glGetShaderiv( FragmentShaderID, GL_COMPILE_STATUS, @compilationResult );
  glGetShaderiv( FragmentShaderID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

  //creating and linking program
  write('Creating and linking program... ' );
  ProgramID := glCreateProgram();
  glAttachShader( ProgramID, VertexShaderID );
  glAttachShader( ProgramID, FragmentShaderID );
  glLinkProgram( ProgramID );

  glGetShaderiv( ProgramID, GL_LINK_STATUS, @compilationResult );
  glGetShaderiv( ProgramID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

  for i := 0 to 400 do
  begin
    glClearColor( 0.0, 1.0-i/400, 0.0+i/400, 1.0 );
    glClear( GL_COLOR_BUFFER_BIT );
    glUseProgram( ProgramID );
    glEnableVertexAttribArray( 0 );
    glBindBuffer( GL_ARRAY_BUFFER, triangleVBO );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, nil );
    glDrawArrays( GL_TRIANGLES, 0, 3 );
    glDisableVertexAttribArray( 0 );
    SDL_Delay( 20 );
    SDL_GL_SwapWindow( sdlWindow1 );
  end;

  //clean up
  glDetachShader( ProgramID, VertexShaderID );
  glDetachShader( ProgramID, FragmentShaderID );

  glDeleteShader( VertexShaderID );
  glDeleteShader( FragmentShaderID );
  glDeleteProgram( ProgramID );

  StrDispose( VertexShaderCode );
  StrDispose( FragmentShaderCode );

  glDeleteBuffers( 1, @triangleVBO );
  glDeleteVertexArrays( 1, @VertexArrayID );

  SDL_GL_DeleteContext( sdlGLContext1 );
  SDL_DestroyWindow( sdlWindow1 );

  SDL_Quit;
end.

Wow that is a lot of code. What you will get is this:

Result for chapter 10

The background will change slowly from green to blue. And you will get this:

Command result for chapter 10

The vendor, OpenGL version and shader version information will be different according to your system. Also, if your system doen’t support the needed OpenGL version you’ll not have “success” but rather “failure” after the compiling and linking processes. Additional information may be shown then.

program chap10_SDL2;
uses Classes, SysUtils, SDL2, GL, GLext;

const
  vertexShaderFile = 'VertexShader.txt';
  fragmentShaderFile = 'FragmentShader.txt';
  triangleData: array[0..8] of GLfloat = ( -1.0, -1.0, 0.0,
                                            1.0, -1.0, 0.0,
                                            0.0,  1.0, 0.0  );

var
sdlWindow1: PSDL_Window;
sdlGLContext1: TSDL_GLContext;
i: Word;
VertexArrayID: GLuint;
triangleVBO: GLuint;

VertexShaderID: GLuint;
VertexShaderCode: PGLchar;
FragmentShaderID: GLuint;
FragmentShaderCode: PGLchar;
ShaderCode: TStringList;
ProgramID: GLuint;
compilationResult: GLint = GL_FALSE;
InfoLogLength: GLint;
ErrorMessageArray: array of GLChar;

The program is called “chap10_SDL2” for obvious reason.

Additionally to the SDL2 unit we load the native FPC units Classes (for TStringList support), SysUtils (for PChar functions) and GL and GLext for OpenGL support.

Thre are three constants declared. The first two are defined as the filenames of the so-called shader source files.  Basically they are simple text files which contain a script. More about shaders and the script later. The third is an array of nine GLfloat values. GLfloat is the OpenGL float variable type which in fact is translated as Pascal’s Single type. In short, these nine values describe three points in 3d space which, if connected, form a triangle. More about this later.

The first variable “sdlWindow1” is well known from previous chapters. Any variable to follow is new though. Most of them are related to OpenGL.

“sdlGLContext1” is of type TSDL_GLContext needed to create a so-called OpenGL context. In fact, this variable type is provided by SDL and a key type to set up an OpenGL conext in a simple and cross-platform manner.

The variable “i” is a simple Word variable for counting purposes.

OpenGL’s Integers and Strings

Most of the following variables are either of type GLuint or of type PGLchar. The last variable is an dynamic array of GLchars. Their specific meaning will be discussed later but GLuint is the OpenGL unsigned integer type (no negative values) which translates to Pascal’s Cardinal/Longword type. Text handling in OpenGL works by null-terminated strings of type PGLchar which translate to Pascal’s PChar. GLchar translates to Char then, obviously.

At this point you may wonder why as for SDL the null-terminated strings are used instead of simple strings (see Chapter 7 for the PAnsiChar variable type discussion). The answer again is that OpenGL is based upon C which handles strings this way. PChar equals PAnsiChar by the way.

The remaining variables “ShaderCode” of type TStringList will be used to handle the shader text files. “compilationResult” and “InfoLogLength” are of GLint type. In contrast to GLuint they allow for negative values.

begin
  if SDL_Init( SDL_INIT_VIDEO ) < 0 then HALT;

  //get an OpenGL window and create OpenGL context
  sdlWindow1 := SDL_CreateWindow( 'OpenGL window', 50, 50, 500, 500, SDL_WINDOW_OPENGL );
  if sdlWindow1 = nil then HALT;

  sdlGLContext1 := SDL_GL_CreateContext( sdlWindow1 );
  if @sdlGLContext1 = nil then HALT;

  //init OpenGL and load extensions
  if Load_GL_VERSION_4_0 = false then
    if Load_GL_VERSION_3_3 = false then
      if Load_GL_VERSION_3_2 = false then
        if Load_GL_VERSION_3_0 = false then
        begin
          writeln(' ERROR: OpenGL 3.0 or higher needed. '); readln;
          HALT;
        end;

  //print out OpenGL vendor, version and shader version
  writeln( 'Vendor: ' + glGetString( GL_VENDOR ) );
  writeln( 'OpenGL Version: ' + glGetString( GL_VERSION ) );
  writeln( 'Shader Version: ' + glGetString( GL_SHADING_LANGUAGE_VERSION ) );

First SDL2 is initilized as known. “sdlWindow1” is created as known by SDL_CreateWindow. Be careful though, in order to work with OpenGL the flag SDL_WINDOW_OPENGL has to be set!

SDL 2.0 and the OpenGL context

An OpenGL context is kind of an abstract name. It doesn’t represents just a window, even though it is created from a SDL2 window, but rather it contains everything (including the window information) that is related to this OpenGL context. The OpenGL context is therefore kind of “broader” than just a window, that is why it is called context rather than just a OpenGL window.

The function to create an OpenGL context from a SDL2 window is:

function SDL_GL_CreateContext(window: PSDL_Window): TSDL_GLContext

So, it is simple as that, just use the SDL2 window as argument and voila, you’ll get a OpenGL context, platform-independent. That is why everybody loves SDL2 to work with OpenGL. Note that the returned Context isn’t a pointer but an actual instance. So to error check against nil you need to refer to the instance’s addresse by the @ operator.

OpenGL version check and initialization

The nested if-then-statements check if at least version 3.0 of OpenGL is installed. If so, the highest available version is loaded. If not, the program is stopped and returns a text message.

If your hardware doen’t support OpenGL 3.0 or higher you should try to update your graphics driver. There is a good chance that you are able to use OpenGL 3.0 or higher then. Anyway, if the upgrade doesn’t work out or you wouldn’t want to update, you may have a look into the JEDI-SDL Chapter about OpenGL, there the old OpenGL is treated (although that chapter treats SDL 1.2, it shouldn’t be too hard to make it work with SDL 2.0 with minor changes).

Next there are three text messages printed out. These present the Vendor, the OpenGL version and the Shading language version. To get them in a readable form you need to transform the constants into strings by function glGetString. Let’s have a look at the command window again:

Command result for chapter 10

Have a look at the first three lines and you see what it could look like.

Vertex Array Object and Vertex Buffer Object

  //create Vertex Array Object (VAO)
  glGenVertexArrays( 1, @VertexArrayID );
  glBindVertexArray( VertexArrayID );

  //creating Vertex Buffer Object (VBO)
  glGenBuffers( 1, @triangleVBO );
  glBindBuffer( GL_ARRAY_BUFFER, triangleVBO );
  glBufferData( GL_ARRAY_BUFFER, SizeOf( triangleData ), @triangleData, GL_STATIC_DRAW );

If you are new to OpenGL,  OpenGL as kind of machine with many switches. Each switch

Briefly, a Vertex Array Object (VAO) is a specific OpenGL object which contains important settings (e.g. format of vertex data) and references to other objects, including Vertex Buffer Objects (VBO). Notice, it doesn’t store the object’s data (content) itself, it just stores the reference to these objects.

The Vertex Buffer Object (VBO) contains the actual data (content). In the example case these are three vertices, each described by three float point values in cartesian space.

OpenGL Object name or ID

Because it is important to understand, in contrast to SDL where objects usually are directly submitted to a function by its pointer reference, in OpenGL you have a so-called OpenGL Object name, which actually is an integer value of GLuint type. Therefore ID is a suitable name, too. Let’s see how this works:

The VAO is created by function glGenVertexArrays( number of VAO names, pointer to VAO names array ). The first parameter determines how many VAO names I’d like to create. We just need 1. The second parameter asks for a pointer to an array of VAO names. Since VAO names are just simple GLuints, it is a simple array of GLuints. Anyway, since we just need one, a pointer to a simple GLuint variable will be suitable, too. In our case that is “VertexArrayID”. To bind (“activate”) the corresponding VAO to the OpenGL context, the function glBindVertexArray( name of VAO ) is used. The argument is the name of the VAO we just created in “VertexArrayID”.

Similar to the VAO, the VBO is created by function glGenBuffers( number of VBO names, pointer to VBO names array ). Again, we just need 1 VBO whose name should be returned to “triangleVBO”. This variable just stores an ID (object name) of GLuint type.

From the naming of “triangleVBO” it is clear to us what we intent here (representing a triangle by three vertices), anyway, how should OpenGL know? – We explain the meaning of this buffer object to OpenGL by using glBindBuffer ( target, VBO name ). There are numerous options as target but GL_VERTEX_BUFFER is the right choice here.

The actual VBO is created by glBufferData( target, size of object’s data store in bytes, pointer to data to be copied into VBO, expected usage ). This functions takes four arguments. The target is GL_VERTEX_BUFFER again. The size of the VBO’s data store in bytes is determined by Pascal’s SizeOf function applied to “triangleData”. The “triangleData” constant also holds the data to be copied into the VBO, so its pointer is suitable as the third argument. Since we are not going to change the data a lot, we should use GL_STATIC_DRAW as fourth argument.

If you are a newcomer to OpenGL, don’t worry if you are confused the first time. Most people are. And now it may even get worse :-(.

Shaders and OpenGL Shading Language

When starting with modern OpenGL the so-called Shaders are talked about a lot. Shaders are scripts written in a C-like script language called OpenGL Shading Language (GLSL). These scripts are compiled at runtime and influence the way how the graphics data is processed at certain steps in the so-called rendering pipeline of OpenGL. In fact, you can create rather complex and special effects with shaders without even changing one line of code of your source code.

Vertex Shader and Fragment Shader

There are two Shaders that are crucial and have to be set up to work with modern OpenGL. They are called  Vertex Shader and Fragment Shader. There are more Shaders not covered here, though. Each type of Shader influences different aspects of the rendering.

The Vertex Shader is the first Shader program executed in the rendering pipeline. Every vertex is “put through” the Vertex Shader program and processed accordingly, hence the name. Often this Shader is used to perform transformation operations. The Shader script used in this tutorial is shown next:

#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;

void main(void) {
	gl_Position.xyz = vertexPosition_modelspace;
        gl_Position.w = 1.0;
}

This GLSL source code is saved into a file VertexShader.txt and located in the same directory as the source code of this chapter’s example source code. I’m not going to explain this GLSL code in detail here, but a detailed explanation is found over at opengl-tutorial.org Chapter 2 where I got this Shader code from, by the way.

The Frgament Shader is the last Shader program executed in the renderin pipeline. The so-called rasterization process produces fragments. Every fragment is “put through” the Fragment Shader program and processed accordingly. The Shader script used for the Fragment Shader is:

#version 330 core

out vec3 color;

void main(){
   color = vec3(1,0,0);
 }

This code is in file FragmentShader.txt and located in the same directory as the VertexShader.txt. The detailed explanation is found over at opengl-tutorial.org Chapter 2 again. Anyway, you’ll notice that there is a “color” variable (three component vector). As you see, it sets the (red,green,blue) values for the fragments to (1,0,0) which means red should be the result, red = 100%, green and blue = 0%. You may play around with these values.

  //creating shaders
  VertexShaderID := glCreateShader( GL_VERTEX_SHADER );
  FragmentShaderID := glCreateShader( GL_FRAGMENT_SHADER );

  //load shader code and get PChars
  ShaderCode := TStringList.Create;
  ShaderCode.LoadFromFile( VertexShaderFile );
  VertexShaderCode := ShaderCode.GetText;
  if VertexShaderCode = nil then HALT;
  ShaderCode.LoadFromFile( FragmentShaderFile );
  FragmentShaderCode := ShaderCode.GetText;
  if FragmentShaderCode = nil then HALT;
  ShaderCode.Free;

Both Shaders are created by function glCreateShader( Shader type ). It returns the reference (or name) as GLuint as seen before for the VAO and VBO. We store them in the VertexShaderID and FragmenShaderID, respecitvely.

The next part is about loading the source code from the two Shader files (VertexShader.txt, FragmentShader.txt) and converting them to be used with OpenGL. First a “ShaderCode” variable of TStringList type is created. Its LoadFromFile method let us load the file contents into the variable conveniently. First for the Vertex Shader, whose file name is stored in constant “VertexShaderFile”. The variable “VertexShaderCode” is of type PGLchar, which is the way OpenGL handles strings. Since PGLchar is of type PChar anyway, the method GetText is perfectly suitable here to convert the source code string into a null-terminated array of chars. Finally, there is a simple check if the PGLchars are empty (nil), which shouldn’t be the case if the source code is pointed to as expected.

Exactly the same is done for the FragmentShader and the source code associated with “FragmentShaderCode”.

Finally, the dummy variable “ShaderCode” is free’d.

  //compiling and error checking vertex shader
  write('Compiling and error checking Vertex Shader... ' );
  glShaderSource( VertexShaderID, 1, @VertexShaderCode, nil );
  glCompileShader( VertexShaderID );

  glGetShaderiv( VertexShaderID, GL_COMPILE_STATUS, @compilationResult );
  glGetShaderiv( VertexShaderID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

  //compiling and error checking fragment shader
  write('Compiling and error checking Fragment Shader... ' );
  glShaderSource( FragmentShaderID, 1, @FragmentShaderCode, nil );
  glCompileShader( FragmentShaderID );

  glGetShaderiv( FragmentShaderID, GL_COMPILE_STATUS, @compilationResult );
  glGetShaderiv( FragmentShaderID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

To associate the source code we stored in “VertexSourceCode” to “VertexShaderID” of GLuint type, the function glShaderSource( Shader reference, number of array elements, pointer to array of source code PGLchars, pointer to array of lengths ). The Vertex Shader reference is stored in “VertexShaderID” which is the first argument. We just have one source code, so the second argument is 1. The source code is stored VertexShaderCode, and its pointer is addressed by @VertexShaderCode as the third argument. As seen before, since we just have one element here, it is not necessary to have really an array. The fourth parameter allows for some length specification, but if set to nil it expects null-terminated arrays of chars.

The compilation is straight forward done by glCompileShader( Shader reference ). It is really advised to to error checking here, that is why it is shown how to do that. The function glGetShaderiv( Shader reference, object parameter, pointer of correct type for return value ) is used to request information about objects. First we like to know if the compilation was successful. The Shader reference is stored in “VertexShaderID”, the object parameter is GL_COMPILE_STATUS. This will return a GLint value, which can be interpreted as GL_FALSE or GL_TRUE. The result is stored in “compilationResult” by using its pointer (@compilationResult) as argument.

Right after that we request the length of the information log by GL_INFO_LOG_LENGTH. It will be greater than 0 if some information were logged (probably an error occured on compilation then). The result is returned to “InfoLogLength” by its pointer @InfoLogLength.

If an error occurs, “compilationResult” is GL_FALSE. In this case “failure” along with more specific information is printed out. I’m not going into detail here, since this shouldn’t happen. Otherwise (and that should be the case), “success” is printed out.

The very same way the Fragment Shader is compiled and checked.

  //creating and linking program
  write('Creating and linking program... ' );
  ProgramID := glCreateProgram();
  glAttachShader( ProgramID, VertexShaderID );
  glAttachShader( ProgramID, FragmentShaderID );
  glLinkProgram( ProgramID );

  glGetShaderiv( ProgramID, GL_LINK_STATUS, @compilationResult );
  glGetShaderiv( ProgramID, GL_INFO_LOG_LENGTH, @InfoLogLength );
  if compilationResult = GL_FALSE then
  begin
    writeln( 'failure' );
    SetLength( ErrorMessageArray, InfoLogLength+1 );
    glGetShaderInfoLog( VertexShaderID, InfoLogLength, nil, @ErrorMessageArray[0] );
    for i := 0 to InfoLogLength do write( String( ErrorMessageArray[i] ) );
    writeln;
  end else writeln( 'success' );

The shaders have to be attached and linked by a Shader program. A Shader program is created by glCreateProgram(). The parenthesis are important here. It returns an reference of GLuint type which is stored in ProgramID.

The Shaders are attached to this Shader program by glAttacheShader( Program reference, Shader reference ). The program is linked by glLinkProgram( Program reference ). The reference for the Shader program is “ProgramID”. The references for the Shaders are “VertexShaderID” and “FragmentShaderID”, respectively.

By complete analogy to the error checking for the Shader compilation, the Shader program linking is checked. Anyway, instead of GL_COMPILE_STATUS, GL_LINK_STATUS is used.

  for i := 0 to 400 do
  begin
    glClearColor( 0.0, 1.0-i/400, 0.0+i/400, 1.0 );
    glClear( GL_COLOR_BUFFER_BIT );
    glUseProgram( ProgramID );
    glEnableVertexAttribArray( 0 );
    glBindBuffer( GL_ARRAY_BUFFER, triangleVBO );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, nil );
    glDrawArrays( GL_TRIANGLES, 0, 3 );
    glDisableVertexAttribArray( 0 );
    SDL_Delay( 20 );
    SDL_GL_SwapWindow( sdlWindow1 );
  end;

The for-loop counts from 0 to 400. Within each cycle it first changes the background color by glClearColor( red, green, blue, alpha ). Red and alpha are constant, green and blue are varied each cycle dependend upon variable i. This makes the background slowly changing from green to blue, feel free to play around with the rgba values. To actually clear the color buffer glClear( buffer ) with GL_COLOR_BUFFER_BIT as argument is used.

glUseProgram( Shader program reference ) is used to apply the Shader program to the rendering state. “ProgramID” is the Shader program reference in the example code.

glEnableVertexAttribArray( array index ) is used in order to make the attribute array available for rendering by glDrawArrays. The index is 0 here. The “triangleVBO” is bound by glBindBuffer( target, buffer ) to the GL_BUFFER_ARRAY target to change attribute data of said VBO. Latter is done by glVertexAttribPointer( index, size, type, normalized, stride, offset of first component ) with the given arguments. Hence, the index is 0, 3 components per generic vertex attribute, each of float point type (thus, GL_FLOAT), not normalized (thus GL_FALSE), no strides between vertex attributes, no offset for the first component.

The rendering is done by glDrawArrays( type of primitive, starting index, number of elements ). The type of primitive is a triangle, hence GL_TRIANGLES is the first argument. We start at the very beginning, so index is 0. We have 3 sequential elements (vertices).

glDisableVertexAttribArray( array index ) is the counter function to glEnableVertexAttribArray( array index ), obviously. It disables the vertex attribute array.

SDL_Delay delays the loop by 20 milliseconds.

The procedure

procedure SDL_GL_SwapWindow(window: PSDL_Window)

is used to actually display the rendering result to the the window “sdlWindow1”. Keep in mind that this window has to be initialized as an OpenGL window. This procedure is comparable to SDL’s SDL_RenderPresent.

After i matching 400, the for-loop is left.

  //clean up
  glDetachShader( ProgramID, VertexShaderID );
  glDetachShader( ProgramID, FragmentShaderID );

  glDeleteShader( VertexShaderID );
  glDeleteShader( FragmentShaderID );
  glDeleteProgram( ProgramID );

  StrDispose( VertexShaderCode );
  StrDispose( FragmentShaderCode );

  glDeleteBuffers( 1, @triangleVBO );
  glDeleteVertexArrays( 1, @VertexArrayID );

  SDL_GL_DeleteContext( sdlGLContext1 );
  SDL_DestroyWindow( sdlWindow1 );

  SDL_Quit;
end.

For the clean up, the shaders have to be detached from the shader program by glDetachShader( program, shader ). After that they can be deleted by glDeleteShader( shader ), and the program by glDeleteProgram( program ).

The shader script PChars are disposed by StrDispose( PChar ).

The VBO and the vertex array have to be free’d by glDeleteBuffers( number of buffer objects, pointer to array of buffers ) and glDeleteVertexArrays( number of VAOs, pointer to array of VAOs ) respectively. The first parameter is the number of objects to be deleted, which is 1 in both our cases.

To resolve the OpenGL context

procedure SDL_GL_DeleteContext(context: TSDL_GLContext)

is used.

The SDL Window is destroyed as known. Finally SDL is shut down as known by SDL_Quit.

← previous Chapter | next Chapter →

No One's Space

Commercial Free Pascal/SDL Project

The No One’s Space SDL game has been added to the SDL Project page. It is the first commercial title added and Klaus Vor der Landwehr (from Turtle-Games) has kindly provided an interview for us. Feel free to support the game in the greenlight state over at Steam. This game demonstrates that Free Pascal and SDL make games of commercial quality possible.

The installation instruction got extend by an explanation how to install and configure Lazarus.

No One’s Space

Short description

A commercial high quality space shooter by game developer Turtle-Games.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: No One’s Space
  • Author: Turtle Games
  • Latest version: Pre-alpha Version
  • First release date: Steam Early Access Release in 2016 (TBA)
  • Compiler: Free Pascal (via Lazarus)
  • SDL Version: 2.0
  • Further libraries: OpenGL, OpenAL, Ogg Vorbis
  • License: Commercial
  • Open source: no
  • Official website: http://www.NoOnesSpace.com

Interview with Klaus Vor der Landwehr from Turtle-Games

Could you please give a short description of No One’s Space for those who have never heard of it?

Klaus Vor der Landwehr: No One’s Space (NOS) is a single-player Retro 2D-Science-Fiction-Shooter with modern physics. It was created as a cross-breed of the classic games Wing Commander I and Star Control II. In NOS, the player experiences a cosmic conflict between four powerful races, taking the role of different heroes. In 54 challenging missions, reaching from manageable duels to large combats, the player controls a variety of vessels and has to go all out to improve his skills to master them all.

Why did you decide to choose Pascal as a programming language and SDL/SDL2 as a library for this project?

Klaus Vor der Landwehr: It wasn’t really a choice. I’m used to Pascal since my school days. I’m a self-taught. I like it.

What do you think is the most interesting Pascal/SDL/SDL2 project out there (besides your own, of course :-D)?

Klaus Vor der Landwehr: Hm, as far as it concerns the programming language, games are rarely tagged. But I’ve seen some impressive stuff right here: Projekt “W” – Phase 2 http://www.saschawillems.de/?page_id=829 (Although I can only assume that it uses SDL).

Are there any further steps for No One’s Space and/or are any new projects planned? What will they be?

Klaus Vor der Landwehr: If the game gets Greenlit, we want to release it on Steam this year (early access) and work further on it.

 

Colorful

Short description

A 2d shooter whose source code is free to study.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Colorful
  • Author: suve
  • Latest version: 1.2
  • First release date: 2012-12-16
  • Compiler: FPC 2.6.2
  • SDL Version: 1.2
  • Further libraries: Originally BASS for audio handling, later replaced with SDL_mixer as to move away from proprietary library; SDL_image; Sour could probably count, too; OpenGL
  • License: zlib w/acknowledgement
  • Open source: Yep. Under zlib, as stated above.
  • Official website: http://svgames.pl

Interview with suve

Could you please give a short description of Colorful for those who have never heard of it?

suve: Colorful is a simple game where the player moves freely around a 2D world, fighting multiple enemies and trying to retrieve colourful artefacts. Originally created in 48h for Ludum Dare, the game is heavily inspired by Hero Core, featuring simplistic graphics and sounds, and a no-game-over approach balancing the overall difficulty level.

Why did you decide to choose Pascal as a programming language and SDL/SDL2 as a library for your projects?

suve: I chose Pascal mostly as it’s the language I’m most proficient and comfortable with. As for SDL, after working with a few different libraries in the past, I’ve found SDL easy to use, but nonetheless really versatile and fitting my needs. The library itself doesn’t really enforce anything on you, so you don’t have to change your habits (much), and the seemingly simplistic API is greatly extended by the supplementary SDL_XYZ libraries.

What do you think is the most interesting Pascal/SDL/SDL2 project out there (besides of your own, of course :-D)?

suve: Supraleiter seems the most awesome of them all, I think. Shame that quite probably I won’t be able to play sit, seeing as I only have an integrated GPU.

Are there any further steps for your projects or any new projects planned? What will they be?

suve: I have two projects underway right now, but one is too early in development and I don’t want to disclose it for fear of not delivering… and the other, for a change, is written in C instead of Pascal. 🙂

 

Alexland

Short description

Alexland is a 2d shooter in a classical style.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Alexland
  • Author: suve & ZbiXs
  • Latest version: 1.3
  • First release date: 2010-01-31
  • Compiler: Free Pascal 2.4.0 (for the 1.3 release)
  • SDL Version: 1.2
  • Further libraries: BASS for audio handling, SDL_image, SDL_ttf, SDL_net
  • License: Back then we didn’t really think about licensing, and seeing how the game contains assets ripped from plenty of places without even keeping track of source… I say it’d be hard for us to claim copyright to anything apart from code and some original graphics (+edits) we created.
  • Open source: Nope. Maybe if there’s a remake one day.
  • Official website: http://svgames.pl

Interview with suve

Could you please give a short description of Alexland for those who have never heard of it?

suve: Born of RPG Maker nostalgia and the hatred for its default graphics set, Alexland is a 2D shooter where the player controls a lone hero in a fight against never-ending hordes of monsters. Featuring 12 weapons to kick ass with, 11 bonuses to enhance the gameplay, 10 monster types to kill, and 60 achievements to unlock, Alexland can provide long hours of mindless, merciless fun. Available in English, Polish, French, German and Russian.

Why did you decide to choose Pascal as a programming language and SDL/SDL2 as a library for your projects?

suve: I chose Pascal mostly as it’s the language I’m most proficient and comfortable with. As for SDL, after working with a few different libraries in the past, I’ve found SDL easy to use, but nonetheless really versatile and fitting my needs. The library itself doesn’t really enforce anything on you, so you don’t have to change your habits (much), and the seemingly simplistic API is greatly extended by the supplementary SDL_XYZ libraries.

What do you think is the most interesting Pascal/SDL/SDL2 project out there (besides of your own, of course :-D)?

suve: Supraleiter seems the most awesome of them all, I think. Shame that quite probably I won’t be able to play sit, seeing as I only have an integrated GPU.

Are there any further steps for your projects or any new projects planned? What will they be?

suve: I have two projects underway right now, but one is too early in development and I don’t want to disclose it for fear of not delivering… and the other, for a change, is written in C instead of Pascal. 🙂

 

 

 

Wallman

Pascal SDL Projects?

A new page has been set up which gives an overview of projects done in SDL with Pascal (any dialect). The projects may be games, interpreters, libraries, anything. Of course SDL should play a key role and shouldn’t be just used to set up an OpenGL window (or similar). If possible I try to have an interview with the creator of the project.

The first project listed is the famous EGSL project and its successor Pulsar2D. Both have been created by Cybermonkey who kindly gave an interview and provided a lot of screenshots to me.

Feel free to contact me to let me know about other Pascal SDL projects.

Edit: As of 09/02/2016 I added suve’s Alexland and Colorful to the project page. Thanks for the interview and the screenshots.