Page 1 of 1

some OpenGL examples

Posted: Thu May 08, 2014 5:55 pm
by applePi
i suspect that the purebasic collection (OpenWindow + OpenWindowedScreen + InitSprite) are OpenGLiZED , ie they provides the suitable environment to use Opengl functions immediately without special preparations such as used in C/C++ (win32 projects) or the example in PB distribution in "PureBasic\Examples\Sources - Advanced\OpenGL Cube\OpenGL.pb"
the special preparations are characterized by the usage of mysterious functions such as "wglCreateContext(hDC)" , "SetupPixelFormat();"PIXELFORMATDESCRIPTOR" ... etc. they are frustrating me and surely frustrating some users.
while in purebasic you can learn OpenGL focusing only on the OpenGL functions. together with everyday normal purebasic functions
this subject are discussed here before by other users, and i just refresh it in another way.
before presenting some examples i suggest to download the glu.pbi in the package "OpenGL-Engine-Linux.tar.gz" provided by remi_meier at the end of this thread http://www.purebasic.fr/english/viewtop ... 15&t=30065 . the glu.pbi will work also for windows. thank for remi_meier for keeping these files alive many years. used here in the Fourth example only

Example 1 : the same cube example in "PureBasic\Examples\Sources - Advanced\OpenGL Cube\OpenGL.pb" but deleting all the mysterious functions mentioned above

Image

Code: Select all

InitKeyboard()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
  CompilerIf Subsystem("OpenGL") = #False
    MessageRequester("Error", "Please set the Library subsystem to OpenGL from IDE : Compiler... Compiler Options")
    End
  CompilerEndIf
CompilerEndIf

If InitSprite() = 0
  MessageRequester("Error", "Can't open screen & sprite environment!")
  End
EndIf

OpenWindow(0, 0, 0, 800, 600, "rotating cube", #PB_Window_SystemMenu | #PB_Window_Invisible)
SetWindowColor(0, 14403509)
ContainerGadget(0, 5, WindowHeight(0)-50, 250, 60, #PB_Container_Raised)
ButtonGadget(1, 5, 5, 55, 20, "Stop/Run")
TrackBarGadget(2, 60, 10, 90, 20, 0, 200)
TextGadget(3, 150, 10, 100, 25, "0")
CloseGadgetList()
SetGadgetState(0, 0)

OpenWindowedScreen(WindowID(0), 0, 0, WindowWidth(0)-50, WindowHeight(0)-60, 0, 0, 0)

HideWindow(0, #False)
Global RollAxisX.f
Global RollAxisY.f
Global RollAxisZ.f

Global RotateSpeedX.f
Global RotateSpeedY.f
Global RotateSpeedZ.f

Global ZoomFactor.f
Global running = 1

glClearColor_ (0.0, 0.0, 0.0, 0.0);
glShadeModel_ (#GL_SMOOTH)

glEnable_(#GL_LIGHTING);
glEnable_(#GL_LIGHT0);
glEnable_(#GL_DEPTH_TEST);


glColorMaterial_(#GL_FRONT,  #GL_AMBIENT_AND_DIFFUSE)
glEnable_(#GL_COLOR_MATERIAL) ; color tracking

glEnable_(#GL_NORMALIZE)

Procedure.l Cube_Render()

 glPushMatrix_()                  ; Save the original Matrix coordinates
  glMatrixMode_(#GL_MODELVIEW)

  glTranslatef_(0, 0, ZoomFactor)  ;  move it forward a bit

  glRotatef_ (RollAxisX, 1.0, 0, 0) ; rotate around X axis
  glRotatef_ (RollAxisY, 0, 1.0, 0) ; rotate around Y axis
  glRotatef_ (RollAxisZ, 0, 0, 1.0) ; rotate around Z axis
 
  RollAxisX + RotateSpeedX 
  RollAxisY + RotateSpeedY 
  RollAxisZ + RotateSpeedZ 

  ; clear framebuffer And depth-buffer

  glClear_ (#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)

  ; draw the faces of a cube
  
  ; draw colored faces

  glDisable_(#GL_LIGHTING)
  glBegin_  (#GL_QUADS)
  
  ; Build a face, composed of 4 vertex ! 
  ; glBegin() specify how the vertexes are considered. Here a group of
  ; 4 vertexes (GL_QUADS) form a rectangular surface.

  ; Now, the color stuff: It's r,v,b but with float values which
  ; can go from 0.0 To 1.0 (0 is .. zero And 1.0 is full intensity) 
  
  glNormal3f_ (0,0,1.0)
  glColor3f_  (0,0,1.0)
  glVertex3f_ (0.5,0.5,0.5)   
  glColor3f_  (0,1.0,1.0)         
  glVertex3f_ (-0.5,0.5,0.5)
  glColor3f_  (1.0,1.0,1.0)
  glVertex3f_ (-0.5,-0.5,0.5)
  glColor3f_  (0,0,0)
  glVertex3f_ (0.5,-0.5,0.5) 

  ; The other face is the same than the previous one 
  ; except the colour which is nice blue To white gradiant

  glNormal3f_ (0,0,-1.0)
  glColor3f_  (0,0,1.0)
  glVertex3f_ (-0.5,-0.5,-0.5)
  glColor3f_  (0,0,1.0)
  glVertex3f_ (-0.5,0.5,-0.5)
  glColor3f_  (1.0,1.0,1.0)
  glVertex3f_ (0.5,0.5,-0.5)
  glColor3f_  (1.0,1.0,1.0)
  glVertex3f_ (0.5,-0.5,-0.5)
  
  glEnd_()
  
  ; draw shaded faces

  glEnable_(#GL_LIGHTING)
  glEnable_(#GL_LIGHT0)
  glBegin_ (#GL_QUADS)

  glNormal3f_ (   0, 1.0,   0)
  glVertex3f_ ( 0.5, 0.5, 0.5)
  glVertex3f_ ( 0.5, 0.5,-0.5)
  glVertex3f_ (-0.5, 0.5,-0.5)
  glVertex3f_ (-0.5, 0.5, 0.5)

  glNormal3f_ (0,-1.0,0)
  glVertex3f_ (-0.5,-0.5,-0.5)
  glVertex3f_ (0.5,-0.5,-0.5)
  glVertex3f_ (0.5,-0.5,0.5)
  glVertex3f_ (-0.5,-0.5,0.5)

  glNormal3f_ (1.0,0,0)
  glVertex3f_ (0.5,0.5,0.5)
  glVertex3f_ (0.5,-0.5,0.5)
  glVertex3f_ (0.5,-0.5,-0.5)
  glVertex3f_ (0.5,0.5,-0.5)

  glNormal3f_ (-1.0,   0,   0)
  glVertex3f_ (-0.5,-0.5,-0.5)
  glVertex3f_ (-0.5,-0.5, 0.5)
  glVertex3f_ (-0.5, 0.5, 0.5)
  glVertex3f_ (-0.5, 0.5,-0.5)

  glEnd_()

  glPopMatrix_()
  glFinish_()
    

EndProcedure

HideWindow(0, #False)

RotateSpeedX = 2.0   ; The speed of the rotation For the 3 axis
RotateSpeedY = 2
RotateSpeedZ = 2.0

ZoomFactor = 0      ; Distance of the camera. Negative value = zoom back

glViewport_(0, 0, WindowWidth(0), WindowHeight(0))
glMatrixMode_(#GL_PROJECTION)
glLoadIdentity_()
gluPerspective_(30.0, Abs(WindowWidth(0) / WindowHeight(0)), 0.1, 500.0)
glMatrixMode_(#GL_MODELVIEW)
glLoadIdentity_()
glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
glLoadIdentity_ ()
; viewing transformation
glTranslatef_(0.0, 2.0, -1.0);
gluLookAt_(0,5,15,0,1.5,0,0,1,0);
  

  Repeat
    EventID = WindowEvent()
    Select EventID
      Case #PB_Event_Gadget
          If EventGadget() = 1
            running ! 1
            RotateSpeedX = running
            RotateSpeedY = running
            RotateSpeedZ = running
          EndIf
          If EventGadget() = 2
            ZoomFactor = (GetGadgetState(2)/200)*5
           
           SetGadgetText(3, Str(ZoomFactor))
          EndIf     
      Case #PB_Event_CloseWindow
        Quit = 1
    EndSelect
    ExamineKeyboard()
     
  Cube_Render()
  FlipBuffers()
  Delay(20)
 
  Until Quit = 1 Or KeyboardPushed(#PB_Key_Escape)

End
Example 2: this example are using "rotatingHelix1.cpp" which can be downloaded free from http://www.sumantaguha.com/downloads (the code zip 6MB) don't forget to download chapter 2, 9, 11 it is a good lessons. but alas the book are paper only, and nowadays who want to read that microscopic characters on paper !!. i have copied the cpp code inside the example 1 code and just a small change i made to get the code works.

Image

Code: Select all

InitKeyboard()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
  CompilerIf Subsystem("OpenGL") = #False
    MessageRequester("Error", "Please set the Library subsystem to OpenGL from IDE : Compiler... Compiler Options")
    End
  CompilerEndIf
CompilerEndIf

If InitSprite() = 0
  MessageRequester("Error", "Can't open screen & sprite environment!")
  End
EndIf

OpenWindow(0, 0, 0, 800, 600, "rotating Helix", #PB_Window_SystemMenu | #PB_Window_Invisible)
SetWindowColor(0, 14403509)
ContainerGadget(0, 5, WindowHeight(0)-50, 250, 60, #PB_Container_Raised)
ButtonGadget(1, 5, 5, 55, 20, "Stop/Run")
TrackBarGadget(2, 60, 10, 90, 20, 0, 200)
TextGadget(3, 150, 10, 100, 25, "0")
CloseGadgetList()
SetGadgetState(0, 0)

OpenWindowedScreen(WindowID(0), 0, 0, WindowWidth(0)-50, WindowHeight(0)-60, 0, 0, 0)

HideWindow(0, #False)
Global RollAxisX.f
Global RollAxisY.f
Global RollAxisZ.f

Global RotateSpeedX.f
Global RotateSpeedY.f
Global RotateSpeedZ.f

Global ZoomFactor.f ;Distance of the camera
Global running = 1
Global angle.f
Global rot.f = 3


Procedure.l Cube_Render()

 glPushMatrix_()                  ; Save the original Matrix coordinates
  glMatrixMode_(#GL_MODELVIEW)

  glTranslatef_(0, 0, -120)  ;  move it forward a bit

  glRotatef_ (RollAxisX, 1.0, 0, 0) ; rotate around X axis
  glRotatef_ (RollAxisY, 0, 1.0, 0) ; rotate around Y axis
  glRotatef_ (RollAxisZ, 0, 0, 1.0) ; rotate around Z axis
 
  RollAxisX + RotateSpeedX 
  RollAxisY + RotateSpeedY 
  RollAxisZ + RotateSpeedZ 

  ; clear framebuffer And depth-buffer

  glClear_ (#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)

  
  glDisable_(#GL_LIGHTING)
  glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT) ;Clear The Screen And The Depth Buffer
  glLoadIdentity_() ;Reset The View
 
  glViewport_(0, 0, WindowWidth(0), WindowHeight(0))
  glMatrixMode_(#GL_PROJECTION)
  glLoadIdentity_()
  ;gluPerspective_(90.0, Abs(WindowWidth(0) / WindowHeight(0)), 0.1, 1000.0)
  glFrustum_(-10.0, 10.0, -10.0, 10.0, 10.0, 1000.0); 
 
  
   R.f = 30.0; // Radius of helix.

   t.f = -10*#PI; // Angle parameter along helix.

   glClear_(#GL_COLOR_BUFFER_BIT);
   glColor3f_(1.0, 0.7, 0.0);
   glPushMatrix_();

   ;The Trick: To align the axis of the helix along the y-axis prior To rotation
   ;And then Return it To its original location.
   glTranslatef_(0.0, 0.0, -120+ZoomFactor);
   glRotatef_(angle, 1, 1, 1);
   glTranslatef_(0.0, 0.0, 60.0);
   ;glPointSize_(5);
   angle.f + rot
   ;//GL_POINTS
   ;//GL_LINE_STRIP
   glBegin_(#GL_LINE_STRIP);
      
   While t <= 10 * #PI
     
       glVertex3f_(R * Cos(t), t, R * Sin(t) - 60.0);
       t = t+(#PI/40.0)
      
   
   Wend
 
 glEnd_();
 glPopMatrix_();
 
 glFinish_()
 
EndProcedure

HideWindow(0, #False)

RotateSpeedX = 2.0   ; The speed of the rotation For the 3 axis
RotateSpeedY = 2.0
RotateSpeedZ = 2.0

  Repeat
    EventID = WindowEvent()
    Select EventID
      Case #PB_Event_Gadget
          If EventGadget() = 1
            running ! 1
            rot = 3*running
          EndIf
          If EventGadget() = 2
           ZoomFactor = (GetGadgetState(2)/200)*100
           SetGadgetText(3, Str(ZoomFactor))
          EndIf     
      Case #PB_Event_CloseWindow
        Quit = 1
    EndSelect
    ExamineKeyboard()
     
  Cube_Render()
  FlipBuffers()
  Delay(20)
 
  Until Quit = 1 Or KeyboardPushed(#PB_Key_Escape)

End
Example 3: a mechanical device posted before but shortened here too much , it is just needs a lighting correction
Image

Code: Select all

InitKeyboard()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
  CompilerIf Subsystem("OpenGL") = #False
    MessageRequester("Error", "Please set the subsystem to OpenGL")
    End
  CompilerEndIf
CompilerEndIf

If InitSprite() = 0
  MessageRequester("Error", "Can't open screen & sprite environment!")
  End
EndIf

OpenWindow(0, 0, 0, 640, 480, "press space key to switch On/Off the fan rotation", #PB_Window_SystemMenu | #PB_Window_Invisible)
SetWindowColor(0, 0)
OpenWindowedScreen(WindowID(0), 0, 0, WindowWidth(0), WindowHeight(0), 0, 0, 0)

HideWindow(0, #False)
Global running.b = 0;
Global angle_step.f = 0.3
Global angle_direction.f
lngh.f : width.f : depth.f


glClearColor_ (0.0, 0.0, 0.0, 0.0);
glShadeModel_ (#GL_SMOOTH)

glEnable_(#GL_LIGHTING);
glEnable_(#GL_LIGHT0);
glEnable_(#GL_DEPTH_TEST);


glColorMaterial_(#GL_FRONT,  #GL_AMBIENT_AND_DIFFUSE)
glEnable_(#GL_COLOR_MATERIAL) ; color tracking

glEnable_(#GL_NORMALIZE)

Procedure.l blade(lngh.f, width.f, depth.f)
   a.f = lngh: b.f = width: c.f = depth
       
glBegin_(#GL_QUADS);

; Top face of box
    glColor3f_(1.0, 0.0, 0.0) ; red blades !
    glNormal3f_(0.0, 1.0, 0.0)
   
    glVertex3f_(a, b, -c);     // Top right vertex (Top of cube)
    glVertex3f_(-a, b, -c);    //Top left vertex (Top of cube)
    glVertex3f_(-a, b, c);     // Bottom left vertex (Top of cube)
    glVertex3f_(a, b, c);      // Bottom right vertex (Top of cube)

    ;Bottom face of box
   
    glNormal3f_(0.0, -1.0, 0.0)   
    glVertex3f_(a, -b, -c);     // Top right vertex (Bottom of cube)
    glVertex3f_(-a, -b, -c);    // Top left vertex (Bottom of cube)
    glVertex3f_(-a, -b, c);   // Bottom left vertex (Bottom of cube)
    glVertex3f_( a, -b, c);   // Bottom right vertex (Bottom of cube)
   
    ;Front of box
   
    glNormal3f_(0.0, 0.0, 1.0)     
    glVertex3f_(a, b, c);      // Top right vertex (Front)
    glVertex3f_(-a, b, c);     // Top left vertex (Front)
    glVertex3f_(-a, -b, c);    // Bottom left vertex (Front)
    glVertex3f_(a, -b, c);     // Bottom right vertex (Front)
   
    ;Back of box
   
    glNormal3f_(0.0, 0.0, -1.0)     
    glVertex3f_(a, -b, -c);    // Bottom right vertex (Back)
    glVertex3f_(-a, -b, -c);   // Bottom left vertex (Back)
    glVertex3f_(-a, b, -c);    // top left vertex (Back)
    glVertex3f_(a, b, -c);     // Top right vertex (Back)
   
    ;Left of box
   
    glNormal3f_(-1.0, 0.0, 0.0)         
    glVertex3f_(-a, b, c);     // Top right vertex (Left)
    glVertex3f_(-a, b, -c);    // Top left vertex (Left)
    glVertex3f_(-a, -b, -c);   // Bottom left vertex (Left)
    glVertex3f_(-a, -b, c);    // Bottom vertex (Left)
   
    ;Right of box
       
    glNormal3f_(1.0, 0.0, 0.0)   
    glVertex3f_(a, b, -c);     // Top right vertex (Right)
    glVertex3f_(a, b, c);      // Top left vertex (Right)
    glVertex3f_(a, -b, c);     // Bottom left vertex (Right)
    glVertex3f_(a, -b, -c);    // Bottom right vertex (Right)
   
    ;End drawing the box
    glEnd_();
    ;Return TRUE;
           


EndProcedure

Procedure.l Fan_Render(spin.f)
glPushMatrix_();

  glColor3f_(1.0, 1.0, 0.0)
 
  ;Fan
  glPushMatrix_();
  ;Fan Base:
        qobj = gluNewQuadric_();
      gluQuadricDrawStyle_(qobj, #GL_FILL); /* smooth shaded */
      gluQuadricNormals_(qobj, #GL_SMOOTH);
      glScalef_( 4 , 0.5 , 4 );
      ;glEnable_(#GL_NORMALIZE);
      ;Sphere With radius 0.25 then scaled
      gluSphere_(qobj, 0.25, 20, 20);
  glPopMatrix_();
   
   ;Fan stand:
  glPushMatrix_();
      gluQuadricDrawStyle_(qobj, #GL_FILL); /* flat shaded */
      gluQuadricNormals_(qobj, #GL_FLAT);
      glRotatef_(-90, 1.0, 0.0, 0.0);
      gluCylinder_(qobj, 0.125, 0.125, 3, 16, 10);
   
  glPopMatrix_();
   
    ;Fan Motor:
    glRotatef_(angle_direction, 0.0, 1.0, 0.0)
  glPushMatrix_();
     gluQuadricDrawStyle_(qobj, #GL_FILL); /* smooth shaded */
     gluQuadricNormals_(qobj, #GL_SMOOTH);
      glTranslatef_(0.0, 2.5, 0.0);
      glScalef_( 0.5, 0.5, 1);
      ;glEnable_(#GL_NORMALIZE);
      gluSphere_(qobj, 1 , 20 , 20 );
  glPopMatrix_();

   ;Blades construction
   glTranslatef_(0.0, 2.5, 0.5)
   ;glClear_ (#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
  glRotatef_(spin, 0.0, 0.0, 1.0 );
   For i = 1 To 360  Step 60
   
    glPushMatrix_();
      glRotatef_( i, 0.0, 0.0, 1.0 );
      glTranslatef_(1.2, 0.0, 0.0);
      glRotatef_( -45, 1.0, 0.0, 0.0 );
      glShadeModel_(#GL_FLAT);   
      glEnable_(#GL_DEPTH_TEST);
      glPushMatrix_();
      ;calling blade ie: drawing the Blade of the fan*/
      blade(0.8,0.3,0.01);
     glPopMatrix_();
    glPopMatrix_();     
   Next
       
    
glPopMatrix_();

EndProcedure
Procedure.f Fan_Physics()
   Static spin.f
   Static speed.f
   If running = 1
     speed = speed + 1
     angle_direction = angle_direction + angle_step
    If angle_direction > 110
      angle_step = -0.3
      ElseIf angle_direction < 0
           angle_step = 0.3
    EndIf
   EndIf
   If speed > 360.0: speed = 360.0: EndIf
   If running = 0 :speed = speed - 1.8: EndIf
  If speed < 0: speed = 0: EndIf
  spin = spin + speed/100
  ProcedureReturn spin
     
EndProcedure
HideWindow(0, #False)

  Procedure.l Fan_Run()
  glViewport_(0, 0, WindowWidth(0), WindowHeight(0))
  glMatrixMode_(#GL_PROJECTION)
  glLoadIdentity_()
  gluPerspective_(30.0, Abs(WindowWidth(0) / WindowHeight(0)), 0.1, 500.0)
  glMatrixMode_(#GL_MODELVIEW)
  glLoadIdentity_()
  glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
   glLoadIdentity_ ()
   ; viewing transformation
   glTranslatef_(0.0, 0.0, -6.0);
   gluLookAt_(5,5,5,0,1.5,0,0,1,0);
   spin.f = Fan_Physics();
   
   Fan_Render(spin);
 
EndProcedure


While Quit.b = 0

  Repeat
    EventID = WindowEvent()
    Select EventID
           
      Case #PB_Event_CloseWindow
        Quit = 1
    EndSelect
    ExamineKeyboard()
  If KeyboardReleased(#PB_Key_Space)
      running ! 1
   EndIf
 
  Fan_Run()
  FlipBuffers()
  Delay(1)
 
  Until EventID = 0
 
Wend

End
Example 4: this needs file glu.pbi from the remi_meier package menstioned above

Image

Code: Select all

;;IncludeFile "glu.pbi"

Global xrot.f ;X Rotation
Global yrot.f ;Y Rotation
Global xspeed.f ;X Rotation Speed
Global yspeed.f ;Y Rotation Speed
;Global z.f=-5.0 ;Depth Into The Screen

Global quadratic.l ;Storage For Our Quadratic Objects ( NEW )


InitKeyboard()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
  CompilerIf Subsystem("OpenGL") = #False
    MessageRequester("Error", "Please set the subsystem to OpenGL")
    End
  CompilerEndIf
CompilerEndIf

If InitSprite() = 0
  MessageRequester("Error", "Can't open screen & sprite environment!")
  End
EndIf
Global angle.f = 0
OpenWindow(0, 0, 0, 800, 600, "Dodecahedron and other GLut objects .. use the slider to rotate", #PB_Window_SystemMenu | #PB_Window_Invisible)
SetWindowColor(0, 14403509)
ContainerGadget(0, 5, WindowHeight(0)-50, 250, 60, #PB_Container_Raised)
TrackBarGadget(2, 60, 10, 90, 20, 0, 200)
TextGadget(3, 150, 10, 100, 25, "0")
CloseGadgetList()
SetGadgetState(0, 0)

OpenWindowedScreen(WindowID(0), 0, 0, WindowWidth(0)-50, WindowHeight(0)-60, 0, 0, 0)

HideWindow(0, #False)
Global running.b = 0;
lngh.f : width.f : depth.f 

glClearColor_ (0.0, 0.0, 0.0, 0.0);
glShadeModel_ (#GL_SMOOTH)

glEnable_(#GL_LIGHTING);
glEnable_(#GL_LIGHT0);
glEnable_(#GL_DEPTH_TEST);


Procedure.l DrawGLScene()
 glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT) ;Clear The Screen And The Depth Buffer
 glLoadIdentity_() ;Reset The View
 
  glViewport_(0, 0, WindowWidth(0), WindowHeight(0))
  glMatrixMode_(#GL_PROJECTION)
  glLoadIdentity_()
  gluPerspective_(30.0, Abs(WindowWidth(0) / WindowHeight(0)), 0.1, 500.0)
  glMatrixMode_(#GL_MODELVIEW)
  glLoadIdentity_()
  glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
  glLoadIdentity_ ()
   ; viewing transformation  
   glTranslatef_(0.0, 0.0, -10.0); 
   ;gluLookAt_(5,5,5,0,1.5,0,0,1,0);
      
   glPushMatrix_()                  ; Save the original Matrix coordinates
  ;glMatrixMode_(#GL_MODELVIEW)
  glTranslatef_(0, 0, ZoomFactor)  ;  move it forward a bit
  glClear_ (#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
  glDisable_(#GL_LIGHTING)
  glRotatef_(angle, 0.0, 1.0, 0.0)

glScalef_(0.4,0.4,0.4)  
glBegin_(#GL_TRIANGLES) ; start drawing a triangle
  glColor3f_(1.0, 0.0, 0.0);
  glVertex3f_( 0.0, 1.0, 0.0) ; top
  glColor3f_(0.0, 1.0, 0.0);
  glVertex3f_(-1.0,-1.0, 0.0) ; bottom left
  glColor3f_(0.0, 0.0, 1.0);
  glVertex3f_( 1.0,-1.0, 0.0) ; bottom right
glEnd_() ; finished 
  
glPopMatrix_() 
 
 glRotatef_(xrot,1.0,0.0,0.0) ;Rotate On The X Axis By xrot
 glRotatef_(yrot,0.0,1.0,0.0) ;Rotate On The Y Axis By yrot
 ;glutWireTeapot_(2) 
 glColor3f_(1.0, 0.0, 1.0)
 glutWireDodecahedron_()
 glColor3f_(0.0, 0.6, 0.0)
 glutWireIcosahedron_()
 
 xrot+xspeed ;Add xspeed To xrot
 yrot+yspeed ;Add yspeed To yrot
 ProcedureReturn #True ;Keep Going
 
EndProcedure


While Quit.b = 0

  Repeat 
    EventID = WindowEvent()
    Select EventID
        Case #PB_Event_Gadget
          If EventGadget() = 1
            run.i = 1
          EndIf
          If EventGadget() = 2
           angle = GetGadgetState(2)
           SetGadgetText(3, Str(angle))
           yspeed=0.01*angle
           ;xspeed=0.01*angle
          EndIf
           
      Case #PB_Event_CloseWindow
        Quit = 1
    EndSelect
    ExamineKeyboard()
  If KeyboardReleased(#PB_Key_Escape)
    Quit = 1
      
   EndIf
  
  DrawGLScene()
  FlipBuffers()
  Delay(1)
  
  Until EventID = 0
  
Wend

End

some references:
http://glprogramming.com/red/ the red book

GLFW 304 wrapper 1.03:
http://www.purebasic.fr/english/viewtop ... 40&t=57875

Simple Windowed OpenGL Framework - for OpenGL beginners
http://www.purebasic.fr/english/viewtopic.php?t=28835

Small cross-platform OpenGL demo:
http://www.purebasic.fr/english/viewtop ... 12&t=49583

OpenGL with GL, GLU and GLUT:
http://www.purebasic.fr/english/viewtopic.php?p=223261

How to initialise and use OpenGL (not OGRE) in MacOSX:
http://www.purebasic.fr/english/viewtop ... 19&t=36261

Re: some OpenGL examples

Posted: Thu May 08, 2014 6:31 pm
by luis
Hi
applePi wrote:i suspect that the purebasic collection (OpenWindow + OpenWindowedScreen + InitSprite) are OpenGLiZED , ie they provides the suitable environment to use Opengl functions immediately without special preparations such as used in C/C++
They are OpenGLiZED as long as you specify the opengl subsystem when required (Windows only).
The big problem with the current implementation of that, when you want to use opengl using the pre-cooked environment created by PB, is you have no control on how the rendering context is created.

See this thread / feature request for more info -> http://www.purebasic.fr/english/viewtop ... =3&t=57157

EDIT: here you can find another set of opengl includes up to opengl 4.1, based on the original one by remi_meyer -> http://www.purebasic.fr/english/viewtop ... 74#p348374

Re: some OpenGL examples

Posted: Thu May 08, 2014 6:33 pm
by IdeasVacuum
Brilliant stuff applePi

Re: some OpenGL examples

Posted: Thu May 08, 2014 6:50 pm
by IdeasVacuum
..... and very useful OpenGL 4 update from Luis too.

Re: some OpenGL examples

Posted: Thu May 08, 2014 6:57 pm
by Artus
Hio,

@applePI: You should take the OpenGL 4.1 include, which luis posted the link
or write your own like i did to be always up to date..
In our time 2014, nobody use glBegin and glEnd anymore ^^
Better use VAO (Vertex Array Object) and VBO (Vertex Buffer Object) and render complete over Shader.

Greetings
Arthur
UnionBytes

Re: some OpenGL examples

Posted: Thu May 08, 2014 7:45 pm
by Samuel
@Artus
Personally, I prefer the newer shader based OpenGL as well, but for new users the fixed pipeline is much easier to understand and work with.
OpenGL 3.3 and up can be a bit of a overload for many people. If applePi's up for the challenge then great, but if not then I can't say I blame him.

Re: some OpenGL examples

Posted: Thu May 08, 2014 8:19 pm
by Artus
@Samuel: Yeah, you are right.
At the end it depends what he (the user) want to do with it. I just thought, I prevent him to do the double work ^^ But maybe you are right, this way is better for beginners.

@applePI: I'm sorry, I didn't want to say the example is not good or something like that. It is good, it's just on the classic way.

Greetings
Arthur
UnionBytes

Re: some OpenGL examples

Posted: Thu May 08, 2014 8:32 pm
by applePi
Artus, i never heard that glBegin()+ glEnd() are deprecated, in fact i'm from the v1.1 era
what should i replace:
glBegin_ (#GL_QUADS)
glVertex3f_ (0.5,0.5,0.5)
glVertex3f_ (-0.5,0.5,0.5)
glVertex3f_ (-0.5,-0.5,0.5)
glVertex3f_ (0.5,-0.5,0.5)
glEnd_()

using the luis 4.1 include update ?
the glBegin()+ glEnd() are used every where even in recent opengl books, and in the purebasic cube example.
in fact i have asked my self many times before that to define a cube we need too many lines and i felt it is not a good way.

Re: some OpenGL examples

Posted: Thu May 08, 2014 9:07 pm
by Artus
They are already deprecated, i guess, since OpenGL 3.3, but i'm not sure ^^.

Yes, this is the same problem I had, I followed the books I bought but the most are just old and deprecated.
You have to search explicit after OpenGL 3.3 or 4 Tutorials on google, but now there are a lot of.
Of course they are all in different languages the most c++, but not so hard to understand.

PS: If you start to write a deferred rendering system, than it get really hard to find any good tutorial. :)

Greetings
Arthur
UnionBytes

Re: some OpenGL examples

Posted: Thu May 08, 2014 9:11 pm
by Samuel
Here are some tutorials if you don't mind a little reading. I know their code is in C++, but just reading their explanations will help you understand the process better.
http://www.opengl-tutorial.org/

As Artus said there's a lot of information out there, but most of it is in C++. Which is one of the reasons I use C++ for some of my bigger OpenGL projects.

Re: some OpenGL examples

Posted: Thu May 08, 2014 9:45 pm
by luis
Just my little opinion.

In the opengl library I'm writing, I mainly use immediate mode opengl.

The good thing about it it's vastly supported, easy to understand (up to a point), runs on old and limited hardware, there are tons of code written with it.

Depends of the type of features you want to use and how complex it's the application you want to write, most of all how much data you want to push around, that's really the most important parameter in my opinion. Ok, there are other points but this one is really preponderant.

For the 95% of the games people like us (I mean people doing this alone to have fun with it and learn real-time graphical game programming) opengl 1.2 it's more then enough, especially if you stay 2d only.

If you want to do some in 3d, opengl 2.1 is probably enough.

Also not all the platforms have the lastest opengl drivers, or they are not available on all the hardware for that platform.

The good thing is with extensions you can get the *most* important features from modern opengl implementations and fallback when something it's not available.

That's what I do in my lib, if there are some modern features available and they make a huge difference in some way I use them (vbo, fbo, vertex arrays, multisample, shaders, etc.), if they are not there I fall back one level, and sometime if that is not available another level too. Performance or image quality can degrade, but still works.

That's a good compromise, and when using the lib it's generally transparent.

Modern opengl it's more efficient, more easily customizable, possibly more elegant but with this lib I'm targeting compatibility and simplicity over efficiency. Old-style opengl still has its place and rarely will be a bottleneck unless you are making an AAA game and/or pushing a lot of data.

Re: some OpenGL examples

Posted: Fri May 09, 2014 1:42 pm
by applePi
in theory could it be possible that the compiler options have 3 official choices opengl_1.2 opengl_4.1 and default DX so the user can choose what is suitable for his system regarding the opengl subsystem , the lib folder can have 2 versions of opengl32_1.2.LIB opengl32_4.1.LIB , the user will use what is suitable to his opengl32.DLL in windows\system32
Image

Re: some OpenGL examples

Posted: Fri May 09, 2014 5:15 pm
by luis
I think PB graphical commands are based on opengl 1.2.

To use in YOUR opengl programs any version of opengl from 1.x to 4.x you just need for pb to provide the appropriate RC (rendering context), so probably having different subsystem for every version it's not needed.
The opengl library it's ALWAYS the same. All the advanced features are accessed through extensions.
What your opengl implementation supports depends on the driver coming with your video card.

We just need a way to "hint" to pb how we would like the RC to be created. In that case that could break the pb graphic commands but that's ok, you wouldn't use them anyway.
Without "hints" pb should just create the RC as it see fit for its personal use like it's doing now.

As I said, up to now you have zero control on the RC, and the provided RC differs from platform to platform (as shown in the thread I've linked above) and could potentially differ from version to version for what we know.
This make the usage of the opengl subsystem shortcut to program in opengl with PB practically useless or at best unreliable unless you just want to try it out some simple opengl code to start to learn it.
That's why I've made that request (I've actually limited myself about its scope) and why at this moment it's required to use the "scary api stuff" on every platform to initialize the rendering context in the appropriate way for your project.
I don't have nothing against doing the initialization by myself as I'm doing now, but if implemented it would made easier and more accessible opengl development to everyone (that's why there are so many opengl interface libs around) and shouldn't be a big burden for the devs, since pb already provide some sort of RC when using the opengl subsystem. It just needs more or less to be influenced by some external hint.

Re: some OpenGL examples

Posted: Sun May 11, 2014 9:58 am
by applePi
luis, what is the opengl version the following code are invoking since it has new instructions i think, it is just drawing a square ,it is from this site also look other small one at the end of that page
it seems use the same strategy used in the official PB opengl cube example but adding other functions, also we don't need to specify the library subsystem

Code: Select all

Structure TVertex
  x.f
  y.f
  z.f
EndStructure
Enumeration
  #Window_0
EndEnumeration
#GL_COLOR_BUFFER_BIT                = $00004000
#GL_DEPTH_BUFFER_BIT                = $00000100
#GL_ARRAY_BUFFER                    = $8892
#GL_ELEMENT_ARRAY_BUFFER            = $8893
#GL_MODELVIEW                       = $1700
#GL_PROJECTION                      = $1701
#GL_SMOOTH                          = $1D01
#GL_DEPTH_TEST                      = $0B71
#GL_CULL_FACE                       = $0B44
#GL_STATIC_DRAW                     = $88E4
#GL_VERTEX_ARRAY                    = $8074
#GL_FLOAT                           = $1406
#GL_TRIANGLES                       = $0004
#GL_UNSIGNED_BYTE                   = $1401
#GL_UNSIGNED_SHORT                  = $1403
#GL_UNSIGNED_INT                    = $1405

Global pfd.PIXELFORMATDESCRIPTOR

Procedure HandleError (Result, Text$)
  If Result = 0
    MessageRequester("Error", Text$, 0)
    End
  EndIf
EndProcedure

Procedure OGL_PB(Width,Height)
Global hWnd = OpenWindow(#Window_0, 0, 0, Width, Height, "PB_OGL",  #PB_Window_SystemMenu|#PB_Window_ScreenCentered )
Global hdc = GetDC_(hWnd)       
pfd\nSize        = SizeOf(PIXELFORMATDESCRIPTOR)
pfd\nVersion     = 1
pfd\dwFlags      = #PFD_SUPPORT_OPENGL | #PFD_DOUBLEBUFFER | #PFD_DRAW_TO_WINDOW
pfd\dwLayerMask  = #PFD_MAIN_PLANE
pfd\iPixelType   = #PFD_TYPE_RGBA
pfd\cColorBits   = 24
pfd\cDepthBits   = 24 
pixformat = ChoosePixelFormat_(hdc, pfd)
HandleError( SetPixelFormat_(hdc, pixformat, pfd), "SetPixelFormat()")
hrc = wglCreateContext_(hdc)
HandleError( wglMakeCurrent_(hdc,hrc), "vglMakeCurrent()") 
EndProcedure

OGL_PB(800,600)
Prototype PFNGLGENBUFFERSPROC ( n.i, *buffers)
Global glGenBuffers.PFNGLGENBUFFERSPROC
glGenBuffers = wglGetProcAddress_( "glGenBuffers" )
Prototype PFNGLBINDBUFFERPROC ( target.l, buffer.i)
Global glBindBuffer.PFNGLBINDBUFFERPROC
glBindBuffer = wglGetProcAddress_( "glBindBuffer" )
Prototype PFNGLBUFFERDATAPROC ( target.l, size.i, *Data_, usage.l)
Global glBufferData.PFNGLBUFFERDATAPROC
glBufferData = wglGetProcAddress_( "glBufferData" )

glMatrixMode_(#GL_PROJECTION)
glLoadIdentity_();
gluPerspective_(45.0, 800/600, 1.0, 60.0)
glMatrixMode_(#GL_MODELVIEW)
glTranslatef_(0, 0, -4)
glShadeModel_(#GL_SMOOTH) 
glEnable_(#GL_DEPTH_TEST)
glEnable_(#GL_CULL_FACE)     
glViewport_(0, 0, 800, 600)

Global BuffId.i,iiId.i
Dim Vertex.TVertex(3)
Vertex(0)\x = 1
Vertex(0)\y = -1
Vertex(0)\z = 0

Vertex(1)\x = -1
Vertex(1)\y = -1
Vertex(1)\z = 0

Vertex(2)\x = 1
Vertex(2)\y = 1
Vertex(2)\z = 0

Vertex(3)\x = -1
Vertex(3)\y = 1
Vertex(3)\z = 0
;=================================================================================
;==============??? ??????????? ?????? )))=========================================
Dim index.l(5)
index(0) = 1 
index(1) = 0
index(2) = 2
index(3) = 3
index(4) = 1
index(5) = 2

;indexsize = 6 ;#GL_UNSIGNED_BYTE
indexsize = 6*2 ;#GL_UNSIGNED_SHORT
indexsize = 6*4 ;#GL_UNSIGNED_INT

glGenBuffers( 1, @BuffId )
glBindBuffer(#GL_ARRAY_BUFFER, BuffId )
glBufferData(#GL_ARRAY_BUFFER,SizeOf(TVertex)*4,@Vertex(0), #GL_STATIC_DRAW)
glBindBuffer(#GL_ARRAY_BUFFER,0);
glGenBuffers( 1, @iiId );
glBindBuffer(#GL_ELEMENT_ARRAY_BUFFER, iiId);
glBufferData(#GL_ELEMENT_ARRAY_BUFFER, indexsize,@index(0),#GL_STATIC_DRAW);
glBindBuffer(#GL_ELEMENT_ARRAY_BUFFER, 0);


Repeat
    Event = WindowEvent()
    Select Event
      Case #PB_Event_CloseWindow
        Quit = 1      
    EndSelect
    glClearColor_(0.2, 0.2, 0.2, 1)
    glClear_(#GL_COLOR_BUFFER_BIT | #GL_DEPTH_BUFFER_BIT)
    
    glEnableClientState_(#GL_VERTEX_ARRAY )
    glBindBuffer(#GL_ARRAY_BUFFER, BuffId)
    glVertexPointer_(3, #GL_FLOAT,0,0)

    
    glBindBuffer(#GL_ELEMENT_ARRAY_BUFFER, iiId)
    ;glDrawElements_(#GL_TRIANGLES,indexsize,#GL_UNSIGNED_BYTE,0)
    ;glDrawElements_(#GL_TRIANGLES,indexsize,#GL_UNSIGNED_SHORT,0)
    glDrawElements_(#GL_TRIANGLES,indexsize,#GL_UNSIGNED_INT,0)
    glBindBuffer(#GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(#GL_ARRAY_BUFFER,0);
    glDisableClientState_(#GL_VERTEX_ARRAY);

    SwapBuffers_(hdc)
    Delay(16)
  Until Quit = 1
End

Re: some OpenGL examples

Posted: Sun May 11, 2014 11:37 am
by luis
Using extension correctly is a relatively complex subject.
The way that code is using them is not reliable, it's ok for a quick test on a specific computer but it will have all sort of problems on other computers. Just don't follow literally that example in REAL code you need to distribute. It will easily not find those entry points by those names on another PC.

Also the name of the functions you import can be different if they are core commands supported by a certain opengl version, or if they are the same command see as an extension available for a lower GL version. They can have an extension like EXT, ARB, etc.

The name of the extension also follow the same rule with a prefix for the name.

GLX_ : Linux only (X11)
AGL_ : OSX only (Carbon)
WGL_ : Windows only (Win32 wiggles)

EXT_ : A generic extension
ARB_ : An extension that has been accepted by all the members of the OpenGL Architecture Review Board
NV_ : nVidia (may be supported by other vendors too)
AMD_ : AMD (may be supported by other vendors too)
INTEL_ : Intel (may be supported by other vendors too)

Also you should always check for an extension to exist before trying to use it, that way you also know if the function names you are going to import have particular suffix that need to be append to the name.

You should read a good book explaining how extensions work, AND google the net and read at least 5 or 6 different tutorials about them, collectively they should get it right and you will end up with the right idea. Maybe I could write one here but ATM I don't have time (not that I'm particularly expert).

Extensions can do different things.

Can simply EXISTS without defining anything new. In this case they can relax limitations or add new values for parameters you are already using with familiar opengl commands.

They can also add new constants and/or new commands. Those can have different names (with a same base but different suffixes) depending if they are core commands for the current gl version, if they are extensions specific to a vendor, if they are generic extensions, if they are ARB approved. Usually an ARB approved extensions become core in the next GL version.

Extensions have a name, for example ARB_multitexture, and an extension string (the one you need to check to see if the extension is present) for example GL_ARB_multitexture.

The opengl example in the PB sources does not use extensions but it create the RC from scratch like the code you posted, so it doesn't rely on the gl subsystem by pb.
It's all very minimal in both, but it can work (windows only)

You can start here:

http://www.opengl.org/archives/resource ... xtensions/
http://www.opengl.org/registry/
http://www.nvidia.it/object/opengl_exte ... orial.html

also it can be very useful a program to enumerate the extensions available on your system

http://www.realtech-vr.com/glview/
http://www.ozone3d.net/gpu_caps_viewer/

Always check the documentation for the extension in the registry linked above before trying to import/use them.

For example to answer your question those commands are core in opengl 1.5, but also accessible in previous versions as extensions if the extension ARB_vertex_buffer_object is defined through the name GL_ARB_vertex_buffer_object or GLX_ARB_vertex_buffer_object.

see the registry http://www.opengl.org/registry/specs/AR ... object.txt

To anyone learning opengl my suggestion is: learn the mechanism and nothing more. Use the standard 1.1 gl language until you find by chance or reading the net an extension could positively help you. Then implement it in a nice include and grow your library of extensions in time. Don't try the import all in one batch approach. 99% of that stuff you don't need ATM and will give you only a headache.
When you need it, you add it. If you need only 5 extensions just import those 5.

All the above if you are ok with legacy opengl, if you want just to support modern hw/drivers and are interested only in gl > 3.3 then most of this does not really apply, and it's actually easier for this specific subject (you can basically forget the need to fallback).