Using OpenGL for Lighting Inbuilt 3D Shapes

You might like to make use of some of the 3D shapes available in the OpenGL units. These solid shapes need lighting to display them effectively. (Wire frame versions are available also). This what-when-how OpenGL page (with examples in C) was most useful for getting started with lighting. The GLUT unit is deprecated but it still works. The example should work if you put the 32-bit glut32.dll (available for download here) in the program folder.

The code follows the captured image of the output.

Captured Image

Captured Image

program OpenGL_Lighting3D_Shapes;
{$Apptype GUI}

uses
  SysUtils, GL, GLU, GLUT, SfmlGraphics, SfmlSystem, SfmlWindow;
var
  OutputWindow: TSfmlRenderWindow;
  OutputImage: PsfmlImage;
  Quad: PGLUquadric;
  Shininess: array[0..0] of GLFloat = (1.0);   // Makes a big difference if removed completely
  LightPosition: array[0..3] of GLFloat = (4.0, 4.0, 3.0, 0.0); // z must be > 0
  LightColour: array[0..3] of GLFloat = (1.0, 1.0, 0.0, 1.0);
  AmbientColour: array[0..3] of GLFloat = (0.9, 0.4, 0.4, 0.6);
begin
  // Create the main window
  OutputWindow := TSfmlRenderWindow.Create(SfmlVideoMode(500, 500),
    'SFML window with  OpenGL', [sfTitleBar, sfClose]);
  OutputWindow.SetActive(True); // Makes it the active window for OpenGL calls

  glMaterialfv(GL_FRONT, GL_SHININESS, Shininess);
  glMaterialfv(GL_FRONT, GL_AMBIENT, AmbientColour);

  glLightfv(GL_LIGHT0, GL_POSITION, LightPosition);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, LightColour);
  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, AmbientColour);

  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glEnable(GL_DEPTH_TEST);
  glClearDepth(1.0);

  // Set up a perspective projection
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity;
  glFrustum(-1, 1, -1, 1, 1, 500);
  // Clear buffers
  glClearColor(1.0, 0.95, 0.7, 1.0);
  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  glTranslatef(0, 0, -2);
  // Quadric required for sphere and cylinders
  Quad := @gluNewQuadric;
  gluQuadricDrawStyle(Quad, GLU_FILL);
  gluQuadricOrientation(Quad, GLU_OUTSIDE);
  gluQuadricNormals(Quad, GLU_FLAT);

  GluSphere(Quad, 0.5, 36, 72);

  glTranslatef(0, -1, 0);
  GluCylinder(Quad, 0.3, 0.3, 0.6, 36, 36);

  glTranslatef(0, 2.2, 0);
  glRotatef(45, 0, 1, 0);
  GluCylinder(Quad, 0.6, 0.3, 0.6, 36, 36);

  // GLUT shapes
  glLoadIdentity;
  glTranslatef(-1.1, -0.9, -2.0);
  glutSolidTeapot(0.5);
  glTranslatef(0.0, 1.7, 0.0);
  glutSolidTorus(0.25, 0.45, 36, 36);
  glTranslatef(2.3, 0.0, 0.0);
  glScalef(0.5, 0.5, 0.5);
  glutSolidIcosahedron;
  glTranslatef(0.0, -3.0, 0.0);
  glutSolidOctahedron;

  OutputImage := OutputWindow.Capture;
  SfmlImageSaveToFile(OutputImage, 'LightingShapes.png');
  OutputWindow.Display;
  sfmlsleep(sfmlSeconds(20));
end.
    
Programming - a skill for life!

How to use the Simple Fast Media Library in Lazarus