Difference between revisions of "OpenGL/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 23: Line 23:
 
*[[Castle Game Engine]] - позволяет перемещаться и визуализировать трехмерные миры (в VRML, X3D и других трехмерных форматах).
 
*[[Castle Game Engine]] - позволяет перемещаться и визуализировать трехмерные миры (в VRML, X3D и других трехмерных форматах).
  
==Tutorial==
+
==Учебник==
* [[OpenGL Tutorial]]
+
* [[OpenGL_Tutorial/ru|OpenGL Tutorial]]
  
 
== Tutorial OpenGL 3.3 ( modern OpnGL )==
 
== Tutorial OpenGL 3.3 ( modern OpnGL )==

Revision as of 15:08, 29 March 2020

Deutsch (de) English (en) français (fr) 日本語 (ja) português (pt) русский (ru) Tiếng Việt (vi) 中文(中国大陆)‎ (zh_CN)

OpenGL (Open Graphics Library) - это кроссплатформенный API для создания трехмерной компьютерной графики. Большинство современных видеокарт обеспечивают аппаратную поддержку OpenGL, что делает OpenGL хорошим решением для написания передового графического программного обеспечения.

Модули OpenGL во Free Pascal

Интерфейс FreePascal OpenGL состоит из следующих модулей:

  • gl: Этот модуль содержит основные функции, такие как рисование полигонов, применение преобразований, установка цветов и материалов, ... Процедуры всегда начинаются с предлога "gl".
  • glu: Этот модульк содержит утилиты OpenGL. Хотя в нем есть некоторые полезные функции, этот модуль не является необходимым, поскольку вы можете реализовать все процедуры glu с функциональностью блока gl. Процедуры всегда начинаются с предлога "glu".
  • glext: Производители могут предоставлять дополнительные функциональные возможности через расширения. Используйте этот модуль для использования этих расширений.

    Функциональность, характерная для более новых версий OpenGL (1.2 и выше), также доступна в этом модуле. Инициализация этой функциональности аналогична инициализации обычных расширений OpenGL: просто вызовите функцию Load_GL_version_X_Y. Если версия вашей библиотеки OpenGL старее X.Y, Load_GL_version_X_Y вернет false.

  • glut: Этот модуль обеспечивает функциональность для создания окна OpenGL. Хотя это кроссплатформенный модуль, большинство операционных систем Windows по умолчанию не имеют glut DLL.
  • glx: glx предоставляет функциональность для настройки окна OpenGL в системе X Window. Процедуры всегда начинаются с предлога "glx". Очевидно, что вы не можете использовать это устройство в не-X Window системах, таких как Windows.

Модули OpenGL в Lazarus

Lazarus включает в себя TOpenGLControl - элемент управления LCL с контекстом OpenGL. Пакет Lazarus LazOpenGLContext находится в каталоге lazarus/components/opengl/lazopenglcontext.lpk. Пример можно найти в lazarus/examples/openglcontrol/openglcontrol_demo.lpi.

Если вы хотите изменить реализацию TOpenGLControl, например, чтобы добавить новые свойства, такие как ColorBits и AuxBuffers, см. Расширение TOpenGLControl.

Сторонние OpenGL модули

  • GLScene - пакет Lazarus с множеством дополнительных функций для приложений OpenGL.
  • Castle Game Engine - позволяет перемещаться и визуализировать трехмерные миры (в VRML, X3D и других трехмерных форматах).

Учебник

Tutorial OpenGL 3.3 ( modern OpnGL )

Q/A using OpenGL binding

Q: I don't understand why the ARB version does not work. AFAIK it has the same entry points as the core functionality and OpenGL versions are required to support the ARB version of functions even if the non ARB version is in the core now.

A: No. OpenGL doesn't have to support the extension entry points, even when it supports the same functionality in core already. Vendor is free to remove the extensions, and support only the "core" functions.

Also, sometimes when functionality is promoted from ARB extension into core it's slightly changed (although in 99% cases it stays the same). Example is the GLSL shaders, that expose (very slightly) different API through ARB extensions and through core 2.0 specification.

Basically, what is exposed through extensions is completely orthogonal to what is exposed through core functionality, so they should be initialized separately. In particular cases, you can make tricks like

if glIsBufferARB = nil then glIsBufferARB := @glIsBuffer;

but this should be left to the final programmer that knows that "ARB_vertex_buffer_object" behavior is identical to how it works in core.

Q: When I try to use the gluTessCallback function from the glu unit, either the compiler complains or I get a segmentation fault when I try to run my program. How can I get it to work properly?

A: The gluTessCallback function is defined in the following way in the glu unit:

{$IFDEF Windows}
  {$DEFINE extdecl := stdcall}
{$ELSE}
  {$DEFINE extdecl := cdecl}
{$ENDIF}

gluTessCallback: procedure(tess: PGLUtesselator; which: GLenum; fn: TCallBack); extdecl;

Windows note:A common problem is that the calling convention of the glu functions seems to vary in several different GLUT DLLs builds for windows. In some it is stdcall, in some cdecl. The most used one seems to be stdcall.

You should define your callback functions like so:

procedure MyTessBegin(which: GLEnum); 
{$IFDEF Windows} stdcall; {$else} cdecl; {$endif}
begin
  glBegin(which);
end;

procedure MyTessEnd; 
{$IFDEF Windows} stdcall; {$else} cdecl; {$endif}
begin
  glEnd();   // The () is required
end;

procedure MyTessVertex(data: Pointer);
{$IFDEF Windows} stdcall; {$else} cdecl; {$endif}
begin
  glVertex3dv(PGLDouble(data));
end;

Note the cdecl/stdcall modifiers; they are required. You then call gluTessCallback in the following manner:

gluTessCallback(tess, GLU_TESS_BEGIN, TCallBack(@MyTessBegin));
gluTessCallback(tess, GLU_TESS_END, TCallBack(@MyTessEnd));
gluTessCallback(tess, GLU_TESS_VERTEX, TCallBack(@MyTessVertex));

Make sure you cast the pointer to your callback function to the TCallBack type, as shown above.

Alternatively, if you want to refer to the OpenGL functions directly, use the following calling convention:

gluTessCallback(tess, GLU_TESS_BEGIN, TCallBack(glBegin));
gluTessCallback(tess, GLU_TESS_END, TCallBack(glEnd));
gluTessCallback(tess, GLU_TESS_VERTEX, TCallBack(glVertex3dv));

Finally, here is source code for a simple tessellation demo (uses glut).

Go back to Packages List