Sign in Join
Wiki copytemporary

OpenGL Tutorial/ja: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11# 概要
22
33OpenGLは2Dや3DのインタラクティブなグラフィックスアプリケーションをOSなどに依存せず作成できる、優れた開発環境です。OpenGLは1992年から開発がすすめられ、いまや2D、3DグラフィックスアプリケーションのAPIとしては、数多くのアプリケーションで使われ、いろんなコンピュータプラットホームで利用でき、業界標準になっています。
44
55OpenGLは、様々な種類のレンダリング、テクスチャマッピング、特殊効果、および他の強力なビジュアライゼーション機能を取り入れており、革新的な、アプリケーション開発を加速できます。
66
77開発者はすべてのポピュラーなデスクトップとワークステーションプラットホームに、OpenGLのパワーを利用することができますので、広いアプリケーション展開が可能になります。もっと詳しい情報は、 [OpenGLのサイト](http://www.opengl.org/about/overview/)で得ることができます。
88
99GLUTはOpenGL Utility Toolkitですの略です。OpenGLを使ったプログラムを書くために、どのようなウィンドウシステムで利用できるツールキットです。 これは、簡単なウインドウをもつOpenGLを使うプログラムで使える、アプリケーションプログラミングインターフェース(API)を実装します。(訳注:GLUTを使えば、ウインドウシステム、プラットフォームの違いを吸収してくれます。) GLUTを使えば、OpenGLプログラミングを学んだり、調査すしたりすることが簡単になります。 また、いろいろなPCとワークステーション、OSにわたって動作するひとつのOpenGLプログラムに書けるのと同様に、GLUTは携帯用のAPIも提供しています。もっと詳しい情報は、 [OpenGLのGLUTのサイト](http://www.opengl.org/resources/libraries/glut/)で得ることができます。
1010
1111多くのOSにGLUTがプレインストールされています。もし、自分の環境にあったものが分からない場合は、 [Google](http://www.google.com/)で調べてみてください。
1212
1313Windowsのバイナリは、[www.xmission.com](http://www.xmission.com/~nate/glut.html)でダウンロードできます。
1414
1515# 最初のGLUTプログラムを作ろう
1616
1717GLUTを使うために、初期化処理をおこなう必要があります。これは、glutInit関数を使って行えます。 この関数はコマンドラインを解析し、メインウインドウのパラメータをセットします。しかし、それは、C/C++形式の入力を前提としています。 あなたは、自分の関数内で、ParamCountとParamStrから、C/C++風のコマンドラインパラメータに変換する必要があります。
1818
19-`procedure glutInitPascal(ParseCmdLine: Boolean); `\
20-`var`\
21-`  Cmd: array of PChar;`\
22-`  CmdCount, I: Integer;`\
23-`begin`\
24-`  if ParseCmdLine then`\
25-`    CmdCount := ParamCount + 1`\
26-`  else`\
27-`    CmdCount := 1;`\
28-`  SetLength(Cmd, CmdCount);`\
29-`  for I := 0 to CmdCount - 1 do`\
30-`    Cmd[I] := PChar(ParamStr(I));`\
31-`  glutInit(@CmdCount, @Cmd);`\
32-`end;`
19+``` pascal
20+procedure glutInitPascal(ParseCmdLine: Boolean);
21+var
22+ Cmd: array of PChar;
23+ CmdCount, I: Integer;
24+begin
25+ if ParseCmdLine then
26+ CmdCount := ParamCount + 1
27+ else
28+ CmdCount := 1;
29+ SetLength(Cmd, CmdCount);
30+ for I := 0 to CmdCount - 1 do
31+ Cmd[I] := PChar(ParamStr(I));
32+ glutInit(@CmdCount, @Cmd);
33+end;
34+```
3335
3436要するに、配列を作って、ParamStrからの文字列をセットしています。この関数は、glutInitに渡して、制御するためのパラメータを取ることができます。コマンドライン、もしくは、実行ファイルそのものの名です。
3537
3638glutInitについての情報は: <http://www.opengl.org/resources/libraries/glut/spec3/node10.html>
3739
3840次に、メインウインドウを生成する必要があります。 メインウインドウに、glutInitDisplayModeを使って、ディスプレイモードを設定します。 これは、フラグの組み合わせで表現されるただ1つのパラメータを取ります。 通常は、GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH で充分でしょう。
3941
4042glutInitDisplayModeについての情報は: <http://www.opengl.org/resources/libraries/glut/spec3/node12.html>
4143
4244The position and size of the window is controlled using ウインドウの位置とサイズは、 glutInitWindowPosition と、 glutInitWindowSize.によって制御されます。 これらは、2個のパラメータをとります。 最初のものはX and Y の組、後のものは、幅と高さです。ウインドウのサイズと中心を得るために、glutGetを使うこともできます。
4345
4446glutInitWindowPosition, glutInitWindowSize と glutGetについての情報は: <http://www.opengl.org/resources/libraries/glut/spec3/node11.html> <http://www.opengl.org/documentation/specs/glut/spec3/node70.html>
4547
4648最後に、glutCreateWindow 関数を使って、ウインドウを生成します。 これは、ウインドウを生成し、パラメータを通してキャプションを設定します。
4749
4850結果として、この関数はウインドウのハンドルを返します。これは、他の関数で必要とされて使われる事があります。
4951
5052glutCreateWindowについての情報は: <http://www.opengl.org/resources/libraries/glut/spec3/node16.html>
5153
5254プログラムがメインループにはいる前に、いくつかコールバックを設定しておきます。ウインドウを描画するとき、リサイズするとき、キーボード入力があったとき、などに、コールバックを必要とします。これらのコールバックは、glutDisplayFunc、 glutReshapeFunc 、 glutKeyboardFuncを使って設定します。
5355
5456コールバックについての情報は: <http://www.opengl.org/resources/libraries/glut/spec3/node45.html#SECTION00080000000000000000>
5557
5658描画関数は、このようになるでしょう。
5759
58-`procedure DrawGLScene; cdecl;`\
59-`begin`\
60-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
61-`  glutSwapBuffers;`\
62-`end;`
60+``` pascal
61+procedure DrawGLScene; cdecl;
62+begin
63+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
64+ glutSwapBuffers;
65+end;
66+```
6367
6468これは、単にウインドウをバックグラウンド色でクリアして、Zバッファをリセットします。(Zバッファについては、後で説明するので分からなくても気にしないでください。)
6569
6670リサイズ関数は、次のようになるでしょう。
6771
68-`procedure ReSizeGLScene(Width, Height: Integer); cdecl;`\
69-`begin`\
70-`  if Height = 0 then`\
71-`    Height := 1;`\
72+``` pascal
73+procedure ReSizeGLScene(Width, Height: Integer); cdecl;
74+begin
75+ if Height = 0 then
76+ Height := 1;
7277
73-`  glViewport(0, 0, Width, Height);`\
74-`  glMatrixMode(GL_PROJECTION);`\
75-`  glLoadIdentity;`\
76-`  gluPerspective(45, Width / Height, 0.1, 1000);`\
78+ glViewport(0, 0, Width, Height);
79+ glMatrixMode(GL_PROJECTION);
80+ glLoadIdentity;
81+ gluPerspective(45, Width / Height, 0.1, 1000);
7782
78-`  glMatrixMode(GL_MODELVIEW);`\
79-`  glLoadIdentity;`\
80-`end;`
83+ glMatrixMode(GL_MODELVIEW);
84+ glLoadIdentity;
85+end;
86+```
8187
8288このコードで、OpenGLにウインドウのどの部分に描画し、必要な値を適切な行列に設定することができます。 (行列関数は、後で説明します。)
8389
8490キーボード入力は、次の関数で評価されます。
8591
86-`procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;`\
87-`begin`\
88-`  if Key = 27 then`\
89-`    Halt(0);`\
90-`end;`
92+``` pascal
93+procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;
94+begin
95+ if Key = 27 then
96+ Halt(0);
97+end;
98+```
9199
92100この関数はESCキーを押すとプログラムを終了するようにします。GLUTはイベントドリブンであり、プログラムを終了するためには、コールバック関数の中でHalt関数をコールします。
93101
94102もし、別の方法でウインドウをクローズすると、ウインドウは消えても、プログラムは見えないところでループを続けているでしょう。
95103
96104メインループを開始するには、glutMainLoopをコールします。 これは、終了しないループに突入し、コールバック関数をコールしていきます。 プログラムの主要部分は次のようになるでしょう。
97105
98-`const `\
99-`  AppWidth = 640; `\
100-`  AppHeight = 480; `\
106+``` pascal
107+const
108+ AppWidth = 640;
109+ AppHeight = 480;
101110
102-`procedure InitializeGL; `\
103-`begin `\
104-`  glClearColor(0.18, 0.20, 0.66, 0); `\
105-`end; `\
111+procedure InitializeGL;
112+begin
113+ glClearColor(0.18, 0.20, 0.66, 0);
114+end;
106115
107-`var `\
108-`  ScreenWidth, ScreenHeight: Integer; `\
109-`begin `\
110-`  glutInitPascal(True); `\
111-`  glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH); `\
112-`  glutInitWindowSize(AppWidth, AppHeight); `\
113-`  ScreenWidth := glutGet(GLUT_SCREEN_WIDTH); `\
114-`  ScreenHeight := glutGet(GLUT_SCREEN_HEIGHT); `\
115-`  glutInitWindowPosition((ScreenWidth - AppWidth) div 2,`\
116-`    (ScreenHeight - AppHeight) div 2); `\
117-`  glutCreateWindow('OpenGL Tutorial 1'); `\
116+var
117+ ScreenWidth, ScreenHeight: Integer;
118+begin
119+ glutInitPascal(True);
120+ glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH);
121+ glutInitWindowSize(AppWidth, AppHeight);
122+ ScreenWidth := glutGet(GLUT_SCREEN_WIDTH);
123+ ScreenHeight := glutGet(GLUT_SCREEN_HEIGHT);
124+ glutInitWindowPosition((ScreenWidth - AppWidth) div 2,
125+ (ScreenHeight - AppHeight) div 2);
126+ glutCreateWindow('OpenGL Tutorial 1');
118127
119-`  InitializeGL; `\
128+ InitializeGL;
120129
121-`  glutDisplayFunc(@DrawGLScene); `\
122-`  glutReshapeFunc(@ReSizeGLScene); `\
123-`  glutKeyboardFunc(@GLKeyboard); `\
130+ glutDisplayFunc(@DrawGLScene);
131+ glutReshapeFunc(@ReSizeGLScene);
132+ glutKeyboardFunc(@GLKeyboard);
124133
125-`  glutMainLoop; `\
126-`end.`
134+ glutMainLoop;
135+end.
136+```
127137
128138次のチュートリアルでは、少しコードを追加して、簡単な図形を書いてみます。
129139
130140下記でソースコードやlinux/Windowsの実行ファイルをダウンロードできます。 [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
131141
132142# 単純な形状を描画する
133143
134144今回は、少しだけコードを追加して、OpenGLの関数の説明にフォーカスします。
135145
136146これまでのコードで説明します。
137147
138-`  .`\
139-`  .`\
140-`  .`\
141-`  glMatrixMode(GL_PROJECTION);`\
142-`  glLoadIdentity;`\
143-`  gluPerspective(45, Width / Height, 0.1, 1000);`\
148+``` pascal
149+ .
150+ .
151+ .
152+ glMatrixMode(GL_PROJECTION);
153+ glLoadIdentity;
154+ gluPerspective(45, Width / Height, 0.1, 1000);
144155
145-`  glMatrixMode(GL_MODELVIEW);`\
146-`  glLoadIdentity;`\
147-`end;`
156+ glMatrixMode(GL_MODELVIEW);
157+ glLoadIdentity;
158+end;
159+```
148160
149161glMatrixMode関数で、変更したい行列を選択します。 OpenGL には、3つの行列があります。
150162
151163GL_MODELVIEW: この行列は、頂点をモデル空間へ移動するためのものです。
152164
153165GL_PROJECTION: この行列は、3次元の位置を2次元の最終的に表示するピクセル位置に変換するためのものです。
154166
155167GL_TEXTURE: この行列はテクスチャ座標を変換するためのものです。
156168
157169いったん、変更したい行列を選択したら、行列値に影響を与える関数をコールします。
158170
159171glLoadIdentity は、行列をリセットするので、頂点位置に影響をあたえなくなります。 ほとんどすべての行列関数は、現在の行列に、生成した一つの行列を掛けるので、時々この関数で行列をクリアする必要があるでしょう。 (訳注:glLoadIdentityは、変換行列を単位行列にする。reset(リセット)や、clear(クリアする)、というと、プログラミング的な表現では、ゼロ行列をおもいうかべそうだが、原文作者の数学的な観念の表現であると考えて、そのまま和訳した)
160172
161173視野行列を設定したいなら、 gluPerspective を使うことができます。4つのパラメータ(アスペクト比、視野の近い側の面、遠い側の面)、が視野をあらわします。これは、シンプルです。
162174
163175(訳注:OpenGLの観念としては、視野は、体積としてとらえるので、視野体積として空間を捉えるとよいだろう。) それで、モデル行列を変更できます。この時点で、固有のものをセットすればよいでしょう。 よろしいでしょうか。それでは、最初の形状を書いてみましょう。
164176
165-`procedure DrawGLScene; cdecl;`\
166-`begin`\
167-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
177+``` pascal
178+procedure DrawGLScene; cdecl;
179+begin
180+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
168181
169-`  glLoadIdentity;`\
170-`  glTranslatef(0, 0, -5);`\
182+ glLoadIdentity;
183+ glTranslatef(0, 0, -5);
171184
172-`  glBegin(GL_TRIANGLES);`\
173-`    glColor3f(1, 0, 0);`\
174-`    glVertex3f(-1, -1, 0);`\
185+ glBegin(GL_TRIANGLES);
186+ glColor3f(1, 0, 0);
187+ glVertex3f(-1, -1, 0);
175188
176-`    glColor3f(0, 1, 0);`\
177-`    glVertex3f(1, -1, 0);`\
189+ glColor3f(0, 1, 0);
190+ glVertex3f(1, -1, 0);
178191
179-`    glColor3f(0, 0, 1);`\
180-`    glVertex3f(0, 1, 0);`\
181-`  glEnd;`\
192+ glColor3f(0, 0, 1);
193+ glVertex3f(0, 1, 0);
194+ glEnd;
182195
183-`  glutSwapBuffers;`\
184-`end;`
196+ glutSwapBuffers;
197+end;
198+```
185199
186200すでに、glClear関数は使いましたが、これは、バッファをリセットします。 次の2個の関数はスキップして、描画関数に注目します。
187201
188202glBegin marks beginning of drawing block. After this function you can start entering vertices. Parameter describes how are vertices used when drawing: GL_POINTS: Treats each vertex as a single point. Vertex n defines point n. N points are drawn.
189203
190204GL_LINES: Treats each pair of vertices as an independent line segment. Vertices 2n-1 and 2n define line n. n/2 lines are drawn.
191205
192206GL_LINE_STRIP: Draws a connected group of line segments from the first vertex to the last. n-1 lines are drawn.
193207
194208GL_LINE_LOOP: Draws a connected group of line segments from the first vertex to the last, then back to the first. Vertices n and n+1 define line n. The last line, however, is defined by vertices n and 1. n lines are drawn.
195209
196210GL_TRIANGLES: Treats each triplet of vertices as an independent triangle. Vertices 3n-2, 3n-1 and 3n define triangle n. n/3 triangles are drawn.
197211
198212GL_TRIANGLE_STRIP: Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices. For odd n, vertices n, n+1 and n+2 define triangle n. For even n, vertices n+1, n and n+2 define triangle n. n-2 triangles are drawn.
199213
200214GL_TRIANGLE_FAN: Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices. Vertices 1. n+1 and n+2 define triangle n. n-2 triangles are drawn.
201215
202216GL_QUADS: Treats each group of four vertices as an independent quadrilateral. Vertices 4n-3, 4n-2, 4n-1 and 4n define quadrilateral n. n/4 quadrilaterals are drawn.
203217
204218GL_QUAD_STRIP: Draws a connected group of quadrilaterals. One quadrilateral is defined for each pair of vertices presented after the first pair. Vertices 2n-1, 2n, 2n+2 and 2n+1 define quadrilateral n. n/2-1 quadrilaterals are drawn. Note that the order in which vertices are used to construct a quadrilateral from strip data is different from that used with independent data.
205219
206220GL_POLYGON: Draws a single, convex polygon. Vertices 1 through n define this polygon.
207221
208222![](/wiki-images/f/f3/SimpleShapePic1.jpg) You'll draw single triangle and for that GL_TRIANGLES flag will do the trick. glVertex3f function defines the position of a vertex you want to draw. There are more glVertex* functions. Only difference is number and type of parameters they take. For instance... glVertex2i takes two parameters (x and y) of integer type. glVertex3f will almost always be just what you need.
209223
210224Before glVertex you can set color, material, texture... For simplicity you'll just specify color for each vertex in this tutorial. Color is set using glColor3f function. glColor can also take different set of parameters like glVertex.
211225
212226As we look through code we can see that Z is set to 0 for all vertices. Since you set near plane to 0.1, triangle will not be visible. That is where those two functions we skipped in the beginning jump in. We already know that glLoadIdentity reset matrix. glTranslatef moves triangles by X, Y and Z values you provide. Since you set Z to -5 (negative Z is farther from camera) all vertices will be drawn 5 units far from point of view and will be visible.
213227
214228In the end you call glEnd functions that finishes drawing. You could now start another drawing block with new glBegin function if you wish.
215229
216230Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
217231
218232# Using display lists
219233
220234Sometimes you'll need to draw some object multiple times on scene. OpenGL has ability to build display lists which make drawing a bit faster. Creating display list is very easy... just draw vertices as you did in previous tutorial and enclose them with glNewList and glEndList calls.
221235
222-`const`\
223-`  LIST_OBJECT = 1;`\
236+``` pascal
237+const
238+ LIST_OBJECT = 1;
224239
225-`procedure CreateList;`\
226-`begin`\
227-`  glNewList(LIST_OBJECT, GL_COMPILE);`\
228-`    glBegin(GL_TRIANGLE_FAN);`\
229-`      glColor3f(1, 0, 0);`\
230-`      glVertex3f(0, 0.5, 0);`\
240+procedure CreateList;
241+begin
242+ glNewList(LIST_OBJECT, GL_COMPILE);
243+ glBegin(GL_TRIANGLE_FAN);
244+ glColor3f(1, 0, 0);
245+ glVertex3f(0, 0.5, 0);
231246
232-`      glColor3f(1, 1, 0);`\
233-`      glVertex3f(-0.5, -0.5, 0.5);`\
247+ glColor3f(1, 1, 0);
248+ glVertex3f(-0.5, -0.5, 0.5);
234249
235-`      glColor3f(1, 1, 1);`\
236-`      glVertex3f(0.5, -0.5, 0.5);`\
250+ glColor3f(1, 1, 1);
251+ glVertex3f(0.5, -0.5, 0.5);
237252
238-`      glColor3f(0, 1, 1);`\
239-`      glVertex3f(0.5, -0.5, -0.5);`\
253+ glColor3f(0, 1, 1);
254+ glVertex3f(0.5, -0.5, -0.5);
240255
241-`      glColor3f(0, 0, 1);`\
242-`      glVertex3f(-0.5, -0.5, -0.5);`\
256+ glColor3f(0, 0, 1);
257+ glVertex3f(-0.5, -0.5, -0.5);
243258
244-`      glColor3f(0, 1, 0);`\
245-`      glVertex3f(-0.5, -0.5, 0.5);`\
246-`    glEnd;`\
259+ glColor3f(0, 1, 0);
260+ glVertex3f(-0.5, -0.5, 0.5);
261+ glEnd;
247262
248-`    glBegin(GL_QUADS);`\
249-`      glColor3f(1, 1, 0);`\
250-`      glVertex3f(-0.5, -0.5, 0.5);`\
263+ glBegin(GL_QUADS);
264+ glColor3f(1, 1, 0);
265+ glVertex3f(-0.5, -0.5, 0.5);
251266
252-`      glColor3f(1, 1, 1);`\
253-`      glVertex3f(0.5, -0.5, 0.5);`\
267+ glColor3f(1, 1, 1);
268+ glVertex3f(0.5, -0.5, 0.5);
254269
255-`      glColor3f(0, 1, 1);`\
256-`      glVertex3f(0.5, -0.5, -0.5);`\
270+ glColor3f(0, 1, 1);
271+ glVertex3f(0.5, -0.5, -0.5);
257272
258-`      glColor3f(0, 0, 1);`\
259-`      glVertex3f(-0.5, -0.5, -0.5);`\
273+ glColor3f(0, 0, 1);
274+ glVertex3f(-0.5, -0.5, -0.5);
260275
261-`      glColor3f(0, 1, 0);`\
262-`      glVertex3f(-0.5, -0.5, 0.5);`\
263-`    glEnd;`\
264-`  glEndList;`\
265-`end;`
276+ glColor3f(0, 1, 0);
277+ glVertex3f(-0.5, -0.5, 0.5);
278+ glEnd;
279+ glEndList;
280+end;
281+```
266282
267283glNewList creates new display list and all drawing functions will be recorded until glEndList is called. The first parameter for glNewList function is list ID. Every list is defined by it's ID. If list with given ID is already created it fill be cleared before recording. If the second parameter is GL_COMPILE then all drawing functions are just recorded, but if it is GL_COMPILE_AND_EXECUTE then they are recorded and executed automaticly.
268284
269285glIsList function can help you with display lists. It can tell if some list ID is already filled with data. Another useful function is glGenLists. It will create multiple empty display lists. You pass number of display lists you need and you get ID of the first one. If you require n lists, and get r ID, generated display lists are: r, r+1, r+2,..., r+n-1
270286
271287All created lists should be deleted. You will do that before program exits:
272288
273-`procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;`\
274-`begin`\
275-`  if Key = 27 then`\
276-`  begin`\
277-`    glDeleteLists(LIST_OBJECT, 1);`\
278-`    Halt(0);`\
279-`  end;`\
280-`end;`
289+``` pascal
290+procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;
291+begin
292+ if Key = 27 then
293+ begin
294+ glDeleteLists(LIST_OBJECT, 1);
295+ Halt(0);
296+ end;
297+end;
298+```
281299
282300glDeleteLists takes 2 parameters, ID of display list and number of lists to delete. If ID is r, and number of lists to delete is n, deleted lists are: r, r+1, r+2,..., r+n-1
283301
284302Now you know how to create and delete display lists... let's see how to draw them:
285303
286-`procedure DrawGLScene; cdecl;`\
287-`begin`\
288-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
304+``` pascal
305+procedure DrawGLScene; cdecl;
306+begin
307+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
289308
290-`  glLoadIdentity;`\
291-`  glTranslatef(-2, 0, -5);`\
292-`  glRotatef(40, 1, 0, 1);`\
293-`  glCallList(LIST_OBJECT);`\
309+ glLoadIdentity;
310+ glTranslatef(-2, 0, -5);
311+ glRotatef(40, 1, 0, 1);
312+ glCallList(LIST_OBJECT);
294313
295-`  glLoadIdentity;`\
296-`  glTranslatef(1, -2, -10);`\
297-`  glRotatef(62, 0, 1, 0);`\
298-`  glCallList(LIST_OBJECT);`\
314+ glLoadIdentity;
315+ glTranslatef(1, -2, -10);
316+ glRotatef(62, 0, 1, 0);
317+ glCallList(LIST_OBJECT);
299318
300-`  glLoadIdentity;`\
301-`  glTranslatef(-4, 0.5, -15);`\
302-`  glRotatef(200, 1, 0, 0);`\
303-`  glCallList(LIST_OBJECT);`\
319+ glLoadIdentity;
320+ glTranslatef(-4, 0.5, -15);
321+ glRotatef(200, 1, 0, 0);
322+ glCallList(LIST_OBJECT);
304323
305-`  glutSwapBuffers;`\
306-`end;`
324+ glutSwapBuffers;
325+end;
326+```
307327
308328![](/wiki-images/a/a5/DisplayListsPic1.jpg) Using glCallList you can draw only one display list. In this tutorial, before drawing display list, you change model matrix and draw object in different places. Some times you would like to draw multiple lists at once. That is possible using glCallLists function. It takes number of lists you want to draw, type of array that contains display list IDs and array with display list IDs. Type of list can be one of the following:
309329
310330GL_BYTE: list is treated as an array of signed bytes, each in the range -128 through 127.
311331
312332GL_UNSIGNED_BYTE: list is treated as an array of unsigned bytes, each in the range 0 through 255.
313333
314334GL_SHORT: list is treated as an array of signed two-byte integers, each in the range -32768 through 32767.
315335
316336GL_UNSIGNED_SHORT: list is treated as an array of unsigned two-byte integers, each in the range 0 through 65535.
317337
318338GL_INT: lists is treated as an array of signed four-byte integers.
319339
320340GL_UNSIGNED_INT: list is treated as an array of unsigned four-byte integers.
321341
322342GL_FLOAT: list is treated as an array of four-byte floating-point values.
323343
324344GL_2_BYTES: list is treated as an array of unsigned bytes. Each pair of bytes specifies a single display list ID. The value of the pair is computed as 256 times the unsigned value of the first byte plus the unsigned value of the second byte.
325345
326346GL_3_BYTES: list is treated as an array of unsigned bytes. Each triplet of bytes specifies a single display list ID. The value of the triplet is computed as 65536 times the unsigned value of the first byte, plus 256 times the unsigned value of the second byte, plus the unsigned value of the third byte.
327347
328348GL_4_BYTES: list is treated as an array of unsigned bytes. Each quadruplet of bytes specifies a single display list ID. The value of the quadruplet is computed as 16777216 times the unsigned value of the first byte, plus 65536 times the unsigned value of the second byte, plus 256 times the unsigned value of the third byte, plus the unsigned value of the fourth byte.
329349
330350That is for now. Next tutorial will show how to create little planetary system. We'll talk about matrices and how to make animated scene that doesn't depend of number of frames per second.
331351
332352Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
333353
334354# Full screen animation
335355
336356Entering full screen mode is easy with GLUT. Let's change main part of the program:
337357
338-`const`\
339-`  FSMode = '800x600:32@75';`\
358+``` pascal
359+const
360+ FSMode = '800x600:32@75';
340361
341-`begin`\
342-`  glutInitPascal(False);`\
343-`  glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH);`\
344-`  glutGameModeString(FSMode);`\
345-`  glutEnterGameMode;`\
346-`  glutSetCursor(GLUT_CURSOR_NONE);`\
362+begin
363+ glutInitPascal(False);
364+ glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH);
365+ glutGameModeString(FSMode);
366+ glutEnterGameMode;
367+ glutSetCursor(GLUT_CURSOR_NONE);
347368
348-`  InitializeGL;`\
369+ InitializeGL;
349370
350-`  glutDisplayFunc(@DrawGLScene);`\
351-`  glutReshapeFunc(@ReSizeGLScene);`\
352-`  glutKeyboardFunc(@GLKeyboard);`\
353-`  glutIdleFunc(@DrawGLScene);`\
371+ glutDisplayFunc(@DrawGLScene);
372+ glutReshapeFunc(@ReSizeGLScene);
373+ glutKeyboardFunc(@GLKeyboard);
374+ glutIdleFunc(@DrawGLScene);
354375
355-`  glutMainLoop;`\
356-`end.`
376+ glutMainLoop;
377+end.
378+```
357379
358380Since we don't want GLUT to parse command line this time we call glutInitPascal with False parameter. As you can see, there is no code for window creation. GLUT have glutEnterGameMode that create full screen window. To specify what kind of full screen mode you want, you call glutGameModeString function which takes string that defines mode you like. Format of that string is:
359381
360-`[width "x" height][":" bpp]["@" hertz]`
382+```text
383+[width "x" height][":" bpp]["@" hertz]
384+```
361385
362386In FSMode string we declared that full screen mode should be 800x600, with 32bit pallete and 75Hz refresh. It is possible to skip one of the group. If you omit size, GLUT will try to use current one or first smaller that can work. That policy is used and for other parameters.
363387
364388Usually in full screen mode cursor is not visible. To hide cursor you use glutSetCursor function. It takes only one parameter which describes cursor you would like to see:
365389
366-`GLUT_CURSOR_RIGHT_ARROW`\
367-`GLUT_CURSOR_LEFT_ARROW`\
368-`GLUT_CURSOR_INFO`\
369-`GLUT_CURSOR_DESTROY`\
370-`GLUT_CURSOR_HELP`\
371-`GLUT_CURSOR_CYCLE`\
372-`GLUT_CURSOR_SPRAY`\
373-`GLUT_CURSOR_WAIT`\
374-`GLUT_CURSOR_TEXT`\
375-`GLUT_CURSOR_CROSSHAIR`\
376-`GLUT_CURSOR_UP_DOWN`\
377-`GLUT_CURSOR_LEFT_RIGHT`\
378-`GLUT_CURSOR_TOP_SIDE`\
379-`GLUT_CURSOR_BOTTOM_SIDE`\
380-`GLUT_CURSOR_LEFT_SIDE`\
381-`GLUT_CURSOR_RIGHT_SIDE`\
382-`GLUT_CURSOR_TOP_LEFT_CORNER`\
383-`GLUT_CURSOR_TOP_RIGHT_CORNER`\
384-`GLUT_CURSOR_BOTTOM_RIGHT_CORNER`\
385-`GLUT_CURSOR_BOTTOM_LEFT_CORNER`\
386-`GLUT_CURSOR_FULL_CROSSHAIR`\
387-`GLUT_CURSOR_NONE`\
388-`GLUT_CURSOR_INHERIT`
390+```text
391+GLUT_CURSOR_RIGHT_ARROW
392+GLUT_CURSOR_LEFT_ARROW
393+GLUT_CURSOR_INFO
394+GLUT_CURSOR_DESTROY
395+GLUT_CURSOR_HELP
396+GLUT_CURSOR_CYCLE
397+GLUT_CURSOR_SPRAY
398+GLUT_CURSOR_WAIT
399+GLUT_CURSOR_TEXT
400+GLUT_CURSOR_CROSSHAIR
401+GLUT_CURSOR_UP_DOWN
402+GLUT_CURSOR_LEFT_RIGHT
403+GLUT_CURSOR_TOP_SIDE
404+GLUT_CURSOR_BOTTOM_SIDE
405+GLUT_CURSOR_LEFT_SIDE
406+GLUT_CURSOR_RIGHT_SIDE
407+GLUT_CURSOR_TOP_LEFT_CORNER
408+GLUT_CURSOR_TOP_RIGHT_CORNER
409+GLUT_CURSOR_BOTTOM_RIGHT_CORNER
410+GLUT_CURSOR_BOTTOM_LEFT_CORNER
411+GLUT_CURSOR_FULL_CROSSHAIR
412+GLUT_CURSOR_NONE
413+GLUT_CURSOR_INHERIT
414+```
389415
390416glutIdleFunc defines callback function that you want to be called every time you program has no messages to process. Since we just want to render new frame if there is nothing to do, just set idle function to DrawGLScene. Some other tutorials show that idle function should send refresh message insted of drawing, but that way I have 50-100 frames less than using method I described.
391417
392418Now, let's look at the program termination where you need to exit full screen mode:
393419
394-`procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;`\
395-`begin`\
396-`  if Key = 27 then`\
397-`  begin`\
398-`    glutLeaveGameMode;`\
399-`    Halt(0);`\
400-`  end;`\
401-`end;`
420+``` pascal
421+procedure GLKeyboard(Key: Byte; X, Y: Longint); cdecl;
422+begin
423+ if Key = 27 then
424+ begin
425+ glutLeaveGameMode;
426+ Halt(0);
427+ end;
428+end;
429+```
402430
403431As you can see, all you need to do is to call glutLeaveGameMode.
404432
405433Now, we'll introduce some new matrix functions. First, let's change ReSizeGLScene function:
406434
407-`procedure ReSizeGLScene(Width, Height: Integer); cdecl;`\
408-`begin`\
409-`  .`\
410-`  .`\
411-`  .`
435+``` pascal
436+procedure ReSizeGLScene(Width, Height: Integer); cdecl;
437+begin
438+ .
439+ .
440+ .
441+```
412442
413-`  glMatrixMode(GL_MODELVIEW);`\
414-`  glLoadIdentity;`\
415-`  gluLookAt(0, 20, 25, 0, 0, 0, 0, 1, 0);`\
416-`end;`
443+``` pascal
444+ glMatrixMode(GL_MODELVIEW);
445+ glLoadIdentity;
446+ gluLookAt(0, 20, 25, 0, 0, 0, 0, 1, 0);
447+end;
448+```
417449
418450gluLookAt create matrix that will define from where are you look to objects. First 3 parameters are X, Y and Z coordinate of position of camera. Next 3 parameters are X, Y and Z coordinate of point where camera look at, and last 3 parameters defines "up" vector (where is "up" for the camera). Usually, up is positive y axis.
419451
420452OK, let's draw now. Since you set matrix with gluLookAt that should be used with all objects, you can't just use glLoadIdentity to reset matrix for next object... you'll save previous matrix state and restore it after object is drawn:
421453
422-`procedure DrawGLScene; cdecl;`\
423-`var`\
424-`  T: Single;`\
425-`begin`\
426-`  T := glutGet(GLUT_ELAPSED_TIME) / 1000;`\
427-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
454+``` pascal
455+procedure DrawGLScene; cdecl;
456+var
457+ T: Single;
458+begin
459+ T := glutGet(GLUT_ELAPSED_TIME) / 1000;
460+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
428461
429-`  glPushMatrix;`\
430-`    glRotatef(5 * T, 0, 1, 0);`\
431-`    glColor3f(1, 1, 0);`\
432-`    glutWireSphere(2, 20, 20);`\
433-`  glPopMatrix;`\
462+ glPushMatrix;
463+ glRotatef(5 * T, 0, 1, 0);
464+ glColor3f(1, 1, 0);
465+ glutWireSphere(2, 20, 20);
466+ glPopMatrix;
434467
435-`  glPushMatrix;`\
436-`    glRotatef(90 * T, 0, 1, 0);`\
437-`    glTranslatef(5, 0, 0);`\
438-`    glRotatef(40 * T, 0, 1, 0);`\
439-`    glColor3f(1, 0, 0);`\
440-`    glutWireSphere(0.6, 10, 10);`\
441-`  glPopMatrix;`\
468+ glPushMatrix;
469+ glRotatef(90 * T, 0, 1, 0);
470+ glTranslatef(5, 0, 0);
471+ glRotatef(40 * T, 0, 1, 0);
472+ glColor3f(1, 0, 0);
473+ glutWireSphere(0.6, 10, 10);
474+ glPopMatrix;
442475
443-`  glPushMatrix;`\
444-`    glRotatef(60 * T, 0, 1, 0);`\
445-`    glTranslatef(-3, 0, 9);`\
446-`    glRotatef(50 * T, 0, 1, 0);`\
447-`    glColor3f(0, 1, 0);`\
448-`    glutWireSphere(1, 16, 16);`\
476+ glPushMatrix;
477+ glRotatef(60 * T, 0, 1, 0);
478+ glTranslatef(-3, 0, 9);
479+ glRotatef(50 * T, 0, 1, 0);
480+ glColor3f(0, 1, 0);
481+ glutWireSphere(1, 16, 16);
449482
450-`    glPushMatrix;`\
451-`      glRotatef(360 * T, 0, 1, 0);`\
452-`      glTranslatef(-1.7, 0, 0);`\
453-`      glRotatef(50 * T, 0, 1, 0);`\
454-`      glColor3f(0, 0, 1);`\
455-`      glutWireSphere(0.4, 10, 10);`\
456-`    glPopMatrix;`\
483+ glPushMatrix;
484+ glRotatef(360 * T, 0, 1, 0);
485+ glTranslatef(-1.7, 0, 0);
486+ glRotatef(50 * T, 0, 1, 0);
487+ glColor3f(0, 0, 1);
488+ glutWireSphere(0.4, 10, 10);
489+ glPopMatrix;
457490
458-`  glPopMatrix;`\
491+ glPopMatrix;
459492
460-`  glutSwapBuffers;`\
461-`end;`
493+ glutSwapBuffers;
494+end;
495+```
462496
463497![](/wiki-images/5/51/FullScreenAnimationPic1.jpg) glPushMatrix i glPopMatrix are used to save and restore matrix state. As you can see, we save matrix state, then change matrix in order to draw object in right place, and then restore old matrix state.
464498
465499You may wonder what is T variable for. Well, it is used to determen animation speed. Every change that depends on time is multiplied with T. That way animation speed is constant on every frame rate. glutGet function with GLUT_ELAPSED_TIME parameter returns time in milliseconds from glutInit is called. By dividing that value with 1000, we get time in seconds.
466500
467501glRotatef function create rotation matrix. First parameter is angle in degrees, and last 3 parameters defines axis around which rotation will be done. Since you multiplied angle with T, object will be rotated by that angle in exactly 1 second.
468502
469503Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
470504
471505# Light
472506
473507This tutorial will introduce some light to the scene. You'll make rotating cube and one light which will add some realism to the scene, but first let's make some utility unit.
474508
475509For now it will have only basic functions to help us getting current and delta (time that elapsed from one render to other render call) times and for calculating frames per second.
476510
477-`unit utils;`\
511+``` pascal
512+unit utils;
478513
479-`{$mode objfpc}{$H+}`\
514+{$mode objfpc}{$H+}
480515
481-`interface`\
516+interface
482517
483-`uses`\
484-`  glut;`\
518+uses
519+ glut;
485520
486-`function GetTotalTime: Single;`\
487-`function GetDeltaTime: Single;`\
488-`procedure FrameRendered(Count: Integer = 1);`\
489-`function GetFPS: Single;`\
521+function GetTotalTime: Single;
522+function GetDeltaTime: Single;
523+procedure FrameRendered(Count: Integer = 1);
524+function GetFPS: Single;
490525
491-`implementation`\
526+implementation
492527
493-`var`\
494-`  OldTime: Integer = 0;`\
495-`  FPSTime: Integer = 0;`\
496-`  FPSCount: Integer = 0;`\
528+var
529+ OldTime: Integer = 0;
530+ FPSTime: Integer = 0;
531+ FPSCount: Integer = 0;
497532
498-`function GetTotalTime: Single;`\
499-`begin`\
500-`  Result := glutGet(GLUT_ELAPSED_TIME) / 1000;`\
501-`end;`\
533+function GetTotalTime: Single;
534+begin
535+ Result := glutGet(GLUT_ELAPSED_TIME) / 1000;
536+end;
502537
503-`function GetDeltaTime: Single;`\
504-`var`\
505-`  NewTime: Integer;`\
506-`begin`\
507-`  NewTime := glutGet(GLUT_ELAPSED_TIME);`\
508-`  Result := (NewTime - OldTime) / 1000;`\
509-`  OldTime := NewTime;`\
510-`end;`\
538+function GetDeltaTime: Single;
539+var
540+ NewTime: Integer;
541+begin
542+ NewTime := glutGet(GLUT_ELAPSED_TIME);
543+ Result := (NewTime - OldTime) / 1000;
544+ OldTime := NewTime;
545+end;
511546
512-`procedure FrameRendered(Count: Integer);`\
513-`begin`\
514-`  Inc(FPSCount, Count);`\
515-`end;`\
547+procedure FrameRendered(Count: Integer);
548+begin
549+ Inc(FPSCount, Count);
550+end;
516551
517-`function GetFPS: Single;`\
518-`var`\
519-`  NewTime: Integer;`\
520-`begin`\
521-`  NewTime := glutGet(GLUT_ELAPSED_TIME);`\
552+function GetFPS: Single;
553+var
554+ NewTime: Integer;
555+begin
556+ NewTime := glutGet(GLUT_ELAPSED_TIME);
522557
523-`  Result := FPSCount / ((NewTime - FPSTime) / 1000);`\
558+ Result := FPSCount / ((NewTime - FPSTime) / 1000);
524559
525-`  FPSTime := NewTime;`\
526-`  FPSCount := 0;`\
527-`end;`\
560+ FPSTime := NewTime;
561+ FPSCount := 0;
562+end;
528563
529-`end.`
564+end.
565+```
530566
531567As you can see, there is nothing complicated in this unit. Time is simply saved betwen calls and difference is returned. FrameRendered should be called every time you draw scene so function can calculate FPS.
532568
533569Now, let's have fun with lights.
534570
535571OpenGL have several types of light... ambient, diffuse, point, spot, specular and emissive light.
536572
537573Ambient light is something like Sun. When sun rays pass through the window of a room they hit the walls and are reflected and scattered into all different directions which averagely brightens up the whole room. All vertices are lit with ambient light.
538574
539575Diffuse light can be represented as parallel light rays comming from far away. They will lit only vertices that are oriented towards the light source.
540576
541577Point light lights all around it. It is like a fire ball, it send light rays all around it and lights vertices that are oriented towards light source and that are close enough.
542578
543579Spot light is like light from flashlight. It is simply a point light source with a small light cone radius. All vertices that falls inside of cone and are close enough are lit.
544580
545581Just like Diffuse light, Specular light is a directional type of light. It comes from one particular direction. The difference between the two is that specular light reflects off the surface in a sharp and uniform way. The rendering of specular light relies on the angle between the viewer and the light source. From the viewer’s standpoint specular light creates a highlighted area on the surface of the viewed object known as specular highlight or specular reflection.
546582
547583Emissive light is a little different than any other previously explained light components. This light comes out of object you draw but don't lit other objects in nearby.
548584
549585For simplicity we'll use only diffuse light in this tutorial. Later on, some other lights may appear in tutorials :)
550586
551587Let's see how to enable light in scene:
552588
553-`const`\
554-`  DiffuseLight: array[0..3] of GLfloat = (0.8, 0.8, 0.8, 1);`\
589+``` pascal
590+const
591+ DiffuseLight: array[0..3] of GLfloat = (0.8, 0.8, 0.8, 1);
555592
556-`  glEnable(GL_LIGHTING);`\
557-`  glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);`\
558-`  glEnable(GL_LIGHT0);`
593+ glEnable(GL_LIGHTING);
594+ glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
595+ glEnable(GL_LIGHT0);
596+```
559597
560598As you see, we enable lighting in OpenGL so lights affect scene you are rendering. Light parameters are set with glLightfv function. It takes 3 parameters... one for light number you want to change (OpenGL suports up to 8 lights), next tells OpenGL what light parameter to change, and the last one is new parameter for light. You'll set just diffuse color for light in this tutorial. After that, you can enable light and there will be light in the scene... but... that is not all.
561599
562600More about glLightfv: <http://www.opengl.org//documentation/specs/man_pages/hardcopy/GL/html/gl/light.html>
563601
564602If you want to use lights you can't just set color for vertex... you must set material for vertices. Let's setup material for drawing:
565603
566-`glEnable(GL_COLOR_MATERIAL);`\
567-`glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);`
604+```text
605+glEnable(GL_COLOR_MATERIAL);
606+glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
607+```
568608
569609![](/wiki-images/e/ed/LightPic1.jpg) You expected something more complicated, do you? :) Well, this code allows us to use glColor function to set material to vertices. By using glEnable function and GL_COLOR_MATERIAL flag, you can define what material properties will glColor change. glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE) tells OpenGL that glColor changes ambient and diffuse material. We'll discus materials more in later tutorials.
570610
571611One more thing that is important when using lights... every vertex must have normal associated with it. Normal is used to find the direction of vertex so light can be calculated properly. You'll use GLUT function to draw cube and it provides normals for us, so this time we'll just walk by normals.
572612
573613After all those setting ups, light will shine up your cube :)
574614
575615Part of the text is copied from [The OpenGL Light Bible](http://www.falloutsoftware.com/tutorials/gl/gl8.htm)
576616
577617Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
578618
579619# Bitmap fonts
580620
581621Games and programs usually need to write some text on screen. GLUT provides several functions for drawing chars that are platform independent.
582622
583623First, we'll show how to use default bitmap fonts. Almost all code additions will be made to utils.pas unit.
584624
585625Since text will be drawn in 2D, we'll need to know width and height of viewport... so, we'll write two functions for that:
586626
587-`function glGetViewportWidth: Integer;`\
588-`var`\
589-`  Rect: array[0..3] of Integer;`\
590-`begin`\
591-`  glGetIntegerv(GL_VIEWPORT, @Rect);`\
592-`  Result := Rect[2] - Rect[0];`\
593-`end;`\
627+``` pascal
628+function glGetViewportWidth: Integer;
629+var
630+ Rect: array[0..3] of Integer;
631+begin
632+ glGetIntegerv(GL_VIEWPORT, @Rect);
633+ Result := Rect[2] - Rect[0];
634+end;
594635
595-`function glGetViewportHeight: Integer;`\
596-`var`\
597-`  Rect: array[0..3] of Integer;`\
598-`begin`\
599-`  glGetIntegerv(GL_VIEWPORT, @Rect);`\
600-`  Result := Rect[3] - Rect[1];`\
601-`end;`
636+function glGetViewportHeight: Integer;
637+var
638+ Rect: array[0..3] of Integer;
639+begin
640+ glGetIntegerv(GL_VIEWPORT, @Rect);
641+ Result := Rect[3] - Rect[1];
642+end;
643+```
602644
603645We just get left/right, top/bottom and calculate width/height by subtracting them.
604646
605647There must be functions for entering and leaving 2D mode:
606648
607-`procedure glEnter2D;`\
608-`begin`\
609-`  glMatrixMode(GL_PROJECTION);`\
610-`  glPushMatrix;`\
611-`  glLoadIdentity;`\
612-`  gluOrtho2D(0, glGetViewportWidth, 0, glGetViewportHeight);`\
649+``` pascal
650+procedure glEnter2D;
651+begin
652+ glMatrixMode(GL_PROJECTION);
653+ glPushMatrix;
654+ glLoadIdentity;
655+ gluOrtho2D(0, glGetViewportWidth, 0, glGetViewportHeight);
613656
614-`  glMatrixMode(GL_MODELVIEW);`\
615-`  glPushMatrix;`\
616-`  glLoadIdentity;`\
657+ glMatrixMode(GL_MODELVIEW);
658+ glPushMatrix;
659+ glLoadIdentity;
617660
618-`  glDisable(GL_DEPTH_TEST);`\
619-`end;`\
661+ glDisable(GL_DEPTH_TEST);
662+end;
620663
621-`procedure glLeave2D;`\
622-`begin`\
623-`  glMatrixMode(GL_PROJECTION);`\
624-`  glPopMatrix;`\
625-`  glMatrixMode(GL_MODELVIEW);`\
626-`  glPopMatrix;`\
664+procedure glLeave2D;
665+begin
666+ glMatrixMode(GL_PROJECTION);
667+ glPopMatrix;
668+ glMatrixMode(GL_MODELVIEW);
669+ glPopMatrix;
627670
628-`  glEnable(GL_DEPTH_TEST);`\
629-`end;`
671+ glEnable(GL_DEPTH_TEST);
672+end;
673+```
630674
631675When entering 2D mode, we save current matrices and set 2D matrix using gluOrtho2D function. This way if we draw some thing on 100, 100 it will be drawn on exactly 100 pixels from left edge of window, and 100 pixels form bottom edge (positive Y is up). Also, we disable ZBuffer. This way text won't alter ZBuffer.
632676
633677Leaving 2D mode just returns old matrices and enable ZBuffer.
634678
635679Now, we can create function for text drawing:
636680
637-`procedure glWrite(X, Y: GLfloat; Font: Pointer; Text: String);`\
638-`var`\
639-`  I: Integer;`\
640-`begin`\
641-`  glRasterPos2f(X, Y);`\
642-`  for I := 1 to Length(Text) do`\
643-`    glutBitmapCharacter(Font, Integer(Text[I]));`\
644-`end;`
681+``` pascal
682+procedure glWrite(X, Y: GLfloat; Font: Pointer; Text: String);
683+var
684+ I: Integer;
685+begin
686+ glRasterPos2f(X, Y);
687+ for I := 1 to Length(Text) do
688+ glutBitmapCharacter(Font, Integer(Text[I]));
689+end;
690+```
645691
646692glutBitmapCharacter can draw only one character of selected font. First parameter is desired font (GLUT_BITMAP_9_BY_15, GLUT_BITMAP_8_BY_13, GLUT_BITMAP_TIMES_ROMAN_10, GLUT_BITMAP_TIMES_ROMAN_24, GLUT_BITMAP_HELVETICA_10, GLUT_BITMAP_HELVETICA_12 or GLUT_BITMAP_HELVETICA_18) and other one is character.
647693
648694Character will be drawn at current raster position. To set desired raster position we call glRasterPos function. glRasterPos can handle different number and types of parameters just like glVertex function. Coordinate specified is transformed by model and projection matrix to get 2D coordinate where new raster position will be. Since we entered 2D mode, X and Y coordinates are actual 2D coordinates where drawing will occur.
649695
650696This new functions will make text drawing very easy:
651697
652-`procedure DrawGLScene; cdecl;`\
653-`begin`\
654-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
698+``` pascal
699+procedure DrawGLScene; cdecl;
700+begin
701+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
655702
656-`  glLoadIdentity;`\
657-`  glTranslatef(0, 0, -5);`\
658-`  glRotatef(GetTotalTime * 10, 0, 0.5, 0.5);`\
703+ glLoadIdentity;
704+ glTranslatef(0, 0, -5);
705+ glRotatef(GetTotalTime * 10, 0, 0.5, 0.5);
659706
660-`  glColor3f(1, 0, 0);`\
661-`  glutSolidCube(2);`\
707+ glColor3f(1, 0, 0);
708+ glutSolidCube(2);
662709
663-`  glEnter2D;`\
710+ glEnter2D;
664711
665-`  glColor3f(0.2, 0.8 + 0.2 * Sin(GetTotalTime * 5), 0);`\
666-`  glWrite(20, glGetViewportHeight - 20, GLUT_BITMAP_8_BY_13,`\
667-`    Format('OpenGL Tutorial :: Bitmap Fonts :: FPS - %.2f FPS', [FPS]));`\
712+ glColor3f(0.2, 0.8 + 0.2 * Sin(GetTotalTime * 5), 0);
713+ glWrite(20, glGetViewportHeight - 20, GLUT_BITMAP_8_BY_13,
714+ Format('OpenGL Tutorial :: Bitmap Fonts :: FPS - %.2f FPS', [FPS]));
668715
669-`  glColor3f(1, 1, 1);`\
670-`  glWrite(50, glGetViewportHeight - 60, GLUT_BITMAP_9_BY_15, 'GLUT_BITMAP_9_BY_15');`\
671-`  glWrite(50, glGetViewportHeight - 90, GLUT_BITMAP_8_BY_13, 'GLUT_BITMAP_8_BY_13');`\
672-`  glWrite(50, glGetViewportHeight - 120, GLUT_BITMAP_TIMES_ROMAN_10, 'GLUT_BITMAP_TIMES_ROMAN_10');`\
673-`  glWrite(50, glGetViewportHeight - 150, GLUT_BITMAP_TIMES_ROMAN_24, 'GLUT_BITMAP_TIMES_ROMAN_24');`\
674-`  glWrite(50, glGetViewportHeight - 180, GLUT_BITMAP_HELVETICA_10, 'GLUT_BITMAP_HELVETICA_10');`\
675-`  glWrite(50, glGetViewportHeight - 210, GLUT_BITMAP_HELVETICA_12, 'GLUT_BITMAP_HELVETICA_12');`\
676-`  glWrite(50, glGetViewportHeight - 240, GLUT_BITMAP_HELVETICA_18, 'GLUT_BITMAP_HELVETICA_18');`\
716+ glColor3f(1, 1, 1);
717+ glWrite(50, glGetViewportHeight - 60, GLUT_BITMAP_9_BY_15, 'GLUT_BITMAP_9_BY_15');
718+ glWrite(50, glGetViewportHeight - 90, GLUT_BITMAP_8_BY_13, 'GLUT_BITMAP_8_BY_13');
719+ glWrite(50, glGetViewportHeight - 120, GLUT_BITMAP_TIMES_ROMAN_10, 'GLUT_BITMAP_TIMES_ROMAN_10');
720+ glWrite(50, glGetViewportHeight - 150, GLUT_BITMAP_TIMES_ROMAN_24, 'GLUT_BITMAP_TIMES_ROMAN_24');
721+ glWrite(50, glGetViewportHeight - 180, GLUT_BITMAP_HELVETICA_10, 'GLUT_BITMAP_HELVETICA_10');
722+ glWrite(50, glGetViewportHeight - 210, GLUT_BITMAP_HELVETICA_12, 'GLUT_BITMAP_HELVETICA_12');
723+ glWrite(50, glGetViewportHeight - 240, GLUT_BITMAP_HELVETICA_18, 'GLUT_BITMAP_HELVETICA_18');
677724
678-`  glColor3f(0.5, 0.5, 1);`\
679-`  glWrite(`\
680-`    glGetViewportWidth - glutBitmapLength(GLUT_BITMAP_9_BY_15, LazText) - 5,`\
681-`    10, GLUT_BITMAP_9_BY_15, LazText);`\
725+ glColor3f(0.5, 0.5, 1);
726+ glWrite(
727+ glGetViewportWidth - glutBitmapLength(GLUT_BITMAP_9_BY_15, LazText) - 5,
728+ 10, GLUT_BITMAP_9_BY_15, LazText);
682729
683-`  glLeave2D;`\
730+ glLeave2D;
684731
685-`  glutSwapBuffers;`\
732+ glutSwapBuffers;
686733
687-`  FrameRendered;`\
688-`end;`
734+ FrameRendered;
735+end;
736+```
689737
690738![](/wiki-images/b/ba/BitmapFontsPic1.jpg) We draw red cube and rotate it, and some text to show how various bitmap fonts look like. glutBitmapLength function is used to find width of string so it could be aligned to right. Code can easily be altered to center text.
691739
692740Note: See how cube looks without light.
693741
694742Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
695743
696744# Textures
697745
698746It's time to use textures :)
699747
700748This tutorial will show how to draw textured polygons and how to blend textures using multipass technic. Since OpenGL has no builtin mechanism for loading textures, we'll use external library: [Vampyre Imaging Library](http://imaginglib.sourceforge.net/). We'll use just OpenGL helper functions, but you may find this lib handy for some other things to.
701749
702750Let's get started... we'll create display list for drawing textured rectangle:
703751
704-`procedure CreateList;`\
705-`begin`\
706-`  glNewList(LIST_OBJECT, GL_COMPILE);`\
707-`    glBegin(GL_QUADS);`\
708-`      glTexCoord2f(1, 0);`\
709-`      glVertex3f( 2, 2, 0);`\
710-`      glTexCoord2f(0, 0);`\
711-`      glVertex3f(-2, 2, 0);`\
712-`      glTexCoord2f(0, 1);`\
713-`      glVertex3f(-2,-2, 0);`\
714-`      glTexCoord2f(1, 1);`\
715-`      glVertex3f( 2,-2, 0);`\
716-`    glEnd;`\
717-`  glEndList;`\
718-`end;`
752+``` pascal
753+procedure CreateList;
754+begin
755+ glNewList(LIST_OBJECT, GL_COMPILE);
756+ glBegin(GL_QUADS);
757+ glTexCoord2f(1, 0);
758+ glVertex3f( 2, 2, 0);
759+ glTexCoord2f(0, 0);
760+ glVertex3f(-2, 2, 0);
761+ glTexCoord2f(0, 1);
762+ glVertex3f(-2,-2, 0);
763+ glTexCoord2f(1, 1);
764+ glVertex3f( 2,-2, 0);
765+ glEnd;
766+ glEndList;
767+end;
768+```
719769
720770Notice glTexCoord functions. They are used to specify which part of texture is assigned to vertex. Coordinates defined in this functions are from 0 to 1 (values greater than 1 are allowed but can generate different results). 0 is first pixel and 1 is last pixel. So, 0.5 will be right in the middle of texture.
721771
722772Texture loading is extremely easy with Vampyre Imaging Library:
723773
724-`var`\
725-`  Tex1, Tex2: GLuint;`\
774+``` pascal
775+var
776+ Tex1, Tex2: GLuint;
726777
727-`procedure InitializeGL;`\
728-`begin`\
729-`  glClearColor(0, 0, 0, 0);`\
730-`  Tex1 := LoadGLTextureFromFile('ashwood.bmp');`\
731-`  Tex2 := LoadGLTextureFromFile('Flare.bmp');`\
732-`  glEnable(GL_TEXTURE_2D);`\
733-`end;`
778+procedure InitializeGL;
779+begin
780+ glClearColor(0, 0, 0, 0);
781+ Tex1 := LoadGLTextureFromFile('ashwood.bmp');
782+ Tex2 := LoadGLTextureFromFile('Flare.bmp');
783+ glEnable(GL_TEXTURE_2D);
784+end;
785+```
734786
735787LoadGLTextureFromFile loads texture from file and returns it's ID. When texture is loaded it is allready setup for rendering. Last line just enables 2D textures.
736788
737789To draw textured polygon you have to bind texture and setup texture coordinations (texture coordinations are set in display list in this tutorial):
738790
739-`  ...`\
740-`  glLoadIdentity;`\
741-`  glTranslatef(-5, 0, -15);`\
742-`  glBindTexture(GL_TEXTURE_2D, Tex1);`\
743-`  glCallList(LIST_OBJECT);`\
744-`  ...`
791+```text
792+ ...
793+ glLoadIdentity;
794+ glTranslatef(-5, 0, -15);
795+ glBindTexture(GL_TEXTURE_2D, Tex1);
796+ glCallList(LIST_OBJECT);
797+ ...
798+```
745799
746800glBindTexture function is used to select texture. When you draw polygins they will have selected texture on them. It's that easy :)
747801
748802So, using one texture is easy... but how to blend two textures. Basicly you draw polygon once with one texture, setup blending parameters, and draw polygon once more time with other texture. You can blend houndreds of textures this way. Let's see how code for this looks:
749803
750-`  ...`\
751-`  glLoadIdentity;`\
752-`  glTranslatef(5, 0, -15);`\
753-`  glBindTexture(GL_TEXTURE_2D, Tex1);`\
754-`  glCallList(LIST_OBJECT);`\
804+```text
805+ ...
806+ glLoadIdentity;
807+ glTranslatef(5, 0, -15);
808+ glBindTexture(GL_TEXTURE_2D, Tex1);
809+ glCallList(LIST_OBJECT);
755810
756-`  glEnable(GL_BLEND);`\
757-`  glBlendFunc(GL_ZERO, GL_SRC_COLOR);`\
758-`  glLoadIdentity;`\
759-`  glTranslatef(5, 0, -15);`\
760-`  glBindTexture(GL_TEXTURE_2D, Tex2);`\
761-`  glCallList(LIST_OBJECT);`\
762-`  glDisable(GL_BLEND);`\
763-`...`
811+ glEnable(GL_BLEND);
812+ glBlendFunc(GL_ZERO, GL_SRC_COLOR);
813+ glLoadIdentity;
814+ glTranslatef(5, 0, -15);
815+ glBindTexture(GL_TEXTURE_2D, Tex2);
816+ glCallList(LIST_OBJECT);
817+ glDisable(GL_BLEND);
818+...
819+```
764820
765821As you can see, polygon is drawn first time like we allready know. Before second drawing we enable blending by calling glEnable(GL_BLEND). Blending means that finall pixel color is calculated like this:
766822
767-`DrawingColor * SRCBLEND + BackgroundColor * DESTBLEND`
823+```text
824+DrawingColor * SRCBLEND + BackgroundColor * DESTBLEND
825+```
768826
769827SRCBLEND and DESTBLEND are defined using glBlendFunc function. In this tutorial we set SRCBLEND to GL_ZERO (zero) and DESTBLENT to GL_SRC_COLOR (DrawingColor) and finall color is then:
770828
771-`DrawingColor * 0 + BackgroundColor * DrawingColor`
829+```text
830+DrawingColor * 0 + BackgroundColor * DrawingColor
831+```
772832
773833![](/wiki-images/d/d4/TexturesPic1.jpg)
774834
775835This means that background will get darker when you draw with dark colors... when you draw with white color, background color will not be changed. The result will look like this
776836
777837Next time, we'll use extensions to show how to use singlepass multitexturing.
778838
779839Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
780840
781841# Multitexturing (extensions)
782842
783843When youknow multipass multi texturing, singlepass is very easy. Texturing is separated in stages. First stage setup and draw first texture, second stage draws another one and so on. All you have to do is to setup texture stages and to render object.
784844
785845Let's see how code looks like:
786846
787-`procedure InitializeGL;`\
788-`begin`\
789-`  Load_GL_ARB_multitexture;`\
790-`  glClearColor(0, 0, 0, 0);`\
791-`  Tex1 := LoadGLTextureFromFile('Lazarus.bmp');`\
792-`  Tex2 := LoadGLTextureFromFile('Mask.bmp');`\
793-`  glActiveTextureARB(GL_TEXTURE0_ARB);`\
794-`  glEnable(GL_TEXTURE_2D);`\
795-`  glBindTexture(GL_TEXTURE_2D, Tex1);`\
796-`  glActiveTextureARB(GL_TEXTURE1_ARB);`\
797-`  glEnable(GL_TEXTURE_2D);`\
798-`  glBindTexture(GL_TEXTURE_2D, Tex2);`\
799-`end;`
847+``` pascal
848+procedure InitializeGL;
849+begin
850+ Load_GL_ARB_multitexture;
851+ glClearColor(0, 0, 0, 0);
852+ Tex1 := LoadGLTextureFromFile('Lazarus.bmp');
853+ Tex2 := LoadGLTextureFromFile('Mask.bmp');
854+ glActiveTextureARB(GL_TEXTURE0_ARB);
855+ glEnable(GL_TEXTURE_2D);
856+ glBindTexture(GL_TEXTURE_2D, Tex1);
857+ glActiveTextureARB(GL_TEXTURE1_ARB);
858+ glEnable(GL_TEXTURE_2D);
859+ glBindTexture(GL_TEXTURE_2D, Tex2);
860+end;
861+```
800862
801863First we need load OpenGL extension that will allow us to use multitexture functions. Load_GL_ARB_multitexture will try to load those extensions and will return TRUE if operation was successful.
802864
803865To select texture stage you want to work on, use glActiveTextureARB function. It takes only one parameter that define which stage you want. After that all texture functions (enabling, disabling, binding, creating...) will affect that stage.
804866
805867Since we setup every thing in initialization function, all we have to do is to draw object:
806868
807-`procedure DrawGLScene; cdecl;`\
808-`begin`\
809-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
869+``` pascal
870+procedure DrawGLScene; cdecl;
871+begin
872+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
810873
811-`  glLoadIdentity;`\
812-`  glTranslatef(0, 0, -5);`\
874+ glLoadIdentity;
875+ glTranslatef(0, 0, -5);
813876
814-`  glBegin(GL_QUADS);`\
815-`    glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1, 0);`\
816-`    glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 1, 0);`\
817-`    glVertex3f(2.516, 2, 0);`\
818-`    glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 0);`\
819-`    glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0, 0);`\
820-`    glVertex3f(-2.516, 2, 0);`\
821-`    glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 1);`\
822-`    glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0, 1);`\
823-`    glVertex3f(-2.516,-2, 0);`\
824-`    glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1, 1);`\
825-`    glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 1, 1);`\
826-`    glVertex3f(2.516,-2, 0);`\
827-`  glEnd;`\
877+ glBegin(GL_QUADS);
878+ glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1, 0);
879+ glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 1, 0);
880+ glVertex3f(2.516, 2, 0);
881+ glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 0);
882+ glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0, 0);
883+ glVertex3f(-2.516, 2, 0);
884+ glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 1);
885+ glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0, 1);
886+ glVertex3f(-2.516,-2, 0);
887+ glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1, 1);
888+ glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 1, 1);
889+ glVertex3f(2.516,-2, 0);
890+ glEnd;
828891
829-`  glutSwapBuffers;`\
830-`end;`
892+ glutSwapBuffers;
893+end;
894+```
831895
832896![](/wiki-images/5/52/MultitexturePic1.jpg) As you can see, difference is only in defining texture coordinations. We now use glMultiTexCoord2fARB function that takes texture stage and texture coordinations. Every thing else is unchanged.
833897
834898Today almost all graphic cards supports at least 2 texture stages. Using singlepass multitexturing is faster than multipass version since you draw objects only once. If hardware supports singlepass multitexturing (Load_GL_ARB_multitexture returns TRUE) use it.
835899
836900Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
837901
838902# Render to texture
839903
840904This one will be short. OpenGL can capture current scene to texture so you can use it for texturing other objects (TV screen, mirror or some thing else). Well just render scene to texture and apply it to rotating plane.
841905
842906First, we must create empty texture which well use to capture scene:
843907
844-`procedure SetupRenderTexture;`\
845-`var`\
846-`  Data: Pointer;`\
847-`begin`\
848-`  GetMem(Data, 256*256*3);`\
849-`  glGenTextures(1, @RenderTexture);`\
850-`  glBindTexture(GL_TEXTURE_2D, RenderTexture);`\
851-`  glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);`\
852-`  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);`\
853-`  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);`\
854-`  FreeMem(Data);`\
855-`end;`
908+``` pascal
909+procedure SetupRenderTexture;
910+var
911+ Data: Pointer;
912+begin
913+ GetMem(Data, 256*256*3);
914+ glGenTextures(1, @RenderTexture);
915+ glBindTexture(GL_TEXTURE_2D, RenderTexture);
916+ glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);
917+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
918+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
919+ FreeMem(Data);
920+end;
921+```
856922
857923Buffer for 256*256 RGB image is created and it is used to setup 2D texture.
858924
859925Main part is in drawing function:
860926
861-`procedure DrawGLScene; cdecl;`\
862-`var`\
863-`  TotalTime: Single;`\
864-`begin`\
865-`  glClearColor(0, 0, 0, 0);`\
866-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
867-`  glEnable(GL_LIGHTING);`\
868-`  glDisable(GL_TEXTURE_2D);`\
869-`  glViewport(0, 0, 256, 256);`\
927+``` pascal
928+procedure DrawGLScene; cdecl;
929+var
930+ TotalTime: Single;
931+begin
932+ glClearColor(0, 0, 0, 0);
933+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
934+ glEnable(GL_LIGHTING);
935+ glDisable(GL_TEXTURE_2D);
936+ glViewport(0, 0, 256, 256);
870937
871-`  TotalTime := GetTotalTime;`\
938+ TotalTime := GetTotalTime;
872939
873-`  glLoadIdentity;`\
874-`  glTranslatef(0, 0, -5);`\
875-`  glRotatef(50 * TotalTime, 1, 0, 0);`\
876-`  glRotatef(100 * TotalTime, 0, 1, 0);`\
877-`  glRotatef(50 * TotalTime, 0, 0, 1);`\
940+ glLoadIdentity;
941+ glTranslatef(0, 0, -5);
942+ glRotatef(50 * TotalTime, 1, 0, 0);
943+ glRotatef(100 * TotalTime, 0, 1, 0);
944+ glRotatef(50 * TotalTime, 0, 0, 1);
878945
879-`  glColor3f(1, 1, 1);`\
880-`  glutSolidCube(2);`\
946+ glColor3f(1, 1, 1);
947+ glutSolidCube(2);
881948
882-`  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, 256, 256, 0);`\
949+ glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, 256, 256, 0);
883950
884-`  glClearColor(0.18, 0.20, 0.66, 0);`\
885-`  glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);`\
886-`  glDisable(GL_LIGHTING);`\
887-`  glEnable(GL_TEXTURE_2D);`\
888-`  glViewport(0, 0, AppWidth, AppHeight);`\
951+ glClearColor(0.18, 0.20, 0.66, 0);
952+ glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
953+ glDisable(GL_LIGHTING);
954+ glEnable(GL_TEXTURE_2D);
955+ glViewport(0, 0, AppWidth, AppHeight);
889956
890-`  glLoadIdentity;`\
891-`  glTranslatef(0, 0, -7);`\
892-`  glRotatef(20 * TotalTime, 1, 0, 0);`\
893-`  glRotatef(50 * TotalTime, 0, 1, 0);`\
957+ glLoadIdentity;
958+ glTranslatef(0, 0, -7);
959+ glRotatef(20 * TotalTime, 1, 0, 0);
960+ glRotatef(50 * TotalTime, 0, 1, 0);
894961
895-`  glBegin(GL_QUADS);`\
896-`    glTexCoord2f(1, 0);`\
897-`    glVertex3f(2, 2, 0);`\
898-`    glTexCoord2f(0, 0);`\
899-`    glVertex3f(-2, 2, 0);`\
900-`    glTexCoord2f(0, 1);`\
901-`    glVertex3f(-2,-2, 0);`\
902-`    glTexCoord2f(1, 1);`\
903-`    glVertex3f(2,-2, 0);`\
904-`  glEnd;`\
962+ glBegin(GL_QUADS);
963+ glTexCoord2f(1, 0);
964+ glVertex3f(2, 2, 0);
965+ glTexCoord2f(0, 0);
966+ glVertex3f(-2, 2, 0);
967+ glTexCoord2f(0, 1);
968+ glVertex3f(-2,-2, 0);
969+ glTexCoord2f(1, 1);
970+ glVertex3f(2,-2, 0);
971+ glEnd;
905972
906-`  glutSwapBuffers;`\
907-`end;`
973+ glutSwapBuffers;
974+end;
975+```
908976
909977![](/wiki-images/6/6e/RenderToTexturePic1.jpg) First, everything is setup for scene that will be captured. Viewport is reduced to 256*256 so it will fit into texture and scene is drawn. glCopyTexImage2D is used to capture scene to currently selected texture.
910978
911979When we have scene captured to texture, everything can be cleared again, viewport can be returned to original size and final scene is drawn using previous scene as texture.
912980
913981P.S. Captured texture can be saved using SaveGLTextureToFile function from [Vampyre Imaging Library](http://imaginglib.sourceforge.net/).
914982
915983Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
916984
917985# Vertex array
918986
919987OpenGL is capable of rendering primitives using data that is stored in buffers insted of calling glVertex. Buffers can be used to define vertex and texture coordinates, and colors (index and RGBA), normals and edge flags.
920988
921989In this tutorial well use only vertex and color buffers, and we'll show non-indexed and indexed drawing. Non-indexed mode draws buffers as streams. Indexed mode will draw buffer elements in order that is defined in index buffer. But enough talking... let's start coding.
922990
923991First, let's define some types and constants:
924992
925-`type`\
926-`  TVertex3f = record`\
927-`    X, Y, Z: Single;`\
928-`  end;`\
993+``` pascal
994+type
995+ TVertex3f = record
996+ X, Y, Z: Single;
997+ end;
929998
930-`  TColor3f = record`\
931-`   R, G, B: Single;`\
932-`  end;`\
999+ TColor3f = record
1000+ R, G, B: Single;
1001+ end;
9331002
934-`  VertexBuffer: array [0..5] of TVertex3f = (`\
935-`    (X : 1; Y : 1; Z : 0),`\
936-`    (X : -1; Y : 1; Z : 0),`\
937-`    (X : -1; Y : -1; Z : 0),`\
938-`    (X : 1; Y : 1; Z : 0),`\
939-`    (X : -1; Y : -1; Z : 0),`\
940-`    (X : 1; Y : -1; Z : 0)`\
941-`  );`\
942-`  ColorBuffer: array [0..5] of TColor3f = (`\
943-`    (R : 1; G : 0; B : 1),`\
944-`    (R : 0; G : 0; B : 1),`\
945-`    (R : 0; G : 1; B : 0),`\
946-`    (R : 1; G : 0; B : 1),`\
947-`    (R : 0; G : 1; B : 0),`\
948-`    (R : 1; G : 1; B : 0)`\
949-`  );`
1003+ VertexBuffer: array [0..5] of TVertex3f = (
1004+ (X : 1; Y : 1; Z : 0),
1005+ (X : -1; Y : 1; Z : 0),
1006+ (X : -1; Y : -1; Z : 0),
1007+ (X : 1; Y : 1; Z : 0),
1008+ (X : -1; Y : -1; Z : 0),
1009+ (X : 1; Y : -1; Z : 0)
1010+ );
1011+ ColorBuffer: array [0..5] of TColor3f = (
1012+ (R : 1; G : 0; B : 1),
1013+ (R : 0; G : 0; B : 1),
1014+ (R : 0; G : 1; B : 0),
1015+ (R : 1; G : 0; B : 1),
1016+ (R : 0; G : 1; B : 0),
1017+ (R : 1; G : 1; B : 0)
1018+ );
1019+```
9501020
9511021We have two buffers. One for vertex coordinates and one for vertex colors. This 6 vertices defines 2 triangles that forms rectangle.
9521022
9531023Drawing primitives using buffers is easy:
9541024
955-`  glEnableClientState(GL_VERTEX_ARRAY);`\
956-`  glEnableClientState(GL_COLOR_ARRAY);`\
957-`  glVertexPointer(3, GL_FLOAT, 0, @VertexBuffer[0]);`\
958-`  glColorPointer(3, GL_FLOAT, 0, @ColorBuffer[0]);`\
1025+```text
1026+ glEnableClientState(GL_VERTEX_ARRAY);
1027+ glEnableClientState(GL_COLOR_ARRAY);
1028+ glVertexPointer(3, GL_FLOAT, 0, @VertexBuffer[0]);
1029+ glColorPointer(3, GL_FLOAT, 0, @ColorBuffer[0]);
9591030
960-`  glDrawArrays(GL_TRIANGLES, 0, Length(VertexBuffer));`\
1031+ glDrawArrays(GL_TRIANGLES, 0, Length(VertexBuffer));
9611032
962-`  glDisableClientState(GL_VERTEX_ARRAY);`\
963-`  glDisableClientState(GL_COLOR_ARRAY);`
1033+ glDisableClientState(GL_VERTEX_ARRAY);
1034+ glDisableClientState(GL_COLOR_ARRAY);
1035+```
9641036
9651037First we enable buffers we want to use using glEnableClientState function. Than we can select buffers we want to use. Every buffer type has own function for selecting (glColorPointer, glEdgeFlagPointer, glIndexPointer, glNormalPointer, glTexCoordPointer, glVertexPointer). First parameter in those functions defines how many numbers every element contains. For example, let's take vertex buffer. If this parameter is 2 than OpenGL expects that every element in buffer contains x and y coordinate. If this parameter is, for example, 4, than every element should contains x, y, z and w coordinate. Next parameter defines what type of data element contains (GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT or GL_DOUBLE). Next one defines how many bytes are between each element. This way you can have buffer that contains vertex coordinates and some custom data. For arbitrary data type, this parameter can be calculated like this:
9661038
967-`type`\
968-`  TBufferData = record`\
969-`    DataBefore: TDataBefore;`\
970-`    Vertex: TVertex;`\
971-`    DataAfter: TDataAfter;`\
972-`  end;`\
1039+``` pascal
1040+type
1041+ TBufferData = record
1042+ DataBefore: TDataBefore;
1043+ Vertex: TVertex;
1044+ DataAfter: TDataAfter;
1045+ end;
9731046
974-`Bytes between elements = SizeOf(TDataBefore) + SizeOf(TDataAfter)`
1047+Bytes between elements = SizeOf(TDataBefore) + SizeOf(TDataAfter)
1048+```
9751049
9761050Last parameter if pointer to the begginig of buffer.
9771051
9781052When buffers are selected we can draw them using glDrawArrays functions. All enabled buffers are used to draw primitives. What kind of polygons are being generated is defined in first parameter (same as in glBegin function). Next two defines subset of buffer which is used for drawing (start and count).
9791053
9801054When buffers are not needed you can disable them.
9811055
9821056To demonstrate indexed mode, I made some simple mesh class that can load vertex, color and index data from external files:
9831057
984-`type`\
985-`  TMesh = class`\
986-`  private`\
987-`    FVertices: array of TVertex3f;`\
988-`    FColors: array of TColor3f;`\
989-`    FIndices: array of Integer;`\
990-`    procedure FreeBuffers;`\
991-`  public`\
992-`    constructor Create;`\
993-`    destructor Destroy; override;`\
994-`    procedure LoadMesh(FileName: String);`\
995-`    procedure DrawMesh;`\
996-`  end;`
1058+``` pascal
1059+type
1060+ TMesh = class
1061+ private
1062+ FVertices: array of TVertex3f;
1063+ FColors: array of TColor3f;
1064+ FIndices: array of Integer;
1065+ procedure FreeBuffers;
1066+ public
1067+ constructor Create;
1068+ destructor Destroy; override;
1069+ procedure LoadMesh(FileName: String);
1070+ procedure DrawMesh;
1071+ end;
1072+```
9971073
9981074FVertices will contain data about vertices, FColors data about color and FIndices data about indices when external file is loaded.
9991075
10001076First we'll write some code that deals with creation and destruction of class:
10011077
1002-`procedure TMesh.FreeBuffers;`\
1003-`begin`\
1004-`  FVertices := nil;`\
1005-`  FColors := nil;`\
1006-`  FIndices := nil;`\
1007-`end;`\
1078+``` pascal
1079+procedure TMesh.FreeBuffers;
1080+begin
1081+ FVertices := nil;
1082+ FColors := nil;
1083+ FIndices := nil;
1084+end;
10081085
1009-`constructor TMesh.Create;`\
1010-`begin`\
1011-`  FreeBuffers;`\
1012-`end;`\
1086+constructor TMesh.Create;
1087+begin
1088+ FreeBuffers;
1089+end;
10131090
1014-`destructor TMesh.Destroy;`\
1015-`begin`\
1016-`  FreeBuffers;`\
1017-`  inherited Destroy;`\
1018-`end;`
1091+destructor TMesh.Destroy;
1092+begin
1093+ FreeBuffers;
1094+ inherited Destroy;
1095+end;
1096+```
10191097
10201098File that will contain mesh data is simple text file. First row will contain number of vertices and indices separated by space character. After that row will come rows for every vertex and color. X, Y, Z, R, G and B all separated by space character. In the end, there will be rows for indices... every index number is written in its own row... so, for one triangle, data file will look like this:
10211099
1022-`3 3`\
1023-`-1 -1 0 1 1 1`\
1024-`1 -1 0 1 1 1`\
1025-`0 1 0 1 1 1`\
1026-`0`\
1027-`1`\
1028-`2`
1100+```text
1101+3 3
1102+-1 -1 0 1 1 1
1103+1 -1 0 1 1 1
1104+0 1 0 1 1 1
1105+0
1106+1
1107+2
1108+```
10291109
10301110This means that there is 3 vertices and 3 indices defined in file. First vrtex is at -1, -1, 0 and has color 1, 1, 1 and so on. Indices defines that order in which vertices are drawn (in this case vertices are drawn in the same order as they are defined).
10311111
10321112Code for loading this data will loke like this:
10331113
1034-`procedure TMesh.LoadMesh(FileName: String);`\
1035-`var`\
1036-`  MeshFile: TextFile;`\
1037-`  VertexCount, IndexCount: Integer;`\
1038-`  iV, iI: Integer;`\
1039-`begin`\
1040-`  FreeBuffers;`\
1114+``` pascal
1115+procedure TMesh.LoadMesh(FileName: String);
1116+var
1117+ MeshFile: TextFile;
1118+ VertexCount, IndexCount: Integer;
1119+ iV, iI: Integer;
1120+begin
1121+ FreeBuffers;
10411122
1042-`  AssignFile(MeshFile, FileName);`\
1043-`  Reset(MeshFile);`\
1123+ AssignFile(MeshFile, FileName);
1124+ Reset(MeshFile);
10441125
1045-`  ReadLn(MeshFile, VertexCount, IndexCount);`\
1126+ ReadLn(MeshFile, VertexCount, IndexCount);
10461127
1047-`  SetLength(FVertices, VertexCount);`\
1048-`  SetLength(FColors, VertexCount);`\
1049-`  SetLength(FIndices, IndexCount);`\
1128+ SetLength(FVertices, VertexCount);
1129+ SetLength(FColors, VertexCount);
1130+ SetLength(FIndices, IndexCount);
10501131
1051-`  for iV := 0 to VertexCount - 1 do`\
1052-`    ReadLn(MeshFile,`\
1053-`      FVertices[iV].X, FVertices[iV].Y, FVertices[iV].Z,`\
1054-`      FColors[iV].R, FColors[iV].G, FColors[iV].B);`\
1132+ for iV := 0 to VertexCount - 1 do
1133+ ReadLn(MeshFile,
1134+ FVertices[iV].X, FVertices[iV].Y, FVertices[iV].Z,
1135+ FColors[iV].R, FColors[iV].G, FColors[iV].B);
10551136
1056-`  for iI := 0 to IndexCount - 1 do`\
1057-`    ReadLn(MeshFile, FIndices[iI]);`\
1137+ for iI := 0 to IndexCount - 1 do
1138+ ReadLn(MeshFile, FIndices[iI]);
10581139
1059-`  CloseFile(MeshFile);`\
1060-`end;`
1140+ CloseFile(MeshFile);
1141+end;
1142+```
10611143
10621144After loading data, we have everything for drawing:
10631145
1064-`procedure TMesh.DrawMesh;`\
1065-`begin`\
1066-`  glEnableClientState(GL_VERTEX_ARRAY);`\
1067-`  glEnableClientState(GL_COLOR_ARRAY);`\
1068-`  glVertexPointer(3, GL_FLOAT, 0, @FVertices[0]);`\
1069-`  glColorPointer(3, GL_FLOAT, 0, @FColors[0]);`\
1146+``` pascal
1147+procedure TMesh.DrawMesh;
1148+begin
1149+ glEnableClientState(GL_VERTEX_ARRAY);
1150+ glEnableClientState(GL_COLOR_ARRAY);
1151+ glVertexPointer(3, GL_FLOAT, 0, @FVertices[0]);
1152+ glColorPointer(3, GL_FLOAT, 0, @FColors[0]);
10701153
1071-`  glDrawElements(GL_TRIANGLES, Length(FIndices), GL_UNSIGNED_INT, @FIndices[0]);`\
1154+ glDrawElements(GL_TRIANGLES, Length(FIndices), GL_UNSIGNED_INT, @FIndices[0]);
10721155
1073-`  glDisableClientState(GL_VERTEX_ARRAY);`\
1074-`  glDisableClientState(GL_COLOR_ARRAY);`\
1075-`end;`
1156+ glDisableClientState(GL_VERTEX_ARRAY);
1157+ glDisableClientState(GL_COLOR_ARRAY);
1158+end;
1159+```
10761160
10771161As you can see, allmost everything is the same as for non-indexed drawing, except function that actually draw polygons. In this case we use glDrawElements function. For this one we specify what kind of polygons we want, how many indices are in index buffer, type of data in index buffer and pointer to the beginning of index buffer.
10781162
10791163![](/wiki-images/7/77/VertexArrayPic1.jpg)Full source code comes with mesh data file that this class can use to generates rectangle that is identical with one that is drawn using non-indexed mode. Mesh data file looks like this:
10801164
1081-`4 6`\
1082-`1 1 0 1 0 1`\
1083-`-1 1 0 0 0 1`\
1084-`-1 -1 0 0 1 0`\
1085-`1 -1 0 1 1 0`\
1086-`0`\
1087-`1`\
1088-`2`\
1089-`0`\
1090-`2`\
1091-`3`
1165+```text
1166+4 6
1167+1 1 0 1 0 1
1168+-1 1 0 0 0 1
1169+-1 -1 0 0 1 0
1170+1 -1 0 1 1 0
1171+0
1172+1
1173+2
1174+0
1175+2
1176+3
1177+```
10921178
10931179As you can see, there is data for only 4 vertices and 6 indices. So, first triangle is defined by vertices 0, 1 and 2, and the seccond one by vertices 0, 2 and 3. By using indexed mode we don't have to duplicate vertices.
10941180
10951181Download source code, linux executable or windows executable from [Lazarus CCR SourceForge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=199145).
10961182
10971183---
10981184*From the Free Pascal wiki, page "OpenGL Tutorial/ja", as it stood on 2009-01-29 after a change by Saeka-jp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history