You are on page 1of 171

MC LC

Li m u

PHN 1: TM HIU TH VIN HA OPENGL 1


Chng 1: S lc v OPENGL 1
1.1. Lch s pht trin ........................................................................ 1
1.2. Khi nim.................................................................................... 1
1.3. Thnh phn ................................................................................. 5

Chng 2: ha hai chiu GDI 6


2.1. Ta cc v ta mn hnh................................................ 6
2.2. nh ngha vertex v kiu d liu hnh dng................................ 8
2.3. Cc php bin hnh ...................................................................... 10
2.4. S dng ma trn cho cc php bin hnh...................................... 17

Chng 3: ha ba chiu GDI 25


3.1. H ta ba chiu ......................................................................... 25
3.2. nh ngha i tng ba chiu ....................................................... 25
3.3. Cc phng php th hin hnh 3-D ln mn hnh .......................... 28
3.4. Bin hnh i tng 3-D ................................................................ 31

Chng 4: Chng trnh OpenGL ti thiu 36


4.1. Cc kiu d liu OpenGL .............................................................. 36
4.2. Ng cnh biu din ........................................................................ 36
4.3. nh dng im v ......................................................................... 38
4.4. To ng cnh bin din .................................................................. 44
4.5. Tng kt: ....................................................................................... 48

Chng 5: V hnh v s dng mu: 48


5.1. C php lnh OpenGL ................................................................... 48
5.2. Cc trng thi OpenGL .................................................................. 49
5.3. Xt mt chng trnh OpenGL ti thiu ......................................... 50
5.4. nh ngha v v im ................................................................... 53

5.5. nh ngha v v ng ................................................................. 56


5.6. nh ngha v v a gic ................................................................ 61
5.7. Tng kt......................................................................................... 74

Chng 6: Cc php binhnh OpenGL 75


6.1. Xy dng i tng 3-D t cc a gic .......................................... 75
6.2. Php chiu ..................................................................................... 77
6.3. Php bin hnh i tng ............................................................... 79
6.4. Php bin i viewport .................................................................. 85
6.5. Tng kt......................................................................................... 88

Chng 7: Chiu sng i tng 3-D 89


7.1. Cc loi ngun sng ....................................................................... 89
7.2. nh ngha mt ngun sng ........................................................... 90
7.3. nh ngha tch cht vt liu .......................................................... 92
7.4. nh ngha cc php tuyn ............................................................. 95
7.5. Xc nh kiu bng v kch hot vic kim tra chiu su................ 97
7.6. nh ngha n chiu ..................................................................... 98
7.7. Th hin i tng 3-D c chiu sng........................................ 99
7.8. Bng mu logic .............................................................................. 103
7.9. Tng kt ...................................................................................... 107
Chng 8: To cnh 3-D

108

8.1. S dng cc php bin hnh OpenGL to cnh 3-D ................... 108
8.2. S dng cc stack ma trn .............................................................. 113
8.3. To o gic chuyn ng vi OpenGL ........................................... 117
8.4. Tng kt......................................................................................... 119
Chng 9: Anh v gn cu trc 119
9.1. Bitmap v nh OpenGL ................................................................. 120
9.2. Bitmap ph thuc thit b v bitmap c lp vi thit b ................ 125
9.3. nh dng DIB............................................................................... 125
9.4. Gii thiu lp Cdib ........................................................................ 129
9.5. Gn cu trc cho a gic ................................................................ 139

9.6. Tng kt......................................................................................... 147

Chng 10: Pha trn , gim hiu ng rng ca, v sng m 148
10.1. Pha trn ....................................................................................... 148
10.2. Gim hiu ng rng ca ............................................................... 154
10.3. Sng m ................................................................................... 157

Chng 11: Display List 160


11.1. nh ngha: .................................................................................. 160
11.2. Ti sao phi dng display list ....................................................... 160
11.3. Cc tnh cht ca display list. ....................................................... 162
11.4. Cc trng hp c th s dng display list. .................................. 162
11.5. Nhc im ca display list. ........................................................ 162
11.6. To v thc thi mt display list. ................................................... 163
11.7. Qun l bin trng thi trong display list ..................................... 164

Chng 12: Quadric. 164


PHN 2: M PHNG CC GII THUT HA 3 D VI OPENGL: 166
Chng 1: Tng quan: 166
1.1. Mt s khi nim lin quan: ........................................................... 166
1.2. Cc php bin i: ......................................................................... 167

Chng 2: Xy dng ng dng m phng thut gii: 169


2.1. Xy dng ng dngOpenGL .......................................................... 169
2.2. Cch lm vic ca ng dng .......................................................... 172
2.3. Bng k chng trnh: .................................................................... 179

Li M u

C cu rng mt hnh nh bng c nghn li ni . iu tht khng th ph


nhn. V r rng l nu hin th thng tin ch vi cc k hiu, ch ci, ch s
khng thi th khng th hp dn v d hiu nh khi c thm biu din ha K
thut ho cng l cng c khng th thiu trong cc ngnh khoa hc k thut,
gio dc, ngh thut, gii tr, qung co( din t my mc thit b, kin trc,
cu trc c th, thng tin thin vn a l, hnh nh minh ho..). Chnh v vy,
ha l mt vn c quan tm trong ngnh cng ngh thng tin.
Cng vi s pht trin ca tin hc, k thut ha trn my vi tnh, ngy
cng tr nn tinh xo. Giao din cc phn mm ngy nay tr nn thn thin, p
mt nh cc th hin ha. S h tr ca tin hc cho cc ngnh khc tr nn c
lc hn nh kh nng ha vi tnh. V th gii thc th c biu din mt cch
sinh ng, linh hot, y mu sc bng khng gian ba chiu.
Trong thnh cng ca k thut ha ngy nay khng th khng ni n s pht
trin vt bc ca tc phn cng ln h iu hnh. Nhng bn thn k thut
ha th c bc tin nhy vt t nhng php tnh ton hc phc tp n nhng th
vin ha c to sn. Cc th vin ny cho php gim nh thi gian v cng
sc ca ngi lp trnh; Bi vi chng, c c mt tc phm ha khng
i hi phi c mt kin thc hng hu v ng cong Bezier, B-spline, v hnh
hc, to bng, m ch ng dng cc hm to sn. Mt trong nhng th vin l
OpenGL, c xem l tiu chun thit k cng nghip cho ha ba chiu.
Mc tiu ca lun vn ny l tm hiu th vin ha ca OpenGL trong ha
ba chiu, ng thi cng c gng a ra mt ng dng ca OpenGL trong vic
minh ha cc gii thut ha ba chiu.
Tuy nhin, ti khng th khng trnh khi nhng hn ch v thiu st, nn rt
mong c s ch bo, gp ca qu Thy C v bn b.

PHN 1:

TM HIU TH VIN HA OPENGL


Chng1:S Lc v OPENGL
1.1.Lch S Pht Trin :
Nguyn thy, GL do Silicon Graphics Incorporated (SGI) thit k dng cho cc
trm lm vic (workstation) ha IRIS ca h. IRIS GL vi cc cu hnh phn cng
khc th c vn pht sinh.
OpenGL l kt qu n lc ca SGI nhm ci thin tnh tng thch ca IRIS GL.
Ngn ng mi ny c kh nng ca GL, ng thi m ngha l d dng tng thch
vi cc lai cu hnh phn cng, cng nh cc h iu hnh khc nhau.
Version1.0 ca OPENGL c gii thiu vo ngy 01/7/1992.
bo m tnh m , mi s nng cp OpenGL phi thng qua Uy Ban Xem Xt Kin
Trc OpenGL(OpenGL Architecture Review Board AEB) gm cc thnh vin sng lp l
SGI, Digittal Equipment Corporation, IBM ,Intel v Microsoft.ARB hp mi nm hai ln.

(Cc cng ty khc cng c th tham gia tho tun nhng khng c quyn b phiu ).
Open GL version1.1 c ARB thng qua vo thng 12/1995.
1.2. Khi Nim :
OpenGL c nh ngha l giao din phn mm cho phn cng ha . Thc
cht, OpenGL l mt th vin cc hm ha, c xem l tiu chun thit k cng
nghip cho ha ba chiu.
Vi giao din lp trnh mnh m, OpenGL cho php to cc ng dng 3-D phc
tp vi tinh vi, chnh xc cao, m ngi thit k khng phi nh vt vi cc ni cng
thc ton hc v cc m ngun phc tp. V do OpenGL l tiu chun cng nghip, cc
ng dng to t n dng c trn cc phn cng v h iu hnh khc nhau.
Cc mc sau s gii thiu cch nhn tng qut v cch lm vic ca OpenGL:
- Cc phn t ha c bn v lnh gii thiu v cc phn t ha c bn
(primitive) v s thc hin lnh
- Cch lm vic ca OpenGL cho bit cc lai thao tc ha m OpenGL kim
sot
- M hnh hot ng ni v m hnh client/server cho vic thng dch lnh
OpenGL
- Thao tc OpenGL c bn a ra mt m t mc cao v cch OpenGL x l d
liu v to ra hnh nh tng ng ln b im khung.
Cc phn t ha c bn v lnh:
Primitive c xc nh bi nhm ca mt hay nhiu vertex l im trong khng gian.
Mi vertex xc nh mt im, mt u on thng hay mt nh a gic. D liu (bao
gm ta vertex, mu sc, normal, texture v c xc nh loi cnh) kt hi vi vertex.
Khi x l primitive, mi cp vertex v d liu lin kt vi n c s l c lp vi cc
cp khc, theo th t v cng mt phng php. Ngoi l duy nht l trong trng hp
kh phn khut ca primirite(clipping). Khi , d liu vertex c sa v cc vertex
khc c to ra. Loi clipping tu thuc loi primirite m nhm vertex biu din.
Cc lnh lun lun c x l theo th t m n tip nhn, mt d c s tr hon
khng xc nh trc khi lnh c hiu lc. Ngha l mi primirite c v trn vn trc
khi lnh tip theo c hiu lc.
Cch lm vic ca OpenGL:
OpenGL l ngn ng ha theo th tc ch khng phi ngn ng m t.Thay v t
cc cnh v cch chng xut hin, OpenGL a ra cc bc cn thit c c s th
hin hay hiu qu nht nh. Cc bcny l cc li gi n giao din lp trnh ng
dng gm xp x 120 lnh v hm. Chng c dng v cc phn t ha c bn
nh im, ng v a gic trong khng gian ba chiu. Ngoi ra, OpenGL cn h tr
chiu sng, t bng, gn cu trc, to o gic chuyn ng v cc hiu qu c bit khc.
OpenGL khng c cc chc nng qun l ca s, tng tc vi ngi dng hay
xut nhp file. Mi trng ch (tc h iu hnh) c cc chc nng ny v chu trch
nhim thc hin cc bin php qun l cho OpenGL.
M hnh hot ng:
M hnh thng dch lnh OpenGL l client-server. M ng dng(vai tr client) a ra
cc lnh. Lnh c thng dch v s l bi OpenGL (vai tr server). Server v client c
th l trn cng mt my tnh khc nhau. Theo ngha ny, OpenGL l network-transparent

(tm dch l mng trong sut). Server duy tr nhiu ng cnh OpenGL, mi ng cnh l
mt trng thi OpenGL. Client c th ni vi bt c ng cnh no. Giao thc mng c
s dng c th l c lp ha da trn giao thc mng hin c (tc OpenGL dng trn
my c lp hay trn mi trng mng). Khng c lnh OpenGL no tip nhn vic nhp
d liu trc tip t ngi dng.
Cui cng, h thng ca s kim sot tc dng ca cc lnh OpenGL trn b m khung
qua cc thao tc:
- Quyt nh cc phn ca b m khung m OpenGL c th truy xut ti thi im cho
php.
- Truyn t cho OpenGL thng tin v cu trc cc phn .
- Nh vy, khng c lnh OpenGL no nh dng b m khung hay khi to OpenGL.
S nh dng b m khung c thc hin bn ngoi OpenGL trong s lin kt vi h
thng ca s. S khi to OpenGL c tin hnh khi h thng cp pht ca s cho vic
biu din.
Hnh 1.1
M hnh hot
ng c bn
ca OpenGL
Lnh OpenGL
Pha Client

OpenGL DLL
Pha Server

Server DLL
Win DLL
Thao tc OpenGL c bn:
Video Driver
S khi 1.2 tm tt cch OpenGL x l d liu. Cc lnh i vo pha tri s
v qua ng ng x l. Mt s lnh xc nh i tng hnh hc c v, v s khc
kim sot cch qun l i tng qua cc giai on s l khc nhau.

Hnh 1.2 S x l d liu ca OpenGL:


Danh
sch

Lnh
l

c
ng

Thao tc trn
vertex v
primitive

Rasterization

Thao tc
trn
fragme

B
m
khung

B nh
texture

Cc thao tc

Cc giai on s l khc nhau: pixel


Danh sch hin th thay v x l lp tc ton b cc lnh, mt s lnh c gom li
trong mt danh sch x l sau.
B c lng: c lng l qu trnh OpenGL sinh ra cc vertex v thng s t cc
phng trnh Bzier xc nh trc, cung cp mt phng cch hiu qu xp x hnh
hc cc b mt v ng cong bng cch nh gi cc lnh a thc ca gi tr a vo.
Cc thao tc trn vertex v s t hp ca primirite: OpenGL x l cc primirite hnh
hc (im, on thng v a gic). Nhng primirite ny c biu din bi cc vertex.
Cc vertex c bin i, chiu sng, v cc primirite c kh cc cc phn khut theo
viewport chun b rasterze.
Raterization: giai on resterize to ra mt chui cc a ch b m khung v cc
gi tr lin kt s dng hnh dng hai chiu ca im, on thng hay a gic. Cc
fragment to ra c cung cp cho qu trnh tip theo.
Cc thao tc trn fragment: l cc thao tc cui cng trn d liu, trc khi lu tr
d liu di dng cc pixel trong b m khung.
Cc thao tc ny bao gm vic cp nht (c iu kin) b m khung da trn gi tr
lu tr v gi tr va c, vic pha trn cc mu va c v mu lu tr, cng nh thao tc
mask v cc thao tc logic khc trn cc gi tr pixel.
D liu c th c a vo di dng cac pixel. Khi , sau giai on thao pixel,
d liu pixel.
Hoc c lu tr nh l b nh texture, dng cho giai on rasterizatrion.
Hay rasterize, vi kt qu cc fragment c kt hp vo trong b m khung, nu
chng pht sinh t d liu hnh hc.
1.3. Thnh Phn:
OpenGL gm 5 b hm :

B ht nhn c 115 hm c bn. Tn cc hm ny bt u bng GL. Windows


NT h tr 4 chng loi hm khc, bao gm th vin OpenGL utility(tn hm bt u bng
GLU), th vin OpenGL auxiliary(tn hm bt u bng AUX), b hmWGL (tn hm
bt u bng WGL), v cc hm WIN32 API (tn hm khng c tin t c bit).
B hm ht nhn cho php thit k cc hnh dng khc nhau, to cc hiu qu
chiu sng, kt hp antialiasing v gn cu trc, thc hin bin i ma trn
Do cc hm c bn c th hin nhiu dng khc nhau ty thuc vo loi d
liu m chng tip nhn, nn trn thc t c hn 300 nguyn mu (prototype) cc hm c
bn.
Th vin OpenGL utility gm cc hm cao cp. Cc hm ny n gin ho vic
s dng hnh nh cu trc, thc hin vic bin i ta mc cao, h tr tesselation a
gic, v biu din cc i tng c c s a gic nh hnh cu, hnh tr hnh da.
Th vin OpenGl auxiliary gm cc hm c bit dng n gin ha cc v d
lp trnh trong sch ch dn lp trnh OpenGL. Cc hm ph thuc platform ny thc hin
cc nhim v nh qun k ca s, iu khin xut/nhp, v cc i tng 3D nht nh.
Do cc hm ny c mc ch thit minh nn khng c dng trong cc m sn xut.
Cc hm WGLkt ni OpenGL vi WINdows NT, cho php ngi lp trnh
xy dng v chn la cc ng cnh biu din, to cc bitmap font, cc hm ny ch dng
trn Windows NT.
Cui cng, cc hm Win32 API c dng gii quyt cc nh dng im nh v
to b m i.

Chng2: Ha Hai Chiu GDI


OpenGL cung cp nhiu hm mnh m, lm n gin cc vic v cc hnh nh
phc tp. D vy, hiu OpenGL, cn c mt cht kin thc trong thc tin lp trnh
ha tiu chun. Bc u tin v mc tiu l tm hiu cch thao tc hnh nh hai chiu
GDI
Cc phn sau s gii thiu c s lp trnh ho 2-D :
- Ta cc v ta mn hnh
- S dng cc Vertex nh ngha mt hnh dng phng
- Tnh tin, co gin v quay
- S dng ma trn trong bin hnh 2-D
2.1.Ta Cc V Ta Mn Hnh:
k mt on thng trn mn hnh, ta thng gi cc hm nh v im u, sau
v on thng. V d cc hm MFC c gi l:
CclientDC dc(this)
dc.MoveTo(x,y)
dc.LineTo(x,y)
Mi quan tm y l vic biu din cc ta x,y.
Trong ta ca s, cng nh ta mn hnh, gc ta v tr gc tri trn, chiu
tng ca ta x v pha phi, chiu tng ta y i v pha di (hnh 2.1)
Tuy nhin, i tng ha c xc nh bi ta cc Vertex ca n trong h
cc (hnh2.2). Cc im khc bit gia hai ta ny l:
H cc xc nh chiu tng ta y l chiu i ln.

H cc cho php c ta m.
V nh vy, vn pht sinh khi biu din mt i tng c nh ngha trong h
cc. Trong ta mn hnh, ta li nhn c mt tam gic nh (hnh 2.4), nu vi m to
hnh nh sau :
CCLientDC dc(this)
dc.MoveTo(2,5);
dc.LineTo(5,2);
dc.LineTo(2,2);
dc.LineTo(2,5);
Do s khc bit gia mn hnh th hin v ta cc, cn c mt phng php
chuyn i gia chng. Thut ng ha gi l mapping cc im trong ta cc
sang ta mn hnh th hin i tng ng v tr.

Hnh 2.1 Ta mn hnh

Hnh 2.2 Ta cc

Hnh 2.3 Tam gic trong ta cc

Hnh 2.4 v tam gic khng c s


chuyn i gia ta cc v
ta mn hnh

Nu b qua vn ga tr m, th vic th hin im (x1,y1) trong ta cc


sang im (x2,y2) trong ta mn hnh i hi cng thc sau:
X2=X1;
Y2=maxY Y1;
D nhin, thc hin cng thc ny, trc ht cn bit kch thc hin ti ca ca
s, bng cch gi hm GetClientRect(). Hm ny in y cu trc RECT vi kch thc
ca s. S dng hm MFC, on m sau v tam gic cho ln ca s, mapping gia ta
cc v ta mn hnh:
Int triangle[6]={2,5,5,2,2,2,};
CCLientDC dc(this);
Int newX,newY,startX,startY;
RECT clientRect;
GetClientRect(&clientRect);
For (int x=0;x<3;++x)
{
newX = triangle[x*2];
newY = maxY triangle[x*2+1];
if(x = = 0)
{
dc. MoveTo(newX,newY);
startX = newX;
startY = newY;
}
else dc.LineTo(newX,newY);
}
dc.LineTO(startX,startY);
}
Dng u tin ca on m nh ngha mt mng chc cc ta cc tam
gic. Tip theo, on m tm ng cnh dng c ca ca s v khai bo cc bin cc b.
Cc bin newX, newY chc cc ta mn hnh ca mt im, cn startX, startY cha
ta mn hnh im u tin ca tam gic. Cu trc RECT, clientRect, cha kch thc
ca s. Sau hm GetClientRect() c gi in y cu trc clientRect. thnh phn
bottom cha chiu cao ca s. Gi tr ny c gn cho bin maxY.
Vng lp for lp i lp li mng ta tam gic. Trong thn vng lp cc ta
(x,y) c mapping gia ta cc v ta mn hnh .
im u tin l im bt u tam gic. Cc im tip theo c dng v ng thng
tam gic. Li gi LienTo() bn ngoi vng lp ni im cui cng vi im u tin.

2.2. nh Ngha Vertex V Kiu D Liu Hnh Dng:


Mt hnh phng th c xc nh bi mt tp hp cc vertex. Cc vertex ni vi nhau
bng cc on thng. Khi tt c vertex c ni th hon thnh hnh dng.
qun l cc kiu hnh dng khc nhau trong mt chng trnh c d dng,
cn nh ngha cp cu trc bao gm kiu d liu vertex.
Typedef struct vertex
{
int x, y;
//Cu trc ny ch n gin l lu tr
}VERTEX;

//cc ta cc vertex

V kiu d liu hnh phng


Typedef struct shape
{
int numVerts; //Gm mt s nguyn ch s lng
VERTEX*vertices; //vertex trong hnh v mt con tr
}SHAPE;

//tr n mng cu trc

Vi cc kiu d liu mi ny, ta c th vit an m v on thng tng qut hn


nh sau :
VERTEX triangleVerts[3]= {2,5,5,2,2,2}
SHAPE shape1 = {3,triangleVerts};
DrawShape(shape1);
Void DrawShape(SHAPE& shape1)
{
CclientDC dc (this);
Int newX,newY,startX,startY;
RECT clientRect;
GetClientRect(&clientRect);
Int maxY = clientRect.bottom;
For (int x =0 ;x<shape1.numVerts;++x)
{
newX shape1.vertices[x].x;
newY = maxY shape1.vertices[x].y;
if(x = = 0)
{
dc.MoveTo(newX,newY);
startX = newX;
startY = newY;
}
else dc.LineTo(newX,newY);
}
dc.LineTo(startX,startY);

}
Do DrawShape() c tng qut ha lm vic vi cu trc SHAPE, hm
ny c th v mi loi hnh phng.V d v mt hnh ch nht, th shape1 c
nh ngha nh sau:
VERTEX rectangleVerts[4]= {10,10,10010, 100 ,50,10,50};
SHAPE shape1 = {4,rectangleVerts};
Hay i vi mt a gic su cnh nh sau:

Hnh 2.5
VERTEX shapeVerts[6]= {10,10,75,5,100,20,100,50,50,50,25};
SHAPE shape1 = {6,shapeVerts};
2.3.Cc Php Bin Hnh:
Mt hnh phng c to bng cch nh ngha vertex ca n trong ta cc,
mapping gia ta cc v ta mn hnh, ri v cc an thng ni cc vertex.
Tuy nhin, y ch l s khi u. v hnh mi ni trn mn hnh v theo mi
hng, hnh nh cn c thao tc theo nhiu cch khc nhau. Cc thao tc nh vy
gi l cc php bin hnh, bao gm tnh tuyn, co gin v quay.
2.3.1.Php Tnh Tin:
Tnh tin mt hnh n v tr mi ch n gin l cng hoc tr ta ca
mi vertex vi mt gi tr. Tam gic trong hnh 2.6 c tnh tin 3 n v theo
trc x v 2 n v theo trc Y.

Hnh 2.6: Tnh tin mt tam gic


Gi s cn tnh tin 20 n v theo trc X v 30 n v theo trc y, mt tam gic c
nh ngha nh sau:
VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
Cng thc tnh tin mi vertex l :

X2 = X1 + xTranslation;
Y2 = Y1 + yTranslation;
Trong chng trnh ton b php tnh tin nh sau:
VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
DrawShape(shape1);
Translate(shape1,20,30);
Void Traslate(SHAPE& shape,intxTrans,int yTrans)
{
for(int x =0;x< shape.numVerts;++x)
{
shape.vertices[x].x+ xtrans;
shape.vertices[x].y+ ytrans;
}
}
Void DrawShape(SHAPE& shape1)
{
CclientDC dc (this);
Int newX, newY, startX, startY;
RECT clientRect;
GetClientRect(&clientRect);
Int maxY = clientRect.bottom;
For (int x =0 ;x<shape1.numVerts;++x)
{
newX shape1.vertices[x].x;
newY = maxY shape1.vertices[x].y;
if(x = = 0)
{
dc.MoveTo(newX,newY);
startX = newX;
startY = newY;
}
else dc.LineTo(newX,newY);
}
dc.LineTo(startX,startY);
}
Hm Translate() c cc i s l tham chiu n cu trc SHAPE, lng
tnh tin x v lng tnh tin y. N s dng vng lp for gn lng tnh tin
trong ta (x,y) ca mi vertex.
2.3.2 .Php Co Gin:

Thay v cng hoc tr cc vertex vi mt gi tr nh khi tnh tin, co gin


mt hnh l nhn cc vertex ca hnh vi mt h s co gin. Hnh 2.7 biu din
mt tam gic gin hai ln (h s co gin l 2).

Hnh 2.7: Co gin mt tam gic


Ch rng khng ch ring hnh, m ton b h ta co gin. Tc l, mt
im c ta x l 2 n v, s l 4 n v khi co gin.
Gi s cn gin 4 ln (h s co gin l 4 ) mt tam gic c nh ngha nh sau:
VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
Th cng thc co gin mi vertex l :
X2 = X1*scaleFactor;
Y2 = Y1*scaleFactor;
on m php co gin s nh sau:
VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
Scale(shape1,4);
DrawShape(shape1);
Void Scale(SHAPE& shape,float scaleFactor)
{
for(int x =0;x< shape.numVerts;++x)
{
shape.vertices[x].x+=(int)(shape.xerticse[x]x*scaleFactor);
shape.vertices[x].y+=(int)(shape.xerticse[x]y*scaleFactor);
}
}
Void DrawShape(SHAPE& shape1)
{
CClientDC dc (this);
Int newX,newY,startX,startY;
RECT clientRect;
GetClientRect(&clientRect);
Int maxY = clientRect.bottom;
For (int x =0 ;x<shape1.numVerts;++x)
{
newX shape1.vertices[x].x;

newY = maxY shape1.vertices[x].y;


if(x = = 0)
{
dc.MoveTo(newX,newY);
startX = newX;
startY = newY;
}
else dc.LineTo(newX,newY);
}
dc.LineTo(startX,startY);
}
Hm Scale() c cc i s l tham chiu n cu trc SHAPE v h s co
gin, th h s co gin s nh hn 1. Ch rng c th dng h s co gin khc
nhau i vi 2 ta :
Void Scale(SHAPE& shape, float xScale, float yScale)
{
for(int x =0;x< shape.numVerts;++x)
{
shape.vertices[x].x+=(int)(shape.xerticse[x]x*xScale);
shape.vertices[x].y+=(int)(shape.xerticse[x]y*yScale);
}
}
Trong trng hp ny, sau khi co gin, khng nhn c hnh ng dng.
Hnh 2.8 biu din vic co gin mt tam gic, vi h s co gin trc x bng 1 , v
h s co gin trc y bng 2.

Hnh 2.8: Co gin mt tam gic vi hai h s co gin khc nhau

2.3.3.Php Quay:
Quay mt hnh th rc ri hn tnh tin hay co gin, v phi dng n php
ton phc tp hn, phi tnh ton sin, cosin. Tuy nhin y ta ch p dng cng
thc quay, m khng tm hiu ti sau, lm g..
Hnh2.9 biu din vic quay 45 mt tam gic quanh gc ta .

Gi s cn quay mt tam gic 450 nh sau :


VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
Cc cng thc sau c p dng cho cc vertex trong tam gic:
RotatedX = x*cos(angle) y*sine(angle);
RotatedY = y*cos(angle) x*sine(angle);
t nhn c vertex sau:
VERTEX triangleVerts[3]= { -21,49,0,70,-56,84};
Ch rng trong c hai ta m, do tam gic quay sang phn m ca
trc x. Gi tr m c chp nhn trong ta cc, nhng khng th biu din
ln mn hnh. hin th tam gic cn tnh tin n sang phn dng ca trc x .
Ton b php quay v tnh tin s nh sau:
VERTEX triangleVerts[3]= { 20,50,50,50,20,100};
SHAPE shape1 = {3,triangleVerts};
Rotate(shape1,45);
Translate(shape1,100,0);
DrawShape(shape1);
Void Rotate(SHAPE& shape,int degrees)
{
int rotatedX,rotatedY;
double radians = 6.283185308/(360.0/degrees);
double c = cos(radians);
double c = sin(radians);
for(int x =0;x< shape.numVerts;++x)
{
rotatedX = (int) (shape.verticse[x]x*c
shape.vertices[x].y*s);
rotatedY = (int) (shape.verticse[x]y*c
shape.vertices[x].x*s);
shape.vertices[x].x = rotatedX;

shape.vertices[x].y = rotatedY;
}
}
Void Translate(SHAPE& shape1,int xtrans,int yTrans)
{
for(int x =0;x< shape.numVerts;++x)
{
shape.vertices[x].x += xTrans;
shape.vertices[x].y += yTrans;
}
}
Void DrawShape(SHAPE& shape1)
{
CClientDC dc (this);
Int newX,newY,startX,startY;
RECT clientRect;
GetClientRect(&clientRect);
Int maxY = clientRect.bottom;
For (int x =0 ;x<shape1.numVerts;++x)
{
newX shape1.vertices[x].x;
newY = maxY shape1.vertices[x].y;
if(x = = 0)
{
dc.MoveTo(newX,newY);
startX = newX;
startY = newY;
}
else dc.LineTo(newX,newY);
}
dc.LineTo(startX,startY);
}
Hm Rotate( ) nhn tham s l tham chiu n cu trc SHAPE v gc quay().
Cng vic u tin ca n l i sang radian, do radian l n v o m cc hm
sin( ), v hm cosin( ) ca visual c++ yu cu. Vi gc quay dng th hnh s
quay ngc chiu kim ng h, v ngc li
Cng ging nh cc hm Translate( ) v Scale( ), hm Rotate( ) s dng vng lp
for tnh ta (x,y) cho tng vertex.
2.4. S Dng Ma Trn Trong Cc Php Bin Hnh:
Mt chng trnh ha thng thc hin tt c cc php tnh ton trn vertex ca
i tng trc khi th hin i tng ra mn hnh. C th gi cc hm Translate( ),
Scale( ), v Rotate( ) cho cc php tnh ny. Tuy nhin, vic thc hin nhiu php tnh

nh vy cho nhiu vertex s tiu ph thi gian. cng l l do m ma trn thng


c dng cho cc php bin hnh.
Mt ma trn n gin l mt bng s sp xp trn cc hng v ct. Ging nh mng
trong lp trnh, kch thc ma trn c nh ngha trn s hng v ct m n c. v d
ma trn 3*4 l ma trn c 3 hng v 4 ct:
4724
4673
4522
Trong chng trnh ma trn c trnh bi nh sau:
Int matrix[3][4]=
{
4,7,2,4,
4.6.7.3.
4,5,2,2,
};
Thun li ca ma trn trong lp trnh ha l c th trnh by nhiu php bin hnh
vi mt ma trn n. Ngha l mi ma trn n cha mi gi tr cn thit ng thi
dng trong tnh tin, co gin v quay mt hnh. thc hin iu th cn bit t
gi tr no vo ma trn v cn bit php nhn ma trn.
2.4.1.Cc Kiu D Liu Dng Trong Ha 2-D:
ha 2-D dng trong ma trn : 1*3 v 3*3.
Ma trn 1*3 l ma trn c bit , gi l vector. Vector cha cc gi tr x,y v w
th hin mt vertex. Vy kiu d liu vertex nh sau :
Typedef struct vector
{
int x,y,w;
}VECTOR;
Trong ,w l gi tr thng dng n gin ha thao tc ma trn, mt d
OpenGL i khi s dng t bit gi tr ny.Trong hu ht cc trng hp, w bng 1.
Ngha l vertex c biu din bi vector c dng: x, y, z Ma trn 3*3 cha cc gi tr
cn thit cho cc php bin hnh mt vertex (c biu din bng kiu d liu vector, tc
cng l mt ma trn ) Kiu d liu ma trn 3*3 nh sau:
Typedef double MATRIX3*3[3][3];
2.4.2.Cc Ma Trn Bin Hnh :
Bc u tin l cung cp cc gi tr thch hp cho ma trn. Gi tr c dng v
v tr ca n trong ma trn ph thuc kiu bin hnh.
Ma trn dng cho php tnh tin c dng:

1
0
0
0
1
0
xTrrans
yTrans
1
Vi cc bin xTrans v yTrans tng ng l s n v theo chiu ngang v dc
dng cho php tnh tin, (tng t nh khi dng cng thc tnh tin ). Trong chng trnh
ma trn ny c khi to nh sau:
MATRIX3*3 m;
m[0][0] = 1.0;
m[0][1] = 0.0;
m[0][2] = 0.0;
m[1][0] = 0.0;
m[1][1] = 1.0;
m[1][2] = 0.0;
m[2][0] = xTrans;
m[2][1] = yTrans;
m[2][2] = 1.0;
-

Ma trn dng cho php co gin c dng:


XScaleFactor 0
0
0
yScaleFactor
0
0
0
1

Vi cc bin xScaleFactor v yScaleFactor tng ng l co gin theo chiu


ngang v dc. Trong chng trnh, ma trn ny c khi to nh sau :
MATRIX3*3 m;
m[0][0] = xScaleFactor;
m[1][0] = 0.0;
m[2][0] = 0.0;
-

m[0][1] = 0.0;
m[1][1] = xScaleFactor;
m[2][1] = 0.0;

Cui cng ma trn dng cho php quay c dng :


Cos(radians)
sin(radians)
-sin(radians)
cos(radians)
0
0

m[0][2] = 0.0;
m[1][2] = 0.0;
m[2][2] = 1.0;

0
0
1

Vi bin radian l gc quay (n v radian). Trong chng trnh, ma trn ny c


khi to nh sau :
MATRIX3*3 m;
m[0][0] = cos(radians);
m[1][0] = -sin(radians);
m[2][0] = 0.0;

m[0][1] =sin(radians);
m[1][1] = cos(radians);
m[2][1] = 0.0;

m[0][2] = 0.2;
m[1][2] = 0.0 ;
m[2][2] = 1.0;

2.4.3.Kt Hp Cc Php Bin Hnh :


mc trc, tng php bin hnh c biu din bng cc cc ma trn ring bit.
Tuy nhin, nh ni, c th kt hp nhiu php bin hnh trong mt ma trn.
kt hp hai php bin hnh, ta nhn hai ma trn ca chng vi nhau Kt hp php
bin hnh tip theo bng cch nhn ma trn ca n vi ma trn nhn c php kt hp
trc. Hnh 2.10 biu din cc php bin hnh
Mt cch nhn khc c biu din hnh 2.12, nhng kt qu ca tng php kt hp cc
ma trn khng c th hin .

Ma tr n
k t

Cc vector
C a hnh

Hnh
bi n

c
i

nhn hai ma trn vi nhau, th s ct trc phi bng s hng ca ma trn sau.
Nh vy, ta c th nhn hai ma trn 1X3 v ma trn 3X3, hay nhn hai ma trn 3X3
vi nhau .
Hm sau nhn hai ma trn 3X3:
Void MultMatrix(MATRIX3X3& product,
MATRIX3X3& matrix1, MATRIX3X3& matrix2)
{
for (int x = 0; x < 3; ++y)
{
double sum = 0;
for (int z = 0; z < 3; ++z)
sum + = matrix1[x][z]*matrix2[z][y];
product[x][y] = sum;
}
}
Cc tham s ca hm trn bao gm mt ma trn cha kt qu nhn, v hai ma trn
tham gia php nhn .V d v cch s dng hm nh sau:
MATRIX3X m1,m2,m3;
m[0][0] = 1.0;
m[1][0] = 0.0;
m[2][0] = 0.0;

m[0][1] = 0.0;
m[1][1] = 1.0;
m[2][1] = 0.0;

m[0][2] = 0.0;
m[1][2] = 0.0;
m[2][2] = 1.0;

m[0][0] = 9.0;
m[0][1] = 8.0;
m[0][2] = 7.0;
m[1][0] = 6.0;
m[1][1] = 5.0;
m[1][2] = 4.0;
m[2][0] = 3.0;
m[2][1] = 2.0;
m[2][2] = 3.0;
MultiMatrix(m3,m1,m2);
on m khai bo ba ma trn 3X3 l m1, m2, m3. Sau khi to m1, m2, ri gi
hm MulMatrix() nhn m1 vi m2, v lu tr kt qu trong m3. Do m1 l ma trn n
v, kt qu cha trong m3 s c cng gi tr nh trong m2.

Ma trn n v i cp n c nh ngha l loi ma trn ng cho nXm chiu, vi cc


phn t ng cho hnh n v:

I [ik],

vi ik

= 0 nu i k;
ik = 1 nu i = k;

Trong lp trnh ha, ma trn n v thng c dng khi to ma trn chnh


l ma trn dng kt hp cc php bin hnh. Vic khi to nh vy s chc chn khng
tn ti gi tr l trong ma trn .
2.4.4.Thc Hin Bin Hnh:
Sau khi kt hp cc php bin hnh, ta nhn c mt ma trn chnh cha cc gi tr
chnh xc cn thit ng thi tnh tin, co gin v quay hnh. Cng vic bin hnh by
gi ch n gin l nhn ma trn chnh vi cc vector ca hnh (xem hnh 2.10,2.11). V
nh vy cn mt hm khng ch nhn vector 1X3 vi ma trn 3X3, m nhn ma trn vi
ton b danh sch vector:
Void Transform(SHAPE& shape, MATRIX3X3& m)
{
int transformedX,transformY;
for (int x= 0; x <shape.numverts; ++x)
{
transformX = (int) (shape.vertices[x].x*m[0][0] +
shape.vertices[x].y*m[1][0] + m[2][0]);
transformY = (int) (shape.vertices[x].y*m[0][0] +
shape.vertices[x].x*m[1][0] + m[2][0]);
}
}
Hm trn c cc i s l tham chiu n cc cu trc SHAPE v tham chiu n
mng MATRIX3X3.
2.4.5.Mt S Hm Ma Trn Tin ch:
C hai hm ma trn tin ch thng c dng lm d dng hn vic s dng
ma trn trong lp trnh. Chng gm:
- Hm khi to ma trn theo ma trn n v:
MATRIX3X m1,m2,m3;
m[0][0] = 1; m[0][1] = 0;
m[0][2] = 0;
m[1][0] = 0; m[1][1] = 1;
m[1][2] = 0;
m[2][0] = 0; m[2][1] = 0;
m[2][2] = 1;
-

Hm sao chp ma trn:


Void intMatrix(MATRIX3X3& m)
{
for (int i=0; i <3; ++i)
for (int j=0; j <3; ++j)

dst[i][j] = src [i][j];


}
2.4.6.Cc Hm Bin Hnh Dng Ma Trn:
- Hm tnh tin :
Void Translate(MATRIX3X3& m,int xTrans,int yTrans)
{
MATRIX3X m1,m2;
m[0][0] = 1;
m[1][0] = 0;
m[2][0] = xTrans;

m[0][1] = 0;
m[1][1] = 1;
m[2][1] =yTrans0;

m[0][2] = 0;
m[1][2] = 0;
m[2][2] = 1;

MultMatrix(m2,m1,m);
CopyMatrix(m,m2);
}
Hm c i s l tham chiu n ma trn chnh (cha trng thi hin ti ca php bin
hnh) v cc gi tr tnh tin x, y. u tin, n to ma trn tnh tin ; Ri nhn ma trn tnh
tin vi ma trn chnh, lu kt qu trong ma trn cc b m2; Cui cng sao chp m2 tr
li ma trn chnh.
-

Hm co gin:
Void Scale(MATRIX3X3& m,double xScale,double yScale)
{
MATRIX3X m1,m2;
m[0][0] = xScale; m[0][1] = 0;
m[0][2] = 0;
m[1][0] = 0;
m[1][1] = yScale; m[1][2] = 0;
m[2][0] = 0;
m[2][1] =0;
m[2][2] = 1;
MultMatrix(m2,m1,m);
CopyMatrix(m,m2);

}
Hm quay:
Void Rotate(MATRIX3X3& m,int degrees)
{
MATRIX3X m1,m2;
If (degrees = = 0) return;
Double radians = 6.283185308/(360.0/ degrees);
Double c = cos(radians);
Double s = sin(radians);
m[0][0] = c;
m[0][1] = s;
m[0][2] = 0;
m[1][0] = -s;
m[1][1] = c;
m[1][2] = 0;
m[2][0] = 0;
m[2][1] =0;
m[2][2] = 1;

MultMatrix(m2,m1,m);
CopyMatrix(m,m2);
}
Hm quay c cc i s l tham chiu n ma trn chnh v gc quay(). u tin
n kim tra gc quay c bng khng hay khng. Nu gc quay bng khng, hm kt thc
loi tr, li chia cho 0. Nu khc khng, hm i ra radians v tnh sin, cosin. Tip
theo, Rotate khi to ma trn quay, nhn n vi ma trn chnh, lu kt qu vo ma trn
cc b m2. Cui cng, sao chp m2 tr li ma trn chnh.
By gi ta c mt b hm dng ma trn. Hy xt cch dng chng trong
bin hnh on m sau:
MATRIX3X3 m;
IntMatrix(m);
Translate(m,10,15);
Scale(m,0.5,0.5);
Rotate(m,45);
Transform(shape1,m);
DrawShape(shape1);
Trc tin on m khai bo mt ma trn bin hnh 3X3 l m. Sau gi hm
IntMatrix() khi to m theo ma trn n v. M s l:
1.0000000000000
0.0000000000000
0.0000000000000

0.0000000000000
1.0000000000000
0.0000000000000

0.0000000000000
0.0000000000000
1.0000000000000

Li gi hm Translate( ) kt hp m vi ma trn tnh tin cha cc gi tr 10 v


15. Matrn bin hnh m s l:
1.0000000000000
0.0000000000000
10.0000000000000

0.0000000000000 0.0000000000000
1.0000000000000 0.0000000000000
15.0000000000000 1.0000000000000

Sau khi gi hm Scale( ), m cha cc gi tr ca php tnh tin v co gin:


1.0000000000000
0.0000000000000
10.0000000000000

0.0000000000000
0.0000000000000
0.5000000000000
0.0000000000000
15.0000000000000 1.0000000000000

Cui cng sau li gi hm Rotate( ), m cha y cc php tnh tin v quay:


0.35355339055702 0.3535533906295 0.0000000000000
-o.35355339062953 0.35355339055702
0.0000000000000
10.000000000000
15.000000000000
1.0000000000000
Li gi hm Translate() p dng ma trn cho mt vertex ca shape1. Sau
Drawshape() v hnh bin hnh ln mn hnh.

Chng 3: Ha Ba Chiu GDI


Trong chng ny, chng ta s tm hiu:
- H ta cc ba chiu.
- nh ngha vertex cho i tng 3-D.
- Php chiu song song v php chiu phi cnh.
- Chuyn ng i tng 3-D.
3.1.H Ta Ba Chiu:
Mt i tng ba chiu th khng th biu din trong h ta hai chiu ch gm hai
trc x v y. to h ta mi, ta ch n gin thm mt trc z vo mt phng cc,
bin i thnh hnh khi. Mt d cc trc x, y, z c th hng theo mi phng, ta qui
nh trc x theo chiu ngang, trc y theo chiu ng, trc z theo phng i vo v ra mn
hnh. l hng trc logic cho nhiu chng trnh, xut pht t vic trc x v y chy
theo cc phng tng ng vi ta mn hnh.
3.2 .nh Ngha i Tng Ba Chiu:
Vic to mt hnh hai chiu ch n gin l nh ngha tp vertex ca n, ri ni cc
vertex vi nhau. Nhng i vi i tng 3-D, vn c php tp hn, bi v s lng
vertex l nhiu hn, i hi vic xc nh vic ni cc vertex hnh thnh ng i
tng yu cu. Do , i vi chng, khng ch nh ngha cc vertex, m cn phi nh
ngha cc cnh. Mt i tng 3-D c xy dng trn cc vertex v cnh c gi l
mt m hnh khung li (wireframe model).
nh ngha mt m hnh khung li cn danh sch cc vertex v cnh. Do , hin
nhin l cn mt s kiu d liu mi.
-Trc tin l kiu d liu nh ngha vertex ca i tng 3-D vi ba ta x, y,
z nh sau:
Typedef struct vertex
{
int x,y,z,w;
}VERTEX;
- v mt cnh, ta cn bit vertex khi u v vertex kt thc, sau ni chng
li vi nhau. Kiu d liu nh ngha cnh nh sau:
Typedef struct edge
{
UINT vertex1,vertex2;
}EDGE;
Vi vertex1 l im xut pht cnh, v vertex2 cui.
- Kiu d liu ca m hnh khung li nh sau:
Typedef struct model
{
UINE numverts;
VERTEX* vertices;
UINE numEdges;
EDGE*edges;

}MODEL;
Nh vy, cu trc MODEL bao gm hai s nguyn khng du cha vertex v cnh
i tng, mt con tr ch n kiu d liu VERTEX cha a ch ca danh sch vertex,
v m con tr ch n kiu d liu EDGE cha a ch ca danh sch cnh.

Hnh 3.1Hnh khi:

S dng cc kiu d liu trn cho khi vung,


vi s th t cc nh nh hnh 3.1. Ta cc
nh ln lc l (0,4,0), (4,4,0), (4,4,-4), (0,4,4), (0,0,0,), (4,0,0), (4,0,-4),(0,0,-4).
Danh sch vertex s nh sau :
VERTEX cubeVerts[8] =
{
0,4,0,
4,4,0,
4,4,-4,
0,4,-4,
0,0,0,
4,0,0,
4,0,-4,
0,0,-4,
}
Ch rng ta z ca i tng cho bng 0 hoc m, do chiu tng ta z
hng ra khi mn hnh .
Cc ta dng nh ngha mt m hnh khung li, nh trong cu trc cubeverts
trn, th c xem l cc ta cc b. Ta cc b tr thnh ta th gii khi
chng trnh s dng cc php tnh tin co gin hoc quay v bin m hnh. Cui cng,
chng trnh ha bin i cc ta th gii thnh ta mn hnh c th th hin
m hnh ln mn hnh.
Danh sch cnh ca khi vung trn nh sau :
EDGE cubeedges[12]=
{
1,2,
2,3,
3,4,
4,1,
5,6,
6,7,
7,8,
8,5,
5,1,
6,2,

7,3,
8,4,
};
Bn cp ta u to thnh nh hnh khi. Bn cp ta tip theo hnh thnh
y hnh khi. Bn cp to cui cng ni nh v y hnh khi vi nhau.
Vi danh sch vertex v danh sch cnh c, khi vung trn hnh 3.1 c nh
ngha nh sau:
MODEL cube = {8,cubeVerts,12,cubeEdges};
3.3.Cc Phng Php Th Hin 3-D Ln Mn Hnh:
Mt i tng 3-D c xc nh bi cc ta x,y,z,nhng mn hnh th c
biu din ch vi cc ta x, v y. Vy bng cch no c th biu din mt i tng
3-D ln mn hnh ?
C hai phng php thc hin vn trn l php chiu song song v php chiu
phi cnh.
3.3.1.Php Chiu Song Song:
Vi php chiu song song, mt i tng 3-D c th hin ln mn hnh bng cch
b qua cc ta z. Kt qu l mt hnh 2-D n gin. Nh vy, vi trng hp khi
vung, hnh nh th hin trn mn hnh ch l mt hnh vung. Hm v khi vung s
dng php chiu song song nh sau :
Void DrawModel (CDC* pDC, MODEL& mode)
{
int newX,int newY;
RECT clientRect;
GetClientRect (&clientRect);
Int maxY = clientRect.bottom;
For (UINT I=0; I<model.numEdges; ++i)
{
UINT vertNum = model.edges[i].vertex1;
NewX = model.vertices[vertNum -1].x;
NewY = maxY model.vertices[vertNum -1].y 1;
pDC ->MoveTo(newX,newY);
vertNum = model.edges[i].vertex2;
newX = model.vertices[vertNum 1].x;
newY = maxY model.vertices[vertNum -1].y 1;
pDC -> LineTo(newX,newY);
}
}
Hm trn gi GetClientRect() xc nh ta Y ln nht ca ca s. Sau
dng vng lp for v cc cnh ca i tng. Bn trong vng lp, hm tnh s hiu ca
vertex dng lm im u ca cnh, ri dng s tm cc ta X, Y ca vertex.
Cc ta ny c dng trong li gi n MoveTo() xc nh v tr im u. Cc
ta X, Y, ca im th hai c tm bng cch tng t, sau dng trong hm gi
n LineTo() v cnh:

3.3.2 .Php Chiu Phi Cnh:


Php chiu song song khng th s dng, nhng n khng mang li mt kt qu
va , tr khi dng cho mt chng trnh phc tho. Mt yu t then cht ca hnh nh 3D l chiu su nh. Ao gic m c to bng cch dng php chiu phi cnh, lm cho
i tng xa c v nh hn i tng gn . V d hnh 3.2 biu din hnh chiu phi
cnh ca khi vung, khi quan st t mt trc, gc di tri.

Hnh 3.2 v khi vung vi php


chiu phi cnh
Cc cng thc dng cho php chiu phi cnh :
Double t 1.0/(1.0 zCoord / eye);
PerspX = (int) ( xCoord * t);
PerspY = (int) ( yCoord * t);
Bin t cha gi tr co gin cc ta X v Y trn c s ta Z . Ta Z cng
nh (cng xa gc ta ), th tc dng co gin cng ln . Cc bin xCoord, yCoord v
zCoord cha cc ta vertex. Cc bin perspX, prspY cha ta mn hnh ca vertex
sau php chiu phi cnh. Bin eye xc nh mc tc ng ca php chiu trn m
hnh. Khi quan st i tng cng gn (eye cng nh) th hiu qu php chiu cng ln .

Hnh 3.3 Hnh chiu phi


cnh khi quan st gn(eye nh)

Hnh 3.4 Hnh chiu phi cnh


khi quan st xa (eye ln)

Hm gn php chiu phi cnh cho cc vertex ca mt m hnh khung li nh


sau :
Void PerspProject (MODEL& model, double eye)
{
for (UINT I =0; I<model.numVerts; ++i)
{
int xCoor = model.vertices[i].x;
int yCoor = model.vertices[i].y;
int zCoor = model.vertices[i].z;
double t = 1.0/(1.0 zCoor/ eye);
model.vertices[i].x = (int) (xCoor *t);
model.vertices[i].y = (int) (yCoor *t);

}
}
Hm trn c cc i s l tham chiu n cc cu trc MODEL v gi tr eye dng
tnh ton t. PerspProject()dng vng lp for gn php chiu phi cnh cho tng vertex
ca m hnh.
on m v d sau cho thy cc nh ngha m hnh, gn php chiu v v i tng:
VERTEX cubeVerts[8] =
{0,
100,
0,
1,
100, 100,
0,
1,
100, 100,
-100, 1,
0,
100, -100, 1,
0,
0,
0,
1,
100, 0,
0,
1,
100, 0,
-100, 1,
0,
0,
-100, 1];
EDGE cubeEdges[12] =
{ 1,2,
2,3,
3,4,
4,1,
5,6,
6,7,
7,8,
8,5,
5,1,
6,2,
7,3,
8,4};
MODEL cube;
Cube.numVerts = 8;
Cube.vertices = cubeVerts;
Cube. numEdges = 12;
PerspProject (cube, 200);
DrawModel (pDC, cube);
3.4.Bin Hnh i Tng 3-D:
Nh vy v mt i tng 3-D th khng kh. Nhng vi gc nhn pha trc,
gc di tri nh hnh 3.2 th cng khng p g. c mt gc nhn khc, ta cn bin
hnh i tng .
Vic bin hnh i tng 3-D khng khc my so vi bin hnh i tng 2-D, ch n
gin l ch xt thm ta z . Ma trn bin hnh dng trong trng hp ny c kch thc
4x4, vi kiu d liu nh sau:
Typedef double MATRIX4x4[4][4];
Cc hm InitMtrix(), CopyMatrix(), MultMatrix() by gi nh sau:
Khi to ma trn:

Void InitMatrix(MATRIX4x4& m)
{
m[0][0] = 1;
m[0][1] = 0;
m[0][2] = 0;
m[0][3] = 0;
m[1][0] = 0;
m[1][1] = 1;
m[1][2] = 0;
m[1][3] = 0;
m[2][0] = 0;
m[2][1] =0;
m[2][2] = 1;
m[2][3] = 0;
m[3][0] = 0;
m[3][1] = 0;
m[3][2] = 0;
m[3]3[] = 1;
}
Hm sao chp ma trn :
Void CopyMatrix(MATRIX4x4& src)
{
for (int =0; I<4; ++i)
for(int j =0; j<4; ++j)
dst[i][j];
}
Hm nhn ma trn:
Void MultMatrix(MATRIX4x4&product,MATRIX4x4&
matrix1,MATRIX4x4& matrix2)
{
for (int x=0; x<4; ++x)
for(int y=0; y<4; ++y)
{
double sum =0;
for (intz 0; z<4; ++z)
sum +=matrix[x][z]* matrix2[z][y];
product[x][y] = sum;
}
}
3.4.1.Php Tnh Tin 3-D:
Ma trn tnh tin:
1
0
0
0
0
1
0
0
0
0
1
0
xTrans
yTrans
zTrans
1
Hm tnh tin:
Void Translate(MATRIX4x4& m,int xTrans,yTrans,zTrans)
{
m[0][0] = 1;
m[0][1] = 0;
m[0][2] = 0;
m[1][0] = 0;
m[1][1] = 1;
m[1][2] = 0;
m[2][0] = 0;
m[2][1] =0;
m[2][2] = 1;
m[3][0] = xTrans;
m[3][1] = yTrans;
m[3][2] = zTrans;
MultMatrix(m2,m1,m);
CopyMatrix(m,m2);
}
3.4.2 .Php Co Gin:

m[0][3] = 0;
m[1][3] = 0;
m[2][3] = 0;
m[3]3[] = 1;

Ma trn co gin:
XFactor
0
0
YFactor
0
0
0
yTrans

0
0
ZFactor
zTrans

0
0
0
1

Hm co gin:
Void Scale(MATRIX4x4& m,double xScale,yScale,zScale)
{ MATRIX4x4 m1,m2;
m[0][0] = xScale;
m[0][1] = 0;
m[0][2] = 0;
m[1][0] = 0;
m[1][1] = yScale;
m[1][2] = 0;
m[2][0] = 0;
m[2][1] =0;
m[2][2] = zScale;
m[3][0] = 0;
m[3][1] = 0;
m[3][2] = 0;
MultMatrix(m2,m1,m);
CopyMatrix(m,m2);

m[0][3] = 0;
m[1][3] = 0;
m[2][3] = 0;
m[3]3[] = 1;

}
3.4.3. Php Quay 3-D:
Khi quay mt hnh phng, thc cht l ta quay n quanh trc z. i vi i tng
3-D, ta c th quay n quanh 3 trc x, y, z. Th nhng khng c mt ma trn n gin c
th thc hin 3 php quay cng mt lc. Thay vo , mi php quay coi nh mt php
bin hnh ring bit.
a) Quay Quanh Trc Z:
Ma trn quay quanh trc z:
Cos(radians)
sin(radians)
-sin(radians)
cos(radians)
0
0
0
0

0
0
1
0

0
0
0
1

Hm quay quanh trc z:


Void Rotate(MATRIX4x4& m,int zAngle)
{
if (zAngle = =0) return;
double radians = 6.383185308 / (360.0 / zAngle);
double c = cos(radians);
double s = sin(radians);
m[0][0] = c; m[0][1] = s;
m[0][2] = 0;
m[0][3] = 0;
m[1][0] = -s; m[1][1] = c;
m[1][2] = 0;
m[1][3] = 0;
m[2][0] = 0; m[2][1] = 0;
m[2][2] = 1;
m[2][3] = 0;
m[3][0] = 0; m[3][1] = 0;
m[3][2] = 0;
m[3]3[] = 1;
MultMatrix(m2,m1,m);
CopyMatrix(m,m2);
}

b) Quay Quanh Trc X:


Ma trn quay quanh trc x:
1
0
0
0
0
cos(radians)
sin(radians)
0
0
-sin(radians)
cos(radians)
0
0
0
0
1
Hm quay quanh trc X:
Void Rotate(MATRIX4x4& m,int zAngle)
{
if (zAngle = =0) return;
double radians = 6.383185308 / (360.0 / zAngle);
double c = cos(radians);
double s = sin(radians);
m[0][0] = 1; m[0][1] = 0;
m[0][2] = 0;
m[1][0] = 0; m[1][1] = c;
m[1][2] = s;
m[2][0] = 0; m[2][1] =-s;
m[2][2] = c;
m[3][0] = 0; m[3][1] = 0;
m[3][2] = 0;

m[0][3] = 0;
m[1][3] = 0;
m[2][3] = 0;
m[3]3[] = 1;

MultMatrix(m2,m1,m);
CopyMatrix(m,m2);
}
c) Quay Quanh Trc Y:
Ma trn quay quanh trc y:
cos(radians)
0
-sin(radians)
0
1
0
sin(radians)
0
cos(radians)
0
0
0
Hm quay quanh trc Y:
Void Rotate(MATRIX4x4& m,int zAngle)
{
if (zAngle = =0) return;
double radians = 6.383185308 / (360.0 / zAngle);
double c = cos(radians);
double s = sin(radians);
m[0][0] = c; m[0][1] = 0;
m[0][2] = -s;
m[0][3] = 0;
m[1][0] = 0; m[1][1] = 1;
m[1][2] = 0;
m[1][3] = 0;
m[2][0] = s;
m[2][1] = 0;
m[2][2] = c;
m[2][3] = 0;
m[3][0] = 0;
m[3][1] = 0;
m[3][2] = 0;
m[3]3[] = 1;
MultMatrix(m2,m1,m);
CopyMatrix(m,m2);

Chng 4: Chng Trnh OpenGL Ti Thiu

0
0
0
1

Chng ny trnh by cch khi to ng dng OpenGL v cch kt hp OpenGL


vo mt chng trnh MFC :
_ Cc yu cu ca mt chng trnh OpenGL ti thiu .
_ Cc kiu d liu v c php ca lnh OpenGL.
_ Cch to ng cnh biu din v nh dng im v.
_ Cch thit lp mt chng trnh MFC cho OpenGL .
4.1.Cc Kiu D Liu OpenGL :
OpenGL nh ngha kiu d liu d dng thao tc trong chng trnh . Cc kiu
d liu ny c trnh by trong bng 4.1.
Bng 4.1 : Cc kiu d liu OpenGL & hu t tng ng ca lnh
Kiu d liu OpenGL
Glbyte
Glshort
GLint,GLsizei
Glfloat,GLclampf
Gldouble,Glclampd
Glubyte,Glboolean
Glushort
Gluint, GLenum,
Glbitfield
Glvoid
HGLRC

Kiu d liu tng ng ngha


trong C
Signed char
S nguyn 8 bit
Short
S nguyn 16 bit
Long
S nguyn 16 bit
Float
Du chm ng 32 bit
Double
Du chm ng 64 bit
Unsigned char
Char khng du 8 bit
Unsigned short
S nguyn khng du 16 bit
Unsigned long
S nguyn khng du 32 bit
Void
HGDIOBJ

Hm khng i s hoc
khng tr v mt gi tr
Handle ca di tng GDI

4.2. Ng Cnh Biu Din :


Mi chng trnh trn Windows u phi s dng ng cnh dng c (DC,Device
Context), l cu trc d liu cha ng thng tin v cch m d liu ha c th hin
trn ca s. Ng cnh dng c xc nh mu sc bt v v c, kiu v, ni dung bng
mu, kiu mapping (kiu th hin cc phn t ca khng gian ta ngun ln khng
gian ta ch), v cc thuc tnh khc m Windows cn bit th hin thng tin
ha.
OpenGL cng s dng ng cnh dng c nh mi chng trnh Windows khc.
Nhng ng thi phi s dng ng cnh biu din (RC,Rendering Context). Ton b lnh
OpenGL u phi qua ng cnh biu din. Mi thread thc hin li gi OpenGL phi c
mt ng cnh biu din hin hnh. Ng cnh biu din kt ni OpenGL vo h thng ca
s ca Windows NT va Windows95. ng dng s xc nh ng cnh dng c khi n to
ng cnh biu din. Ng cnh biu din ny ph hp vi thut v trn cc ng dng
ch nh bi ng cnh dng c. c bit l ng cnh biu din c cng nh dng im v
(pixel format) nh ng cnh dng c . Mc d vy, Ng cnh biu din khng phi l ng
cnh dng c . Ng cnh dng c cha cc thng tin thch hp i vi GDI ca Windows

NT v Windows. Cn ng cnh biu din cha cc thng tin thch hp i vi OpenGL .


Mt li gi GDI phi xc nh r rng nh mt ng cnh dng c. V mt li gi
OpenGL phi xc nh r rng mt ng cnh biu din .
Mt thread thc hin li gi OpenGL phi c mt ng cnh biu din hin hnh.
Nu ng dng tin hnh li gi OpenGL t mt thread khng c ng cnh biu din, th
li gi khng hiu lc. Thng thng, ng dng to ng cnh biu din, gn ng cnh
l ng cnh biu din hin hnh ca thread, ri gi hm OpenGL. Khi kt thc vic gi
hm OpenGL, ng dng tho b ng cnh biu din khi thread, v xa n. Mt ca s
cng mt lc c th c nhiu ng cnh biu din, nhng ch mt trong s hin hnh v
c tc dng.
Mt ng cnh biu din hin hnh th c mt ng cnh dng c kt hp. Ng cnh
dng c khng cn phi l ng cnh dng c dng khi ng cnh biu din c to ra,
nhng phi tham chiu n cng mt dng c v c cng nh dng im v.
Mt thread c duy nht mt ng cnh biu din hin hnh.V mt ng cnh biu
din l hin hnh cho mt thread duy nht .
Mi li gi hm OpenGL tim n mt ng cnh biu din. Trong khi i vi ng
cnh dng c, mi hm GDI cn mt handle, th i vi ng cnh biu din, ch cn
handle khi to ng cnh biu din hin hnh.

Bng 4.2 : Cc hm WGL qun l ng cnh biu din


Tn hm
WglCreateContext ()
WglDeleteContext ()
WglGetCurrentContext
()
WglGetCurrentDC ()
WglMakeCurrent ()

Chc nng
To mt ng cnh biu din mi
Xa ng cnh biu din
Tr handle v ng cnh biu din hin hnh
Ly handle ca ng cnh dng c lin kt vi ng cnh
biu din hin hnh
Thit lp ng cnh biu din hin hnh

4.3.nh dng im v :
Trc khi to ng cnh biu din, chng trnh phi thit lp nh dng im v
cha cc thuc tnh ca b mt v. Cc thuc tnh ny bao gm ch mu l RGBA hay
ch mc, b m im v l n hay i, s lng cc bit dng trong b m chiu su v
b m stencil, cng cc thng tin ha OpenGL khc .
Bng 4.3 : Cc hm Win32 qun l cc nh dng im v
Tn hm
ChoosePixelFormat ()
DescribePixelFormat ()
GetPixelFormat ()
SetPixelFormat ()

Chc nng
Tr v mt nh dng im v ph hp nht vi nh
dng im v yu cu
Ly thng tin v nh dng im v cho
Ly nh dng im v ca ng cnh dng c cho
Thit lp nh dng im v ca ng cnh dng c
cho

4.3.1.Cu Trc PIXELFORMATDESCRIPTOR:


Mi thit b hin th OpenGL h tr mt s nh dng im v ring. D nhin, cc
nh dng im v ny da trn kh nng thit b. Cc thuc tnh ca mt nh dng im
v ring bit th c miu t bi cu trc PIXELFORMATDESCRIPTOR, gm 26
trng thng tin. Win32 nh ngha cu trc ny nh sau :
Typedef struct tag PIXELFORMATDESCRIPTOR
{ WORD nSize;
WORD nVersion;
DWORD dwFlags;
BYTE iPixelType;
BYTE cColorBits;
BYTE cRedBits;
BYTE cRedShift;
BYTE cGreenBits;
BYTE cGreenShift;
BYTE cBlueBits;
BYTE cBlueShift;

BYTE cAlphaBits;
BYTE cAlphaShift;
BYTE cAccumBits;
BYTE cAccumRedBits;
BYTE cAccumGreenBits;
BYTE cAccumBlueBits;
BYTE cAccumAlphaBits;
BYTE cDepthBits;
BYTE cStencilBits;
BYTE cAuxBuffer;
BYTE iLayerType;
BYTE bServered;
DWORD dwLayerMask;
DWORD dwVisibleMask;
DWORD dwDamageMask;
} PIXELFORMATDESCRIPTOR,* PPIXELFORMATDESCRIPTOR,
FAR * LPPIXELFORMATDESCRIPTOR
Khi thit lp nh dng im v ca ng cnh dng c, th cu trc
PIXELFORMATDESCRIPTOR c in y, v a ch ca n c dng lm i s
cho hm SetPixelFormat () .

Bng 4.4 :Cc thnh phn ca cu trc PIXELFORMATDESCRIPTOR


Thnh phn
Nsize
Nversion
DwFlags
IpixelType

CColorBits

cRedBits
cRedShift
cGreenBits
cGreenShift
cBlueBits
cBlueShift
cAlphaBits
cAlphaShift
cAccumBits
cAccumRedBits
cAccumGreenBits
cAccumBlueBits
cAccumAlphaBits
cDepthBits
cStencilBits
cAuxBuffer
iLayerType

bServered
dwLayerMask
dwVisibleMask
dwDamageMask

M t
Kch thc tnh bng byte ca cu trc . c th thit lp
bng sizeof(PIXELFORMATDESCRIPTOR).
S phin bn (version ) ca cu trc , hin bng 1.
Cc c c tnh cho nh dng im nh (bng 4.6)
M
t
d
liu
mu
ca
im
v
:
- PFD_TYPE_RGBA :i vi ch mu RGBA
- PFD_TYPE_INDEX i vi ch mu ch mc
S bit dng th hin mt mu . N quyt nh s mu th
hin . V d 8 bit th hin c 256 mu . i vi ch
mu RGBA, th khng tnh n alpha bitplane.i vi
ch mu ch mc , cColorBits xc nh kch thc b
m mu .
S bit trong b m mu RGBA
Tng di cc bitplane trong b m mu RGBA
S bit xanh l trong b m mu RGBA
Tng di cc bitplane xanh l trong b m mu
RGBA
S bit xanh dng trong b m mu RGBA
Tng di cc bitplane xanh dng trong b m mu
RGBA
S bit alpha trong b m mu RGBA . Khng dng trn
microsoft windows
Tng di cc bitplane alpha trong b m mu RGBA.
Khng dng trn microsoft windows
S bitplane trong b m tch ly
S bit trn mt pixel trong b m tch ly
S bit xanh l trn mt pixel trong b m tch ly
S bit xanh dng trn mt pixel trong b m tch ly
S bit alpha trn mt pixel trong b m tch ly
S bitplane trong b m chiu su
S bitplane trong b m stencil
S b m ph .khng dng trn microsoft windows
Xc nh kiu lp .trn Microsoft Windows l
PFD_MAIN_PLANE . Ngoi ra cc kiu lp khc l
FPD_OVERLAY_PLANE
v
PFD_UNDERLAY_PLANE
Dng d tr .thng bng 0
Hai trng hp ny i i vi nhau xc nh mt lp
che mt lp .Trn Microsoft Windows khng dng lp
Dng khi nhiu hn mt nh dng im v s dng
chung b m khung. Nu bitwise AND ca cc thnh

vin dwDamageMask ca hai khung nh dng im v


khc 0 , th chng s dng chung mt b m khung.
Bng 4.5 :Cc c c tnh cho nh dng im nh
C
PFD_DRAW_TO_BITMAP
PFD_DRAW_TO_WINDOW
PFD_DOUBLEBUFFER
PFD_GENERIC_FORMAT

PFD_NEED_PALETTE
PFD_NEED_SYSTEM_PALETTE

PFD_STEREO
PFD_SUPPORT_GDI

PFD_SUPPORT_OPENGL
PFD_DOUBLE_BUFFER_DONTC
ARE
PFD_STEREO_DONTCARE

M t
B m c dng v vo bitmap b nh
B m c dng v vo ca s trn mn
hnh hay thit b khc nh my in
Thit lp khi dng b m i.Khng dng
cng vi c PFD_SUPPORT_GDI.
Thit lp khi chn nh dng im v tng
qut ,l nh dng im nh c h tr
bi phn cng hay trnh iu khin thit b
Thit lp khi dng bng mu logic
Thit lp khi h thng s dng phn cng
OpenGL ch c h tr bi mt bng mu
phn cng duy nht . (Bng mu phn
cng mapping mt_mt vi bng mu
logic)
Thit lp khi chn b m lp th.khng
dng trn Microsoft Windows
B m h tr cc hm ha GDI
.Khng
dng
cng
vi
c
PFD_DOUBLEBUFFER
B m h tr cc hm ha OpenGL
nh dng c th dng b m n hay i
,khng u tien cho bt cho ring loai no
Cnh lp th hoc khng lp th, khng u
tin cho ring loi no

4.3.2 .Khi To PIXELFORMATDESCRIPTOR:


Cu trc PIXELFORMATDESCRIPTOR l phc tp v c c mt kt qu
mong mun, khi in vo cu trc cn c mt s hiu bit thc s v OpenGL v hoat
ng ca n.Tuy nhin, c th dng gi tri mc nh cho hu ht cc thnh phn ca cu
trc. Cc gi tr mc nh ny hot ng tt trn nhiu h thng.
PIXELFORMATDESCRIPTOR pfd=
{
sizeof (PIXELFORMATDESCRIPTOR) //Kch thc cu trc.
1,
//S version ca cu trc
PFD_DRAW_TO_WINDOW |
//V vo ca s
PFD_SUPPORT_OPENGL,
//H tr li gi OpenGL
PFD_TYPE_RGBA,
//Ch mu RGBA
24,
//24 bit mu

//khng lu chn
//cc ch
//b m chiu su 32 bit
//Khng dng b m stencil hay
b m ph tr
PFD_MAIN_PLANE,
//Kiu lp ch yu
0,
//Khng chn
0,0,0,
//Khng chn
0,0,0,0,0,0,
0,0,0,0,0,0,0,
32,
0,0,

};
vi khi to nh trn, cc c c tnh trong dwFlags cho php ng dng s dng cc hm
OpenGL v vo ca s, trong khi c PFD_TYPE_DATA trong iPixelType chn ch
mu RGBA. Trng cColorBits chn 24 mu th hin 16.7 triu mu (mu s khng
n nh trn h thng 256 mu). Cc thnh phn t cRedBits n cBlueShift khng c
chn. ng dng s khng dng cc b m alpha hay b m tch ly, do thit lp cc
trng t cAccumBits dn cAccumAlphaBits bng 0. Trng cDepthBits chn b m
chiu su 32 bit. Hai s 0 tip theo cho bit ng dng khng dng cc b m ph tr hay
b m stencil. C PFD_MAIN_PLANE trong iLayerType l gi tr c duy nht dng
cho kiu lp trong Microsoft Windows. Cui cng, cc thnh phn d tr v khng h tr
c thit lp bng 0.
4.3.3.Thit Lp nh Dng im V :
Khi khi to cu trc PIXELFORMATDESCRIPTOR, ta c th thit lp nh
dng im v, nh on sau :
CclientDC clientDC(this);
Int pixelFormat=ChoosePixelFormat(clientDC.m_hDC,&pfd);
BOOL result=SetPixelFormat(clientDC.m_hDC,pixelFormat,&pfd);
dng u tin, chng trnh ly DC cho vng client ca ca s ng dng. Sau
, ChoosePixelFormat() ftrong dng th hai tm kim mt ch s cho nh dng v ph
hp nht v yu cu nh dng.
Hai i s ca handle di vi DC ( chn la nh dng im v ),
v a ch ca cu trc PIXELFORMATDESCRIPTOR
(gi thuc tnh ca nh dng im v yu cu). Nu vic gi hm khng thnh cng,
ChoosePixelFormat() tr v gi tr 0. Nu thnh cng, n tr v ch s nh dng im v.
Dng th 3 gi SetPixelFormat() thit lp nh dng im v. Ba i s ca
hm ny l handle i v DC, ch s nh dng im v, v a ch cu trc
PIXELFORMATDESCRIPTOR . Nu thnh cng , hm tr v gi tr TRUE, ngc li,
n tr v gi tr FALSE
4.3.4.Lit K nh Dng im V:
Ch rng ChoosePixelFormat() tr v mt ch s nh dng im v ph hp vi
yu cu nh dng .Thng thng, khng c vn y. Tuy nhin, lun lun phi
kim tra nh dng ny trc khi chc chn n ph hp vi ng dng. Mt cch thc hin
l xem xt mi nh dng c hiu lc, ri chn ra nh dng no c coi l tt nht cho
ng dng. on m thc hin nh sau :

PIXELFORMATDESCRIPTOR pfd;
CClientDC clientDC (this);
Int numFormat = DescribePixelFormat(clientDC.m_hDC,1,sizeof(pfd),&pfd);
For(int i= 0;I<=numFormats;++i)
{
DescribePixelFormat(clientDC.m_hDC,i,sizeof(pfd),&pfd);
}
Dng u tin ca on m khai bo cu trc PIXELFORMATDESCRIPTOR vi
tn l pfd. Dng th 2 ly DC cho vng client ca ca s ng dng .
Dng th 3 gi DescribePixelFormat() ly s ca pixel format c h tr trn
platform hin hnh, Bn i s ca hm ny l handle i vi DC ch s im v kim
tra, kch thc v a ch cu trc PIXELFORMATDESCRIPTOR. Khi gi
DescribePixelFormat(), ly s ca nh dng c sn, th i s th hai bng 1
Sau khi c tng s nh dng im v, vng for c lp t 1 n s . Trong
vng lp , DescribePixelFormat() in cu trc PIXELFORMATDESCRIPTOR cho mi
nh dng .Sau mi li gi n DescribePixelFormat(), chng trnh c th kim tra cu
trc PIXELFORMATDESCRIPTOR v cc thuc tnh m ng dng yu cu.
on m trn khng s dng GetPixelFormat(). Hm ny ch n gin tr ch s nh
dng im v hin hnh ca DC. N c gi nh sau:
Int pixelFormat= GetPixelFormat(hDC);
i s duy nht ca GetPixelFormat() l handle DC m ta cn nh dng im v
ca n. Khi khng thnh cng n tr v gi tri 0.
4.4. To Ng Cnh Biu Din:
Ng cnh biu din c to ra v tr nn hin hnh trc khi cc hm OpenGL
c s dng v vo ca s. Ty theo nhu cu ca chng trnh, m cc k thut sau
c s dng qun l ng cnh biu din:
Phng php 1:
To ng cnh biu din v lm cho n tr nn hin hnh khi p ng thng bo
WM_CREATE. Xa ng cnh biu din, bao gm c vic lm cho n tr nn khng hin
hnh, khi p ng thngWM_DESTROY.
Phng php 2 :
To ng cnh biu din khi p ng thng bo WM_CREATE, nhng ch lm cho
n tr nn hin hnh khi sn sng v vi OpenGL v ngay khi hon thnh vic v th lm
cho n tr nn khng hin hnh. Xa ng cnh biu din khi p ng thng bo
WM_DESTROY
Cn ch cc im nu trong muc 4.2, l ch c thread vi ng cnh biu
din hin hnh l c th gi cc hm OpenGL. Ngoi ra, mt thread ch c mt ng cnh
hin din duy nht. iu ny ng ngay c khi ng dng ch c mt thread. Cui cng ,
mt ng dng lun lun c t nht 1 thread.
4.4.1.Phng Php 1:

Thun li ca phng php ny l chng trnh ch cn mt ln lm cho ng cnh


biu din tr nn hin hnh. V vic lm cho ng cnh biu din tr nn hin hnh chim
nhiu thi gian x l, nn phng php 1 cho php ng dng p ng thng bo
WM_PAINT nhanh hn.
im bt li l ch phi duy tr mt ng cnh dng c cho ton b thi gian chy
chng trnh. Ngoi ra, vi cc chng trnh to ra bi AppWizard ca Visual C++, th
phng php ny khng thch hp.
4.4.2.Phng Php 2 :
Vi phng php ny, chng trnh to v gii phng ng cnh dng c ca ca s
cho mi ln v, nh vy khng cn duy tr ng cnh dng c cho ton b thi gian chy
chng trnh.Tuy nhin, c mi ln to ng cnh dng c, chng trnh ng thi phi
lm cho ng cnh biu din tr nn hin hnh .
on m sau qun l ng cnh biu din theo phng php 2:
IntOpenglView::OnCreate(LPCSREATESTRUCT lpCreateStruct)
{
if(Cview :: ONCreate(lpCreateStruct) = = -1)
return -1;
PIXELFORMATDESCRIPTOR pfd=
{
sizeof (PIXELFORMATDESCRIPTOR) //Kch thc cu trc.
1,
//S version ca cu trc
PFD_DRAW_TO_WINDOW |
//V vo ca s
PFD_SUPPORT_OPENGL,
//H tr li gi OpenGL
PFD_TYPE_RGBA,
//Ch mu RGBA
24,
//24 bit mu
0,0,0,0,0,0,
//khng lu chn
0,0,0,0,0,0,0,
//cc ch
32,
//b m chiu su 32 bit
0,0,
//Khng dng b m stencil hay b m ph tr
PFD_MAIN_PLANE,
//Kiu lp ch yu
0,
//Khng chn
0,0,0,
//Khng chn
};
CClientDC clientDC(this);
int pixelFormat=ChoosePixelFormat(clientDC.m_hDC,&pfd);
BOOL success=SetPixelFormat(clientDC.m_hDC,pixelFormat,&pfd);
m_hDC = wglCreateContext(client.m_hDC)
return 0;
}
void OpenglView::OnDraw(CDC* pDC)
{
Copengl1Doc* pDoc=GetDocument();

ASSERT_VALID(pDoc);
wglMakeCurrent(pDC->m_hDC,m_hRC);
DrawWithOpenGL();
wglMakeCurrent(pDC->m_hDC,NULL);
}
void CopenglView ::ONDestroy()
{
wglDeleteContext(m_hRC);
}
Hm OnCreate() p ng thng bo WM_CREATE bng cch trc tin ly ng
cnh dng c cho vng client ca ca s. Sau o, gi ChoosePixelFormat () tm ch s
nh dng im v yu cu cho DC v gi hm SetPixelFormat () thit lp nh dng
im v.
Tip theo, OnCreate() gi wglCreateContext() to RC thch hp vi ng cnh
dng c cho. i s ca hm ny l handle ca DC. Nu thnh cng,
wglCreateContext() tr v mt handle RC. Nu khng thnh cng, hm tr v gi tr 0.
Trong on trng trnh trn, OnCreate() ch to mt DC tm thi, ch c phm vi
cc b, nn t ng hy khi tr v, Do DC b hy, n khng th lm cho RC tr nn hin
hnh ti im ny trong chng trnh.
n khi cp nht ni dung ca ca s ng dng, MFC gi hm OnDraw() ca lp
view. Lc ny hm OnDraw() sc lm cho RC tr nn hin hnh, bng cch gi
wglMakeCurrent() s dng handle ca i tng DC (DC bt v) c truyn cho
hm. Hai i s ca OnDraw() l handle DC v handle ca RC. Nu thnh cng,
wglMakeCurrent() tr v gi tr TRUE, ngc li n tr v gi tr FALSE.
Sau khi lm cho RC tr nn hin hnh, OnDraw() gi cc b DrawWithOpenGL() v
ln ca s. (Phi vit code cho hm ny)
Li gi ln 2 n wglMakeCurrent(), vi thng s th hai l NULL lm cho ng
cnh biu din tr nn khng hin hnh. (Vi mc ch ny, cng c th dng gi tr
NULL cho c hai i s)
Cui cng, khi kt thc ng dng, MFC gi hm OnDestroy() ca lp view. Trong
OnDestroy(), chng trnh ch gi wglDeleteContext() xa ng cnh biu din .
Thng s duy nht ca hm l handle ca ng cnh biu din. Nu thnh cng , th
wglDeleteContext() ftr v gi tr l TRUE , tri li n tr v gi tri FALSE. Do ng cnh
dng c c to v hy trong p ng cho thng bo WM_PAINT, nn khng c ng
cnh dng c hy cui chng trnh.
C hai iu bit thm l:
- C th cng lc lm cho ng cnh biu din hin ti tr nn khng hin hnh, v mt
ng cnh biu din mi tr nn hin hnh, bng cch s dng handle ca ng cnh
biu din mi lm thng s th hai ca hm wglMakeCurrent ().
- Mt ng cnh dng c khng th b xa khi cn rng but vi ng cnh biu din.
Trc khi xa ng cnh dng c, phi gi wglMakeCurrent() vi gi tr ca i s th
hai l NULL tch ng cnh dng c ra khi ng cnh biu din.

on m OnCreate() trn cho thy cch dng cc hm wglCreateContext(),


wglDeleteContext(), wglMakeCurrent(). Cn cc hm wglGetCurrentContext(),
wglGetCurrentDC(), dng tm kim thng tin v cc ng cnh biu din v dng c, th
s dng nh sau :
Li gi wglCurrentContext();
HGLRC hRC = wglGetCurrentContext();
Nu thnh cng, hm tr v mt handle theo RC hin hnh, tri li n tr v ga tr
NULL .
Li gi wglCurrentDC()
HDC Hdc = wglGetCurrentDC();
Nu thnh cng, hm tr v mt handle theo ng cnh dng c rng but vi ng
cnh dng c hin hnh.Tri li n tr v NULL
4.5.TngKt:
gi thnh cng cc hm OpenGL, chng trnh phi to ng cnh biu din l
phin bng OpenGL ca ng cnh dng c- cho ca s m OpenGL s v vo. to ng
cnh biu din, trc tin phi thit lp nh dng im v ca ca s.
Khi sn sng dng cc hm OpenGL v, chng trnh phi lm cho ng cnh biu
din tr nn hin hnh, ngha l rng but ng cnh biu din vi ng cnh dng c ca
ca s. Trc khi kt thc chng trnh, ng cnh biu din phi c lm tr nn khng
hin hnh v b xa

Chng 5:V Hnh V S Dng Mu


Chng ny trnh by :
- Cch gi cch hm OpenGL
- Cc trng thi OpenGL
- Cch chn mu
- Cch nh ngha hnh dng
- Cc hnh dng c bn c h tr bi OpenGL
5.1.C Php Lnh OpenGL:
Qui c t tn hm OpenGL nh sau :

g l C o l o r 3 f ()
Th vin hm c bn

s lng
kiu d liu
i s
ca i s
Cc bng 5.1, 5.2 tng kt cc tin t, hu t v ngha ca chng.
Do th hin nhiu dng khc nhau, vi cc hu t khc nhau, ty thuc vo s
lng v loi thng s m chng tip nhn, nn trn thc t s lnh mu (prototype hn
s lnh c bn) nhiu hn s lnh c bn. Nh bao gm ht nhn OpenGL c hn 300
nguyn mu, trong khi ch gm 115 hm c bn:

V d lnh glVertex2f() c hu t l 2f , cho bit lnh c i s l 2 du chm ng .


glVertex c n 24 dng:
glVertex2d()
glVertex2i()
glVertex2dv()
glVertex2iv()

glVertex2f()
glVertex2s()
glVertex2fv()
glVertex2sv()

glVertex3d()
glVertex3i()
glVertex3dv()
glVertex3iv()

glVertex3f()
glVertex3s()
glVertex3fv()
glVertex3sv()

glVertex4d()
glVertex4i()
glVertex4dv()
glVertex4iv()

glVertex4f()
glVertex4s()
glVertex4fv()
glVertex4sv()

Ch rng c 12 lnh sau kt thc bng ch v, cho bit cc i s c cho di dng


vector.
Bng 5.1 : Cc tin t lnh OpenGL
Th
B
ht Utility Auxiliary WGL Win32 API
vin
nhn
Tin t gl
glu
Aux
wgl
Khng c tin t c bit
5.2.Cc Trng Thi OpenGL:
Mi trng OpenGL c thit lp trong mi chng trnh duy tr mt trng thi
ring bit.V d, khi thit lp mu v vi li gi glColor(), th mu ny s c tc dng cho
n khi glColor() uc gi mt ln na thay i n. T tng ny rt quen thuc trong
lp trnh trong Windows ,v ng cnh dng c lm vic tng t. Khi la chn 1 bt v,
th mi ng thng s c b rng v mu ca bt v c chn. Tc dng ca bt s
c duy tr cho n khi n c thay th.
Hu t
B
B
F
I
S
Ub
Ui
Us
Bv
Dv
Fv
Iv
Sv
ubv
uiv
usv

Bng 5.2 : Cc hu t lnh OpenGL


Kiu d liu ca i s
Glbyte
GLdouble hay Glclampd
GLfloat hay Glclampf
GLint hay Glsizei
Glshort
GLubyte hay Glboonlean
GLuint, GLenum hay Glbitfield
Glushort
GLbyte dng vector
GLdouble hay GLclampd dng vector
GLfloat hay GLclampf dng vector
GLint hay GLsizei dng vector
GLshort dng vector
GLubyte hay GLboolean dng vector
GLuint, GLenum hay Glbitfield dng vector
GLushort dng vector

Cc thuc tnh khc nhau ca trng thi OpenGL c cha trong bin trng thi.
d dng c tc dng 1 cch nhanh chng, mi bin trng thi c mt gi tr mc nh.
Cc gi tr ny tn ti cho n khi cc hm tng ng c gi thay th thuc tnh. V
d mu xa (bin trng thi tham chiu bi hng GL_COLOR_CLEAR_VALUE ) c gi
tr mc nh l mu en, hay mu v (bin trng thi tham chiu bi hng
GL_CURRENT_COLOR) c gi tr mc nh l mu trng , c gn 200 bin trng thi
trong OpenGL.
5.3.Xt Mt Chng Trnh OpenGL Ti Thiu:
Xt on m s dng cc hm OpenGL th hin 1 on thng en trng trn nn
en
void DrawWithOpenGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor(1.0f, 1.0f, 1.0f);
glBegin(GL_LINE)
glVertex2f(0.25f, 0.25f);
glVertex2f(0.75f, 0.25f);
glEnd();
glFlush();
}
By gi ta xem xt k hn tng dng ca DrawWithOpenGL()
5.3.1.t mu xa:
dng u tin, DrawWithOpenGL() gi hm glClearColor(), thit lp mu
nn ch RGBA. Bn i s ca hm ny l cc gi tr c kiu d liu GLclampf,
biu din cc thnh phn mu: , xanh l, xanh dng
v alpha
RGBA(red, green, blue, alpha) l ch mu kt hp h thng RGB vi alpha (l thnh
phn dng iu khin vic trn mu)
RGB(red, green, blue) l ch pha trn hay phng php th hin mu trn phng tin
dng ngun sng nh mng hnh mu. RGB pha trn theo t l phn trm cc mu c bn
l , xanh l v xanh dng to nn cc mu khc. H iu hnh windows nh ngha
cc t l ny bng gi tr 8 bit, gi l gi tr RGB. Gi tr RGB(0,0,0), tc khng phn
trm (cng thp nht) ca c 3 mu c bn, cho ra mu en. Gi tr
RGB(255,255,255), tc 100 phn trm (cng cao nht) ca c 3 mu c bn, cho ra
mu trng.
Gi tr alpha =1 tng ng m c hon ton, gi tr alpha = 0 tng ng tnh trong
sut hon ton
OpenGL cn ch mu ch mc, l ch mu m mi mu c ch nh bi 1 ch s
trong bng mu.
5.3.2.Xa b m mu:
Dng th hai trong DrawWithOpenGL() xa b m mu v mu xa hin hnh.
Hm glClear() hiu i s ca n nh mt chui cc c bit cho bit b m no cn xa

(hm khng tr v gi tr). B m mu (c biu th bi c


GL_COLOR_BUFFER_BIT ) l vng b nh cha nh thc c th hin trn mn hnh.
OpenGL s dng cc loi b nh khc, bao gm b m chiu su v b m stencil,
gip n x l nh.
5.3.3.t Mu V Hin Hnh:
Li gi glColor3f() thit lp mu v hin hnh. Ba i s ca n (c cho bit bi
hu t 3f) l cc gi tri GLfloat xc nh cc thnh phn mu : , xanh l, xanh dng.
C 32 phin bn ca hm glColor().
Sau khi t mu v, mi i tng c to bi cc li gi hm OpenGL s c
v bng mu v chn. Nh bit, mu ny s duy tr tc dng cho n khi no b thay
i bi li gi glColor() khc.
C th tc ng mt cch su sc n mu ca cc i tng trn mn hnh nh
vo cc thao tc ha nh chiu sng, to bng, lm m v pha trn.
Tn h thng 256 mu, mu c chn c th khng th hin trn mn hnh nh
mong mun. l v bng mu tiu chun ca Windows ch gm 20 mu, gy kh khn
cho OpenGL trong vic th hin. K thut chiu sng (lighting) s ci thin vic kim
sot mu ca OpenGL trn my 256 mu, bng cch to bng mu logic.

5.3.4.nh Ngha Mt Hnh :


Trc khi ra lnh cho OpenGL v mt hnh, ta phi cho OpenGL bit hnh ra sao.
iu ny c thc hin bng cch nh ngha cc vertex i din cho i tng, tng t
nh cc chng ha 2 chiu v ha 3 chiu. im khc bit l khng dng cc kiu
d liu t nh ngha nh Vertex v Model. Thay vo , ta s dng cc lnh OpenGL
glBegin(), glVertex(), glEnd().
Trong DrawWithOpenGL(), glBegine(GL_LINES) bt u vi nh ngha mt
hnh. Trong trng hp ny, hnh l ng thng, c biu th bng c GL_LINES. Cc
c khc c th s dng v glBegin l GL_POINTS, GL_LINE_STRIP, GL_LOOP,
GL_TRIANGLES, GL_TRIANGLES_STRIP, GL_TRIANGLES_FAN, GL_QUADS,
GL_QUADS_STRIP, v GL_POLYGONS
Do mt ng thng c 2 vertex, sau khi gi glBegin(), DrawWithOpenGL() gi
hm glVertex2f() hai ln. Hm glVertex2f(), nh ngha mt vertex, dng cc gi tr i
s kiu GLfloat m t ta X v Y ca vertex (Hm glVertex() c 24 phin bn)
Ti sao 1 th vin 3-D nh OpenGL li nh ngha 1 i tng ch vi ta X v
Y. Cn cc gi tr Z v W th sao. Thc ra, mc d glVertex2f() ch xc nh 2 gi tr X,Y
ca vertex, nhng vn c gi tr z v x lin kt vi vertex. Chng mang cc gi tr mc
nh 0.0 cho z, v1.0 cho w.
Hnh cng phc tp cng dng nhiu li glVertex() nh ngha, c khi l mt
danh sch di gia cp li gi glBegin(), glEnd(). V d, nh ngha 4 ng thng to
nn hnh ch nht, cc li gi nh sau :
glBegin(GL_LINES)

glVertex2f(-0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(0.5f,0.5f);
glVertex2f(0.5f,0.5f);
glVertex2f(-0.5f,0.5f);
glVertex2f(-0.5f,0.5f);
glVertex2f(-0.5f,-0.5f);
glEnd();
Gi tr ca cc vertex trn da trn cc ta Decart mc nh thit lp trong
OpenGL. Cc ta mc nh ny to nn mt khi vung 2x2x2, vi gc ta (0,0) ti
tm khi vung. V vy, on m trn v mt hnh ch nht tm ca s, nh hnh 5.1 .

Hnh 5.1: Hnh ch nht v


bng OpenGL

Hm glVertex() khng i s, lun


lun kt thc danh
sch glVertex().
Hm glVertex() ch l 1 trong 12 hm c th dng gia cp glBegin() v glEnd(). Cc
hm l :
glVertex(), glCallist(), glCallists(), glColor(), glEdgeFlag(),
glEvalCoord(), glIndex(), glMaterial(), glNormal(), glTextCoord(),
5.3.5.Bo m Cc Thao Tc V Hon Tt:
Cho n y, chng trnh thit lp mu xa , xa nn, thit lp mu v, v nh
ngha ng thng. Mc d lc ny, nh cui cng c l xut hin trn mng hnh,
thng thng thao tc v c kt thc vi li gi glFlush(). Hm ny bo m rng mi
lnh OpenGL ghi trong b m c thc hin (glFlush() khng c i s)
Mt hm tng t l glFinish(),thc hin cng mt nhim v nh glFlush(), nhng tr v
ch khi cc thao tc v hon tt.
5.4.nh Ngha V V im:
Hm glBegin() khi u nh ngha mt hnh, i s n ca n l kiu hnh sp
to. Cc hnh c i din bi cc hng GL_POINTS, GL_LINE_STRIP, GL_LOOP,
GL_TRIANGLES, GL_TRIANGLES_STRIP, GL_TRIANGLES_FAN, GL_QUADS,
GL_QUADS_STRIP, v GL_POLYGONS.

Nhiu hnh c v nh tn gi ca chng. V d, hnh to bi glBegin(GL_POINTS) l


mt im trn mn hnh. Mt chui cc im c nh ngha nh sau:
glBegin(GL_POINTS);
glVertex2f(0.0f,0.0f);
glVertex2f(0.75f,0.75f);
glVertex2f(-0.75f,-0.75f);
glVertex2f(-0.75f,0.75f);
glVertex2f(0.75f,-0.75f);
glEnd();
y, mi nm glVertex() nh ngha mt im n. Ch rng on m trn
nh ngha cc im trn mt phng Decart 2D, ch vi hai ta X,Y. Nhng nh bit
, OpenGL t ng thit lp gi tr mt nh 0 v 1 cho cc bin tng ng z v w. Nu
nh ngha cc im trong ta 3D, on m nh sau:
glBegin(GL_POINTS);
glVertex3f(0.0f,0.0f,0.0f);
glVertex3f(0.75f,0.75f,1.0f);
glVertex3f(-0.75f,-0.75f,1.0f);
glVertex3f(-0.75f,0.75f,-1.0f);
glVertex3f(0.75f,-0.75f,-1.0f);
glEnd();
Trong on m ny, phin bn 3f ca glVertex() c dng nh ngha cc ta
3-D X,Y,Z
Vi mn hnh c phn gii cao hin nay, th s kh nhn ra mt im n trn
mn hnh. Tht may, OpenGL c lnh glPointSize(), cho php v im vi bt k kch
thc no. V d v 1 im vi kch thc l 4 pixel
glPointSize(4f);
i s n ca hm l gi tr GLfloat cho bit ng knh yu cu ca
im. xc nh mt dy kch thc im (c h tr bi OpenGL),
glGetFloatv() c dng nh sau
glFloat ps[2];
glGetFloatv(GL_POINT_SIZE_RANGE,ps);
Vi ps l 2 mng thnh phn c gi tr GLFloat cha kch thc im nh nht v
im ln nht. Li gi glGetFloatv() i hi cc i s gm mt hng s cho bit gi tr
cn t c v a ch mng glFloat cha cc gi tr . C gn 150 hng s c th dng
vi cc dng khc nhau ca hm glGet().
Cng c th t c kch thc im hin hnh vi cch tng t.
glFloat ps;
glGetFloatv(GL_POINT_SIZE_RANGE,&ps);
Trong trng hp ny, ps l bin kiu glFloat cha kch thc im hin hnh. a
ch bin ny c cho bi i s th hai trong hm glGetFloat().
on m sau v cc im nh trn hnh 5.2:
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glFloat ps[2];
glGetFloatv(GL_POINT_SIZE_RANGE,ps);
glPointSize(ps[1]);
glBegin(GL_POINTS);
glVertex2f(0.0f,0.0f);
glVertex2f(0.75f,0.75f);
glVertex2f(-0.75f,-0.75f);
glVertex2f(-0.75f,0.75f);
glVertex2f(0.75f,-0.75f);
glEnd();
glFlush()
Hnh 5.2: V cc im vi
OpenGL.

Ch rng mc d c th thit
lp
ng kch ca im, trn thc t kch thc im nh b nh hng bi antialiasing, l
thao tc ha lm gim hoc loi tr hin tng bc thang ca ng thng trn mn
hnh. iu ny cng ng cho cc hnh khc.

5.5.nh Ngha V V ng:


Mt ng c xc nh bi hai vertex xc nh im u v im cui ng
glBegin(GL_LINES)
glVertex2f(0.0f,0.0f);
glVertex2f(1.0f,0.0f);
glEnd();
V c th nh ngha cng lc nhiu ng
glBegin(GL_LINES)
glVertex2f(0.0f,0.0f);
glVertex2f(1.0f,0.0f);
glVertex2f(0.0f,0.0f);
glVertex2f(0.0f,1.0f);
glEnd();
xc nh kch thc ng,ta dng hm glLineWidth() :
glLineWidth(4.0f);

i s n ca hm ny l gi tr GLfloat cho bit b rng ca ng.


xc nh di b rng ng (c h tr bi OpenGL), ta dng hm glGetFloatv()
GLfloat lw[2];
glGetFloatv(GL_POINT_SIZE_RANGE,lw);
Vi lw l mng hai thnh phn cc gi tr GLfloat cha b rng ng nh nht v
ln nht.
Cng c th dng glGetFloat() ly b rng hin hnh:
GLfloat lw;
glGetFloatv(GL_LIINE_WIDTH,&lw);
V lw l bin kiu GLfloat cha b rng hin hnh ca ng. a ch bin ny
c cho nh l i s th 2 trong hm glGetFloatv()
on m sau th hin hnh hnh 5.3
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glFloat lw[2];
glGetFloatv(GL_POINT_SIZE_RANGE,lw);
glLineWidth(lw[1]);
glBegin(GL_LINES);
glVertex2f(-0.75f,-0.75f);
glVertex2f(0.75f,0.75f);
glVertex2f(-0.75f,0.25f);
glVertex2f(0.75f,0.25f);
glVertex2f(-0.75f,-0.25f);
glVertex2f(0.75f,-0.25f);
glVertex2f(-0.75f,-0.75f);
glVertex2f(0.75f,-0.75f);
glEnd();
glFlush();

Hnh5.3: V cc ng vi
OpenGL

5.5.1.V ng Chm:
OpenGL c th v ng chm, l ng to nn bi cc im hay nt gch. Bc
u tin v ng chm l gi glLineStipple() xc nh kiu v bng chm. V lm
iu , cn nh ngha mu chm,bng cch to mt gi tr nh phn, vi 1 tng ng vi
chm, 0 tng ng vi khng chm
V d mu chm 0000000011111111 cho kt qu l mt ng to nn bi khong trng
v nt gch xem k. Hay mu chm 0000111100001111 to mt ng ca cc nt gch
ngn.
s dng mu chm lm i s trong li gi glLineStipple(), phi chuyn n
sang gi tr thp lc phn. v d trn, cc gi tr tng ng l 0x00FF, v 0x0F0F.
Li gi glLineStipple() nh sau .
glLineStipple(1,0x0F0F)
Hai i s ca hm gm 1 gi tr GLint biu th h s lp mu (s ln lp cc im
trong mu chm ), v mt gi tr GLushort cha mu chm. V d, vi h s lp bng 2,
mu chm l 01010101, th ng chm c v l0011001100110011. C th hiu h s
lp nh t l co gin theo phng ngang ca ng.
Sau khi thip lp mu chm, glEnable() c gi cho php vic v bng chm:
glEnable(GL_LINE_STIPPLE);
Hm glEnable() c i s n ca l kh nng ca OpenGL m ta mun s dng.
V d, hng GL_LINE_STIPPLE bt u kh nng v bng chm, GL_LIGHTING bt
u kh nng chiu sng. C gn 50 hng s dng dvi cc hm glEnable() v
glDisable().
on m sau th hin nh hnh 5.4:
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glFloat lw[2];
glGetFloatv(GL_POINT_SIZE_RANGE,lw);
glLineWidth(lw[1]);
glLineStipple(1,0x4444)
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
glVertex2f(-0.75f,-0.75f);
glVertex2f(0.75f,0.75f);
glVertex2f(-0.75f,0.25f);
glVertex2f(0.75f,0.25f);
glVertex2f(-0.75f,-0.25f);
glVertex2f(0.75f,-0.25f);
glVertex2f(-0.75f,-0.75f);
glVertex2f(0.75f,-0.75f);
glEnd();
glFlush();

Hnh5.4: V cc ng chm vi
OpenGL

5.5.2.V Di ng:
Di ng l mt lot ng ni vi nhau. Khi nh ngha di ng, cp vertex
u tin nh ngha ng u tin, mi vertex sau nh ngha im k tip m
OpenGL s v n. Tng t lnh MoveTo() vi 1 on lnh LineTo() theo sau. Trong
trng hp ny, hng GL_LINE_STRIP lm i s cho hm glBegin().
on m sau th hin nh hnh 5.5:
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glFloat lw[2];
glGetFloatv(GL_POINT_SIZE_RANGE,lw);
glLineWidth(lw[1]/2);
glLineStipple(1,0x4444)
glBegin(GL_LINE_STRIPPLE);
glVertex2f(-1.00f,0.75f);
glVertex2f(1.00f,0.75f);
glVertex2f(-1.00f,0.25f);
glVertex2f(1.00f,0.25f);
glVertex2f(-1.00f,-0.25f);
glVertex2f(1,00f,-0.25f);
glVertex2f(-1.00f,-0.75f);
glVertex2f(1.00f,-0.75f);
glEnd();
glFlush();

Hnh5.5: V di ng vi OpenGL

5.5.3.V ng Khp Kn:


Tng t nh di ng, ng khp kn l 1 lot cc ng ni vi nhau, nhng
vertex cui cng ni vi ng u tin. Khi nh ngha ng khp kn, hng
GL_LINES_LOOP lm i s cho hm glBegin().
on m sau th th hin nh hnh 5.6 :
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glFloat lw[2];
glGetFloatv(GL_POINT_SIZE_RANGE,lw);
glLineWidth(lw[1]/2);
glBegin(GL_LINE_LOOP);
glVertex2f(-1.00f,0.75f);
glVertex2f(1.00f,0.75f);
glVertex2f(-1.00f,0.25f);
glVertex2f(1.00f,0.25f);
glVertex2f(-1.00f,-0.25f);
glVertex2f(1,00f,-0.25f);
glVertex2f(-1.00f,-0.75f);
glVertex2f(1.00f,-0.75f);
glEnd();
glFlush();

Hnh5.6: V ng kp kn
Vi OpenGL.
5.6.nh Ngha V V Cc a Gic:
a gic l hnh c to bi cc ng ni (cnh) gia mt tp hp cc vertex.
Mt a gic c t nht 3 cnh. Nh vy, a gic n gin nht l tam gic.
OpenGL c th v a gic nh cc im, cc ng ngoi, hay i tng c bit.
OpenGL cn c th in y cc a gic vi mu c nh ngha. Thm vo , mt
a gic OpenGL c hai mt trc v sau c th v theo hai cch ring, v c th quay 1 a
gic xem mt bn kia.
Hm glPolygonMode() c dng v a gic:
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
Hai i s ca hm ny l l cc gi tri GLenum. i s u tin c th l hng
GL_FRONT, GL_BACK, hay GL_FRONT_AND_BACK, cho bit mt aa gic m ta
mun thit lp ch v l mt trc hay mt sau, hay c hai mt. i s th 2 cho bit
ch v cho mt a gic chn. Cc ch v c th l GL_POINT (v im ti cc
vertex ca a gic ), GL_LINE (v a gic vi cc cnh a gic khung li), GL_FILL
(a gic c)

cho OpenGL bit mt no ca a gic l trc , v mt no l sau, ta dng th


t khi nh ngha cc vertex to nn a gic. Mt a gic c xem l i-din-mt-trc,
khi cc vertex ca n c nh ngha ngc chiu kim ng h. Tuy nhin c th thay
i quan nim ca OpenGL bng cch gi glFontFace():
glFontFace(GL_CW);
Li gi ny cho OpenGL bit a gic i-din-mt-trc chn nh ngha theo
chiu no. i s n ca hng l GL_CW khi chn chiu kim ng h, v GL_CCW khi
chn chiu ngc chiu kim ng h(mc nh)
nh ngha mt a gic cng d nh nh ngha 1 ng . Ch cn t nht 3 vertex,
v phi nh ngha cc vertex ng chiu,(theo gi tr hin hnh c bin trng thi
GL_FRONT_FACE). on m sau nh ngha mt hnh vung i-din-mt-trc:
glBegin(GL_POLYGON);
glVertex2f(-0.5f,0.5f);
glVertex2f(-0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(0.5f,0.5f);
glEND();
Trong an m trn, hng s GL_POLYGON c dng vi glBegin() nh
ngha a gic. Sau , nh ngha cc vertex ca a gic theo chiu ngc chiu kim ng
h (theo mc nh). Cui cng, nh thng l, kt thc vic nh ngha bng li gi
glEND().
on m sau th hin nh hnh 5.7:
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT,GL_LINE);
glPolygonMode(GL_BACK,GL_FILL);
glFontFace(GL_CCW);
glBegin(GL_POLYGON);
glVertex2f(-0.5f,0.5f);
glVertex2f(-0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(0.5f,0.5f);
glEnd();
glFlush();

Hnh 5.7: V a gic vi


OpenGL.

Trong on m trn, hai li gi glPolygonMode() yu cu mt trc a gic v


theo ch khung li, mt sau theo ch a gic c.

Hnh 5.8: V a gic i din


mt sau.

V a gic l i-din-mt-trc, nn ch
mt
trc c th hin. Nu thay i
glFontFace(GL_CCW) bng glFontFace(GL_CW), bo cho OpenGL rng a gic
l i-din-mt-sau, chng trnh s th hin nh hnh 5.8
5.6.1.V a Gic Bng Chm:
Ging nh khi v ng vi ng mu chm do ngi dng nh ngha, ta c th
v a gic c in y vi 1 mu no , bc u tin thc hin l nh dng mu.
Mu l bitmap 32x32, trong mi gi tr 1 th hin ra 1 im trn mn hnh,
V d hnh 5.9 l 1 du chm dng a gic OpenGL . Mu c xy dng trong
h thng ng k 32x32. Mi vung c in y trong mu th hin o mt bit c
gi tr 1.
Mu cn c chuyn i sang cc gi tr thp lc phn (mng gi tr GLubyte)
c th dng trong chng trnh. Vic chuyn i ny bt u vi byte gc tri h thng
ng k , ri dn theo hng phi v i ln. D liu ca mu hnh 5.9 nh sau:
GLubyte pattern[]=
{
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,

0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00,
0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff,
0x0f,0xf0,0x0f,0xf0,
}
Ch rng c 32 dng d liu trong mng trn. Mi dng d liu l mt dng trn
mu hnh 5.9. Dng u tin trn trong mng l dng cui cng ca mu chm, v dng
d liu cui cng l dng d liu u tin ca mu chm.
Hm glPolygonStipple() c gi chuyn mu chm cho OpenGL:
glPolygonStipple(pattern);
i s ca hm l a ch d liu nh ngha mu chm.
Vic tip theo l gi glEnable() cho php vic v bng chm:
glEnable(GL_POLYGON_STIPPLE);
Sau li gi ny mi a gic c trng c v in y bi mu chn. tr li
vic v a gic thng thng, ta dng hm glDisable() :
glDisable(GL_POLYGON_STIPPLE);
on m sau th hin hnh 5.10
GLubyte pattern[]=
{
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,

0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
0xff,0x00,0xff,0x00, 0x0f,0xf0,0x0f,0xf0,
0x00,0xff,0x00,0xff, 0x0f,0xf0,0x0f,0xf0,
};
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glPolygonStipple(pattern);
glEnable(GL_POLYGON_STIPPLE);
glBegin(GL_POLYGON);
glVertex2f(-0.5f,0.5f);
glVertex2f(-0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(0.5f,0.5f);
glEND();
glDisable(GL_POLYGON_STIPPLE);

Hnh5.10: a gic chm

v hnh ch nht mt cch


dng hm glRect(). Hm ny c tm phin bn.

hiu qu, OpenGL

5.6.2.V a Gic Khung Li Li:


OpenGL c 2 s hn ch trong vic v a gic: (hnh 5.11)
- a gic khng c c cc cnh cho nhau.
- a gic li, tc khng cha cc vng lm hay l bn trong
Tuy vy, cc hn ch ny khng gy tr ngi no, bi v c th to hnh dng bt
k t 2 hay nhiu a gic li. Vn l ch khi no to 1 a gic khng li dng khung
li bng cch nh vy th hnh s cha nhng ng khng mong mun bn trong.
kh chng, ta dng hm glEdgeFlag(). Khi gi glEdgeFlag(FALSE) trc khi
nh ngha vertex, OpenGL s khng v cnh ni vertex vi vertex c nh ngha
tip theo. Li gi glEdgeFlag(TRUE) s tr li vic v cnh bnh thng.
Hnh 5.11 a gic li v khng li

a gic li

a gic khng li

Hnh 5.12 :To 1 a gic li t 2 a gic khng li


Hnh 5.13 l a gic khng li ch L to bi ba hnh ch nht. on m sau to hnh
tng t nhng khng cha cc hnh bn trong (Hnh 5.14).
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON);
glEdgeFlag(TRUE);
glVertex2f(-0.2f,0.3f);
glEdgeFlag(FALSE);
glVertex2f(-0.2f,-0.1f);
glEdgeFlag(TRUE);
glVertex2f(0.0f,-0.1f);
glVertex2f(0.0f,0.3f);
Hnh 5.13:
To
hnh ch L
glEnd();
vi 3 hnh ch nht khung li
glBegin(GL_POLYGON);
glEdgeFlag(TRUE);
glVertex2f(-0.2f,-0.1f);
glVertex2f(-0.2f,-0.4f);
glEdgeFlag(FALSE);
glVertex2f(0.0f,-0.4f);
glVertex2f(0.0f,-0.1f);
glEnd();
glBegin(GL_POLYGON);
glEdgeFlag(FALSE);
glVertex2f(0.0f,-0.1f);
glEdgeFlag(TRUE);
glVertex2f(0.0f,-0.4f);
glVertex2f(0.3f,-0.4f);

glVertex2f(0.3f,-0.1f);
glEnd();
glFlush();

Hnh 5.14 : V hnh ch L khng cha cc ng bn trong


5.6.3.V tam gic:
OpenGL h tr vic v nhiu a gic t bit, tam gic l 1 trong s , Vic nh
ngha tam gic khng khc cc a gic khc, ngoi tr vic s dng i s
GL_TRIANGLES cho hm glBegin(). Trong on m sau th hin tam gic nh hnh
5.15 :
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_TRIANGLES);
glVertex2f(-0.5f,0.3f);
glVertex2f(-0.5f,-0.5f);
glVertex2f(0.5f,-0.5f);
glVertex2f(-0.5f,0.8f);
glVertex2f(-0.5f,0.5f);
glVertex2f(0.5f,0.5f);
glEnd();
glFlush();

Hnh 5.15: Tam Gic


OpenGL

5.6.4.V Di Tam Gic:


Di tam gic l chui tam gic ni nhau, mi tam gic c chung mt cnh vi tam
gic v trc n. Ngha l sau khi nh ngha 3 vertex cho tam gic u tin, th ch cn
nh ngha mt vertex cho mi tam gic tip theo trong dy tam gic.

Th t nh ngha cc vertex ca 1 di tam gic l quan trng. Tam gic u tin ca


di c cc vertex nh ngha nh hnh 5.16. Cnh dng chung vi tam gic th hai trong
di c xc nh bi cc vertex 3 v 2 theo th t. Ngha l tam gic th 2 trong di l
c xc nh bi cc vertex 3,2 v 4 (hnh 5.17). Tip theo, vertex 3 v 4 xc nh cnh
dng chung ca tam gic th 2 v 3 trng hp minh ha ny, cc tam gic l idin-mt-trc, nn vertex ca chng c nh ngha ngc chiu kim ng h.
Bng tng kt th t cc vertex trong di tam gic:
S th t tam gic
1
2
3
4
5
6
7

Cnh 1
Vertex1
Vertex3
Vertex2
Vertex5
Vertex5
Vertex7
Vertex7

Hnh 5.16 : Cc vertex


ca tam gic u tin
trong di tam gic

Cnh 2
Vertex2
Vertex2
Vertex4
Vertex4
Vertex6
Vertex6
Vertex8

Cnh 3
Vertex3
Vertex4
Vertex5
Vertex6
Vertex7
Vertex8
Vertex9

Vertex1
Vertex2
Vertex3
Hnh 5.17 : Thm tam gic th hai vo di tam gic

Hnh 5.18: Thm tam gic th 3 vo di tam gic

glClearColor(1.0f, 1.0f, 1.0f, 1.0f);


glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_TRIANGLE_TRIP);
glVertex2f(-0.75f,0.25f);
glVertex2f(-0.75f,-0.25f);
glVertex2f(-0.25f,0.25f);
glVertex2f(0.0f,-0.25f);
glVertex2f(0.25f,0.5f);

glVertex2f(0.5f,0.3f);
glVertex2f(0.75f,0.3f);
glEnd();
glFlush();
Hnh 5.19 : Di tam gic

5.6.5.V qut tam gic:


Qut tam gic, c th hin
bi
hng
GL_TRIANGLE_FAN, l chui cc tam gic c chung 1 vertex. Vic nh ngha qut
tam gic tng t nh vic nh ngha di tam gic. u tin, nh ngha 3 vertex cho tam
gic th 1 trong qut. V cc tam gic k tip c 1 cnh dng chung vi tam gic trc,
nn ch cn nh ngha thm 1 vertex. Hnh 5.20 cho thy th t nh ngha vertex ca 1
qut.
Bng tng kt th t cc vertex trong qut tam gic:
S th t tam gic
1
2
3
4
5
6
7

Cnh 1
Vertex1
Vertex1
Vertex1
Vertex1
Vertex1
Vertex1
Vertex1

Cnh 2
Vertex2
Vertex3
Vertex4
Vertex5
Vertex6
Vertex7
Vertex8

Cnh 3
Vertex3
Vertex4
Vertex5
Vertex6
Vertex7
Vertex8
Vertex9

on m sau th hin nh hnh 5.21.


glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_TRIANGLE_FAN)
glVertex2f(-0.25f,0.25f);
glVertex2f(-0.25f,-0.25f);
glVertex2f(0.25f,0.25f);
glVertex2f(0.25f,0.5f);
glVertex2f(-0.05f,0.7f);
glVertex2f(-0.45f,0.5f);

Hnh 5.20 :Th t nh ngha cc

ca mt qut tam gic


glEnd();
glFlush();

Hnh 5.21 : Qut tam gic

5.6.6.V T Gic:
nh ngha t gic, hng
GL_QUADS c s dng lm i s cho hm glBegin(). Mi t gic c nh ngha
bng 4 vertex. V c th nh ngha nhiu t gic gia 1 cp lnh glBegin() v glEnd().
on m sau th hin hnh 5.22
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_QUADS) ;
glVertex2f(-0.75f,0.75f);
glVertex2f(-0.75f,0.25f);
glVertex2f(-0.25f,0.0f);
glVertex2f(0.0f,0.5f);
glVertex2f(-0.55f,-0.25f);
glVertex2f(-0.75f,-0.45f);
glVertex2f(-0.25f,-0.7f);
glVertex2f(0.5f,-0.25f);
glVertex2f(0.5f,0.75f);
glVertex2f(0.25f,0.1f);
glVertex2f(0.75f,0.2f);
glVertex2f(0.8f,0.65f);
glEnd();
glFlush();

Hnh 5.22 : v t gic

5.6.7.V Di T Gic:
Di t gic l chui cc t gic, trong mi cp t gic c chung vi nhau 2
verrtex. nh ngha di t gic, ta dng GL_QUAD-STRIP vi hm glBegin(). Sau
nh ngha 4 vertex cho t gic u tin ca di, vi mi t gic tip theo, ta nh ngha
thm 2 vertex. Th t nh ngha vertex l rt quan trng. Hnh 5.23 cho thy th t nh
ngha vertex ca 1 di t gic.

Bng tng kt th t cc vertex trong di tam gic:


S th t tam gic
1
2
3
4
5
6
7

Cnh 1
Vertex1
Vertex3
Vertex5
Vertex7
Vertex9
Vertex11
Vertex13

Cnh 2
Vertex2
Vertex4
Vertex6
Vertex8
Vertex10
Vertex12
Vertex14

Cnh 3
Vertex3
Vertex5
Vertex7
Vertex9
Vertex11
Vertex13
Vertex15

Cnh 3
Vertex4
Vertex6
Vertex8
Vertex10
Vertex12
Vertex16
Vertex18

on m sau th hin nh hnh 5.24


glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_QUAD_STRIP) ;
glVertex2f(-0.75f,0.25f);
glVertex2f(-0.65f,0.75f);
glVertex2f(-0.55f,0.1f);
glVertex2f(-0.25f,0.6f);
Vertex2 Vertex4 Vertex6 Vertex8
glVertex2f(-0.15f,-0.2f);
glVertex2f(0.0f,-0.45f);
glVertex2f(0.25f,-0.7f);
glVertex2f(0.5f,0.65f);
Vertex1

Vertex3
Vertex5 Vertex7

glVertex2f(0.75f,-0.3f);
glVertex2f(0.85f,0.45f);
glEnd();
glFlush();

Hnh 5.24 Di t gic

5.7. Tng Kt :
Mt s hm OpenGL c nhiu phin bn, ph thuc vo s lng v kiu d liu
ca i s. Cc phin bn ny c phn bit bi hu t theo sau tn hm c bn.
Cc hm OpenGL thng thay i gi tr ca bin trng thi OpenGl. Cc bin
trng thi ny (v d mu v hin hnh) c hiu lc cho n khi b thay th. iu ny
tng t cch Windows qun l DC.
Mt chng trnh OpenGL n gin thng bt u bng vic thit lp mu xa v
mu v, ri xa b m mu c vng trng dng v. Sau , nh ngha cc
vertex ca hnh gia 1 cp hm glBegin() v glEnd(). i s n ca glBegin() quyt
nh kiu hnh ang c nh ngha cc vertex.
OpenGL c th v cc hnh nh im, ng, a gic, v tam gic. Thm vo ,
c th phi hp cc hnh ny vo di a gic, qut tam gic, ngg khp kn.v cc kiu
hnh khc phc tp hn. Mc d OpenGL khng th qun l cc a gic khng li, vn c
th to cc a gic ny bng cch rp nhiu a gic li li vi nhau.

Chng 6: Cc Php Bin Hnh OpenGL


6.1.Xy Dng i Tng 3D T Cc a Gic:
Vic xy dng i tng 3D t cc a gic tng t nh gn cc mu giy c hnh
dng khc nhau(a gic) thnh cc vt th 3D.
V d ta c 6 mu giy hnh vung 1 (hnh 6.1), v ta mun gn chng li vi
nhau c mt khi vung 1. Cho rng ta c mt khi vung 2 c to thnh t
cc hnh vung 2 thuc h thng li Decart 3D. Hnh vung ln ny th hin th gii
m ta s t hp cc mu giy v to nn i tng. Khi vung bng giy c to nn
bng cch t cc mu giy vo v tr sao cho gc h ta Decart(0,0,0) s nm ti tm
khi vung giy. Tc to l tm ca hai khi vung(hnh 6.2).
chnh l cch xy dng i tng 3D trong OpenGL. Ta s cung cp cho OpenGL
mt danh sch cc vertex, th hin cc ta ca i tng . Danh sch ny khng ch
bo cho OpenGL cch v a gic, m cn cho bit v tr a gic trong h thng li
Decart 3D.
Hnh 6.1 : Su hnh vung
dng to 1 khi vung
Y Axis

Hnh 6.2: T hp khi


vung

Z Axis

X Axis

OpenGL mc nh h thng li 3D l khi vung 2, vi gc ta ti tm.


Ngha l cc ta X,Y,v Z l dy t 1.0 n 1.0. Cc gi tr trn trc X tng t tri
sang phi, Cc gi tr trn trc Y tng t di ln trn, Cc gi tr trn trc Z tng t sau
ra trc.
Nh vy, hnh thnh khi vung nh hnh 6.2, on m sau c s dng
xc nh vertex cho cc a gic.
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glEnd()
glBegin(GL_POLYGON) ;

glVertex3f(0.5f, 0.5f, -0.5f);


glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glEnd()
on m trn trc ht nh ngha mt trc khi vung, k tip l cnh phi, pha
sau, cnh tri, y, v cui cng l nh. Ch rng cc vertex c nh ngha theo cch
mt trc cc a gic to nn bn ngoi khi vung, trong khi mt sau cc a gic pha
trong khi vung. Ngha l, vertex ca cc a gic i-din-mt-trc (nh mt trc
khi vung) c nh ngha theo chiu ngc chiu kim ng h, cn vertex ca a gic
i-din-mt-sau (nh mt sau khi vung) c nh ngha theo chiu kim ng h.
Vic nh ngha vertex cc a gic to nn i tng 3D i hi phi theo chiu
thch hp. trng thi mc nh, cc vertex ca a gic i-din-mt-trc c nh
ngha chiu ngc chiu kim ng h. Vic khng tun theo quy tc ny c th mang li
cc kt qu khng mong mun.
6.2.Php Chiu:
Nu a on m trn vo mt chng trnh OpenGl, kt qu nhn c s nh
hnh 6.3. Do OpenGL s dng php chiu trc giao (php chiu song song) r th hin
hnh khi cho.Vi php chiu ny, mt sau khi vung s khng nh hn, m l cng
kch thc vi mt trc khi vung, do
khng
th thy c.
th hin khi vung 1 cch thc hn, ta
phi s
dng php chiu phi cnh.

Hnh 6.3: Hnh khi th


hin bng php chiu
trc giao

6.2.1. Chn Ma Trn Chiu:


Bc u tin s dng php chiu phi cnh l chn ma trn chiu:
glMatrixMode(GL_PROTECTION);
OpenGL s dng 3 loi stack ma trn khc nhau bin i cc vertex ca i
tng cn th hin. Stack ma trn ging nh stack m my tnh vn dng, nhng lu tr
gi tr cho cc ma trn lin quan, ch khng cha cc kiu d kiu trng thi nh trong
stack thng thng. C th ngh rng mt stack ma trn l mt ma trn 4x4
Hm glMatrixMode() cho php la chn ma trn. i s n ca hm c th l 1
trong cc hng GL_MODEVIEW, GL_PROJECTION V GL_TEXTURE. Cc hng ny
biu din stack ma trn cn thao tc.
6.2.2.Khi To Ma Trn:
s dng ma trn vo vic bin hnh, trc tin cn khi to n bng ma trn
n v. OpenGL c 1 hm ring bit thc hin nhim v ny, l :
glLoadIdentity();
Hm glLoadIdentity() khi to ma trn c chn hin hnh bng ma trn n v,
bo m ma trn c khi to khng cha cc gi tr c th nh hng n cc php tnh
6.2.3.Xc nh Khng Gian Quan St:
Bc tip theo l gi hm glFrustum() xc nh gii hn ca khng gian quan
st, l vng 3D m i tng tn ti.
glFrustum(GLdouble,GLdouble,GLdouble,GLdouble,GLdouble,GLdouble);
Hm ny to ra mt ma trn phi cnh v nhn n vi ma trn chiu c chn
hin hnh. Su i s ca hm xc nh cc ta tri, phi, y, nh, gn, xa ca khng
gian quan st.
Cc i s gn v xa th hin khong cch t mt. Nh vy mang cc gi tr
dng. Mt l im t ta nhn thy cnh. Nu khng thay i th mt v tr gc ta
(0,0,0).
Mt phng gn bt u mt khng gian quan st. Mt phng xa kt thc 1 khng
gian quan st. Mi i tng hay b phn i tng nm gia mt v mt phng gn, hay

xa hn mt phng xa, hoc bn ngoi gii hn tri, phi, y v nh s khng xut


hin trong mn hnh. Ni cch khc mi i tng hay b phn i tng bn ngoi
khng gian quan st u b ct b, khng c th hin. Cc mt phng gii hn khng
gian quan st c gi l cc mt phng ct.
Hnh 6.5 th hin th gii c xc nh bi li gi glFrustum(). c th hin
trn hnh, di tng phi nm trn th gii ny.

Hnh 6.5:Th gii


uc xc nh bi
li gi gglFrushtum()
Trong trng hp cn s dng php chiu trc giao, c th dng cc hm
glOrtho() v glOrtho2D() thit lp php chiu.
6.3.Php Bin Hnh i Tng (Modelview Transformation):
biu din c i tng ln mn hnh, cn phi di chuyn i tng vo
khng gian quan st c xc nh. V sau li gi glFrustum(), i tng vn nm bn
ngoi khng gian quan st.
Hnh 6.6 m t trng hp li gi glFrustum(-1.0, 1.0, -1.0, 1.0, 2.0, 7.0) thit lp
mt phng ct gn cch mt 2 n v, v mt phng ct xa cch mt 7 n v. Nhng khi
vung vn v tr gc ta , hon ton nm ngoi khng gian quan st. Mt khc khong
cch t mt n mt phng ct gn lun l s dng, nn trong mi trng hp, khng th
t i tng vo hn trong khng gian quan st c xc nh. Gii php cho vn
ny l tnh tin i tng.
(Thc ra cng c th s dng hm glClipPlane() th hin i tng ngoi khng gian
quan st c xc nh bi glFrustum())
Li Decart 3D Mt phng ct gn Khng gian quan st
Khi vung
Mt phng
Mt

ct xa

1
0
-1
-2
-3
-4
-5
-6
Hnh 6.6 Khi vung v khng gian quan st.

-7

6.3.1.Php Tnh Tin :


on m sau thc hin vic tnh tin khi vung theo trc Z, t n vo khng
gian quan st:
glMatrixMode(GL_MODEVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -3.5f);

Dng th nht bo cho OpenGL bit kiu stack ma trn cn thao tc l modelview. Dng
th hai khi to ma trn modelview vi ma trn n v. Dng th 3 tnh tin khi vung
3.5 n v theo chim m trc Z. Hm glTranslatef() to mt ma trn tnh tin, ri nhn
ma trn ny vi ma trn c chn hin hnh. Ba i s ca n l cc gi tr GLfloat cho
bit cc lng tnh tin trn trc X,Y v Z. Mt phin bn khc ca hm ny l
glTranslated(), c i s kiu GLdouble.
Sau khi cc dng trn c thc hin, i tng di chuyn vo khng gian quan st nh
hnh 6.7. Tt nhin, do khi vung xa mt hn trc, nn hnh s nh hn.
Hnh 6.7: Khi
vung tin vo
khng gian
quan st

1
-1
-3

-4

-5

-6

-7

on m sau th hin hnh 6.8


glMatrixMode(GL_PROTECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 2.0, 7.0);
glMatrixMode(GL_MODEVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -3.5f);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);

0
-2

glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(0.5f, 0.5f,-0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f,0.5f, -0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glEnd()
glBegin(GL_POLYGON) ;
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glEnd()
glFlush();
on m thit lp php chiu v php bin i i tng quan st, ri v khi
vung ln mn hnh. v khi vung, OpenGL cung cp n tng vertex ca khi
vung, trc tin l php bin i i tng quan st, k tip l php chiu phi cnh,
cui cng l php bin i viewport.

Hnh 6.8 : Hnh


phi cnh khi vung

Tt nhin, cng c th tnh


tin i tng theo
cc trc khc. V d thay cc dng sau vo on m v d trn khng ch tnh tin khi
vung theo chiu m trc Z, m cn a khi vung i ln v sang phi.(hnh 6.9)

glMatrixMode(GL_MODEVIEW);
glLoadIdentity();
glTranslatef(0.75f, 0.75f, -3.5f);
Mt cch khc s dng php bin hnh l dng hm gluLookAt(). Hm ny cho php xem
cnh m khng cn cc php tnh tin v quay.

Hnh 6.9: Tnh tin


Khi vung theo
ba trc

6.3.2.Php co gin:
Hm Scalef() to mt ma
trn co gin, v
nhn n vi ma trn c chn hin hnh. Ba i s ca hm l cc gi tr GLfloat xc
nh cc h s co gin theo cc trc X,Y v Z. Mt phin bn khc ca hm l glScaled()
c cc i s kiu Gldouble.
on m sau th hin nh hnh 6.10, trong DrawCube() l hm nh ngha cc
vertex ca hnh khi:
glMatrixMode(GL_PROTECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 2.0, 7.0);
glMatrixMode(GL_MODEVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -3.5f);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
DrawCube();
glFlush();

Hnh 6.10: Khi


vung gin hai ln
theo trc X

6.3.3.Php quay:
Hm glRotatef() to mt ma trn quay, v nhn n vi ma trn c chn hin
hnh. Bn i s ca hm l cc gi tr GLfloat xc nh gc quay ngc chiu kim ng
h v cc ta X,Y v Z ca verter quay ( quay theo 1 trc, t gi tr 1.0 cho trc
v0.0 cho trc cn li). Mt phin bn khc ca hm glRotated() c cc i s kiu
Gldouble.
on m sau th hin nh hnh 6.11, ch rng ba li gi glRotatef ( 20.0f, 1.0f,
1.0f, 1.0f), v li gi ny s quay hnh quanh vector v t gc ta n
im(1.0,1.0,1.0).
glMatrixMode(GL_PROTECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 2.0, 7.0);
glMatrixMode(GL_MODEVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -3.5f);
glRotatef ( 20.0f, 1.0f, 0.0f, 0.0f);
glRotatef ( 20.0f, 0.0f, 1.0f, 0.0f);
glRotatef ( 20.0f, 0.0f, 0.0f, 1.0f);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 0.0f, 0.0f);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
DrawCube();
glFlush();

Hnh 6.11: Quay


khi vung theo
3 trc ta

c 3 php bin hnh va trnh by trn, nu mun thc hin 1 cch trc tip nh
vi ma trn nh chng 2 ha hai chiu, ta c th s dng cc hm OpenGL
glLoadMatrix(), v glMulMatrix(). glLoadMatrix() thit lp tp gi tr cho ma trn hin
hnh, cn glMulMatrix() nhn ma trn hin hnh vi ma trn cho.
6.4.Php Bin i Viewport:
Nh ni, v 1 hnh OpenGL thc hin php bin hnh i tng, t vo
v tr mong mun, (vic ny lin quan n im nhn). K n, OpenGL cung cp php
chiu phi cnh(hoc song song) xn hnh v chiu phi cnh(hoc song song). Cui
cng, OpenGL thc hin php bin i viewport, quyt nh cch m cc vertex c
th hin trn thit b(mn hnh hay my in).Viewoport ch n gin l ch nht m hnh
c th hin trn .
6.4.1.Thit Lp Viewport:
Khi khng cn xc nh mt viewport ring bit, ta c th s dng mt viewport
mc nh th hin hnh. Tuy nhin, c lc ch cn s dng viewport l 1 phn ca s,
hay cn viewport thay i khi thay i kch thc ca ca s Khi , hm glViewport()
c s dng thit lp kch thc v v tr viewport() nh sau:
glViewport(left,bottom,width,height);
Hai i s u ca hm l cc gi tr Glint xc nh gc tri di. Hai i s tip theo l
cc gi tr Glsizesi xc nh chiu rng v chiu cao viewport.
6.4.2. Gii Quyt T L Th Hin:
Viewport c th cng kch thc vi ca s, bt chp kch thc khng gian quan
st. V khi ca s thay i, viewport cng c thit lp li theo kch thc ca ca s
mi. iu ny lm cho hnh co gin trn c s t l th hin ca ca s, l t l chiu rng
trn chiu cao ca s.
V d, khi ca s l vung, th hnh vung v trn ca s s l vung (hnh 6.12).
Nhng khi ca s b ko di ra, th hnh vung cng b ko di theo(hnh 6.13). Nu t l
th hin ca viewport v t l th hin ca khng gian quan st l mt. Th hnh OpenGL
s khng bin dng.
thay i kch thc viewport mi khi kch thc ca s b thay i, thng bo
WM_SIZE ca Windows phi c p ng. ng dng nhn thng bo ny khi ca s
th hin ln u, cng nh mi khi kch thc ca s b thay i. C th x l thng bo
WM_SIZE nh sau:
Void Copengl3dView::OnSize(UINT nType, int cx, int cy)
{
Cview::OnSize(nType,cx,cy);
//TODO:Add your message handler code here
CClientDC clientDC(this);

wglMakeCurrent(clientDC.m_hDC,m_hRC);
glMatrixMode( GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0,1.0,-1.0,1.0,2.0,7.0);
glViewport(0,0,cx,cy);
wglMakeCurrent(NULL,NULL);
}

Hnh 6.12: Hnh vung


v trn viewport vung

Hnh 6.13: Hnh vung v trn


viewport hnh ch nht

Trc tin on m to mt ng cnh dng c cho ca client, ri dng handle theo ng


cnh dng c ny lm cho i s th nht trong li gi wglMakeCurrent. Li gi ny lin
kt ng cnh biu din OpenGL vi ng cnh dng c. Sau , OnSize() gi
GlMatrixMode() vi i s GL_PROJECTION bo cho OpenGL bit chng trnh
thao tc ma trn chiu. Li gi glLoadIdentity() khi to ma trn chiu theo ma trn n
v. Cui cng, glFrustum() c gi nh ngha khng gian quan st, glViewport()
thit lp viewport theo kch thc ca s client, v wglMakeCurrent() vi i s NULL
lm cho RC ht hin hnh.
Quyt nh ng cc i s cho glFrustum() khng phi l vic d dng. Do ,
th vin OpenGL utility cung cp hm gluPerpective(), cho php nh ngha khng gian
quan st theo 1 cch trc gic hn:
gluPerpective(viewAngle, aspectRatio, nearPlane,farPlane);
Bn i s ca hm l cc gi tr Gldouble. i s u tin l cho bit gc nhn, l
gc to thnh gia cc ng thng t mt n nh v y mt phng ct gn(hnh 6.14).
Gc ny cng ln, cc mt phng ct gn v xa cng cao. i s th hai cho bit t l th
hin ca khng gian quan st. Khi gi tr ny bng 1, th khng gian quan st c chiu
rng bng chiu cao. Hai i s cui cng l cc gi tr dng, cho bit khong cch t
im nhn n cc mt phng ct gn v xa.
gi cho viewport v khng

gian quan st c cng t l th hin,


d ngi dng thay i kch thc ca s,

on m sau c dng p ng thng bo

Hnh 6.14 Gc nhn:


WM_SIZE :
CClientDC clientDC(this);
wglMakeCurrent(clientDC.m_hDC,m_hRC);
glMatrixMode( GL_PROJECTION);
glLoadIdentity();
GLdouble aspectRatio=( GLdouble) cx /( GLdouble) cy;
gluPerspective(40.0,aspectRatio,3.5,10.0);
glViewport(0,0,cx,cy);
wglMakeCurrent(NULL,NULL);
Khi dng on m trn thit lp khng gian quan st v viewport, hnh vung s
lun lun vung cho d ngi dng thay i kch thc ca s. Tuy nhin, hnh s nh i
khi chiu cao ca s b gim.
6.5.Tng kt:
Vi OpenGL, khi xc nh v tr a gic, iu quan trng l nh ngha cc vertex
ca a gic i-din-mt-trc theo chiu ngc chiu kim ng h, tr khi s thay i
chiu c thc hin mt cch r rng vi hm glFrontFace().
OpenGL thc hin bin hnh trn cc vertex ca i tng(trc khi th hin i tng)
theo th t :bin hnh i tng, bin i php chiu, v bin i viewport. Php bin
hnh i tng th c xc nh trn ma trn i tng, cn php chiu v bin i
viewport th c xc nh trn ma trn chiu. Khi gi cc hm tc ng n ma trn,
trc ht phi gi glMatrixMode() chn ng ma trn.
OpenGL c cc hm to khng gian quan st, t hp bin hnh. Chng ta khng phi thao
tc trc tip hon ma trn.

Chng 7:Chiu Sng i Tng


Cc mc trong chng ny gm:
- nh ngha ngun sng.
- To cc loi nh sng mi trng, khuch tn, phn chiu, v nh sng pht.
- nh ngha tnh cht vt liu.
- nh ngha vector trc giao cho vertex a gic.
- To bng mu logic.
7.1. Cc Loi Ngun Sng:
nh sng cung cp mu sc v to nh sng cho i tng 3-D, lm hnh nh nhn
c tr nn thc hn (hnh7.1,7.2).

Hnh7.1: Khi vung khng chiu sng

Hnh7.2: Khi vung c chiu sng

OpenGL c bn loi ngun sng: mi trng, khuych tn, phn chiu, v ngun pht.
Anh sng mi trng l nh sng n t mi hng cng lc; V d nh sng trong mt
phng c chiu sng y l nh sng mi trng. nh sng khuch tn l nh sng
n t mt hng, chiu vo b mt i tng, lm cho b mt ny tr nn sng chi hn,
sau nh sng b khuch tn i mi hng. Anh sng phn chiu l nh sng to m
phn chi, thng l mu trng, trn cc b mt c tnh phn chiu cao. Cui cng, ngun
pht l ngun nh sng pht ra t i tng nh bng n chng hn .
Tt nhin, mi ngun nh sng, k c nh sng mi trng, n t mt ni no . C
th c 8 ngun pht khc nhau trong mt chng trnh OpenGL. Thm vo , c th xc
nh tnh phn x nh sng ca b mt i tng trong mt cnh. i tng s ph thuc
vo nh sng m n phn x. V du khi thit lp b mt tng phn x nh sng xanh
dng, OpenGL s th hin i tng vi cc bng xanh dng khc nhau (gi s nh
sng chiu vo i tng l nh sng trng).
7.2.nh Ngha Mt Ngun Sng:
OpenGL Cho php c tm ngun sng khc nhau trong mt chng trnh. mi ngun
sng c nhiu thuc tnh kim sot cc nh sng tc ng n mt cnh. Cc nh sng

ny bao gm nh sng mi trng, nh sng khuch tn, nh sng phn chiu v nh sng
v tr. Cn xt nh cc thnh phn phn trm mu , xanh dng, xanh lc trong cc
thuc tnh nh sng mi trng, khuch tn,v phn chiu; ng thi phi xc nh cc
ta X,Y,Z v W ca ngun sng. Cng vic ny c qun l bng cc mng cha cc
gi tr yu cu.
7.2.1.Thit Lp Cc Mng Gi Tr Anh Sng:
Cc mng sau cha cc gi tr dng nh ngha mt ngun sng:
Glfloat ambientLight0[] = {0.3f, 0.3f, 0.3f, 1.0f};
Glfloat diffuseLight0[] = {0.5f, 0.5f, 0.5f, 1.0f};
Glfloat specularLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat positionLight0[] = {0.0f, 0.0f, 1.0f, 0.0f};
Trong mng ambientLightO[], lng mu c thit lp cho nh sng mi trng
gm 30% v 30% xanh dng, 30% xanh lc. (Gi tr 1.0 l thnh phn alpha, c th
b qua). Mng diffuselightO[], cha lng mu cho nh snh khuch tn, gm 50% v
50% xanh dng, v 50% xanh lc. Do cc thnh phn mu trong cc mng trn bng
nhau, chng nh ngha nh sng mi trng v nh sng khuch tn l nh sng trng vi
cc sng ring. Thay i t l phn trm cc thnh phn mu s mang li nh sng
mu; V d lng mu ln hn lng mu khc, th nh sng s mang mu . (Cc
gi tr RBGA t 0.0 n1.0).
Mng speculararLight0[] cha cc gi tr ca nh sng trng ti nht (hay khng c
t nh sng no)
Cui cng, mng positionLight0[] cha v tr ngun sng, xc nh bi cc ta
X,Y,Z, v W. Trong , W ch c hai gi tr 1v 0. Nu W bng 0,ta c ngun sng theo
hng, l ngun sng khong cch v hn so vi cnh, tc cc tia sng n i tng l
song song vi nhau. Mt tri l v d cho ngun sng v hng.Nu W bng 1, ta c
ngun sng theo v tr , l ngun sng c v tr gn cnh, nn cc tia sng chiu vo i
tng theo cc gc khc nhau. n l ngun sng theo v tr.
7.2.2 .Chuyn Mng Cho OpenGL:
Cc gi tr nh ngha ngun sng c chuyn cho OpenGL bng cch gi hm
glLight() nh sau:
glLightfv (GL_LIGHT0,GL_AMBIENT, ambientLight0);
glLightfv (GL_LIGHT0,GL_DIFFUSE, diffuseLight0);
glLightfv (GL_LIGHT0,GL_SPECULAR, specularLight0);
glLightfv (GL_LIGHT0,GL_POSITION, positionLight0);
Ba i s ca glLightfv() gm ngun sng nh ngha , hng s th hin tnh cht
nh sng m ta mun thay i, v a ch mng cha cc gi tr dng thay i tnh cht
nh sng. i vi cc thuc tnh nh sng mi trng, khuch tn, v phn chiu, mng
cha cc gi tr RGBA. i vi a ch ngun sng, mng cha cc ta X,Y,Z, v W
ca ngun sng.

Do mt s chng trnh OpenGL c th c tm ngun sng, i s u tin l hng


s t GL_LIGHT0 n GL_LIGHT7
i s th hai l mt trong mi hng s bng7.1. Cc hng s thng dng vi
cc hm ny l GL_AMBIENT,GL_DIFFUSE, GL_SPECULAR,v GL_POSITION.
Bng 7.1: Hng s tnh cht cho hm glight()
Hng s
Gl_AMBIENT
GL-CONSTANT_ATTENUATION
GL_DIFFUSE
GL-LINEAR_ATTENUATION
GL_POSITION

ngha
Xc nh nh nh sng mi trng
Xc nh lng gim nh sng theo mt h s
Xc nh nh sng khuch tn
Xc nh lng gim nh sng trn c s khong
cch t ngun sng n i tng
Xc nh v tr ngun sng

GL_QUADRATIC_ATTENUATION
GL_SPECULAR
GL_SPOT_CUTOFF
GL_SPOT_DIRECTION
GL_SPOT_EXPONENT

Xc nh lng gim nh sng theo bnh phng


khong cch t ngun sng n tng
Xc nh nh sng khong chiu
Xc nh gc tri ca n chiu
Xc nh hng n chiu
Xc nh cng n chiu ,c tnh n gc ca
nh sng.

Cc phin bn khc ca hm glLight() gm glLight(), glLighti(), v glLightiv() c


dng thit lp cc tnh cht khc ca ngun sng. V d, c th dng mt trong cc
hm ny (hay nhiu hm cng lc ) nh ngha n chiu (spotling) trong cnh. Sau
ny ta s thy n chiu cho php to mt ngun sng trc tip vi chm tia hp.
7.2.3.Kch Hot Ngun Sng:
Khi c nh ngha ngun sng, ta phi kch hot chng, tng t nh vic bc
cng tt n, bng hm glEnable():
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
Li gi u kch hot chiu sng. Li gi th hai bt ngun sng 0.
V tr mt ngun sng th b nh hng bi php bin hnh i tng nh mi i tng
khc. Vic bin hnh xy ra khi hm glLight() c gi xc nh v tr hay hng ca
ngun sng. Do , phi gi glMatrixMode(gl_MODELVIEW) v glLoadldentity() trc
khi gi glLight(), nh trc khi nh ngha cc vertex c a gic. D nhin, nu mun
bin i v tr v hng ngun sng theo cc i tng khc trong cnh, phi thc hin
cc php tnh tin, co gin, v quay trc khi gi glLight().
7.3.nh Ngha Tnh Cht Vt Liu:
Tnh cht phn chiu ca vt liu rt nh hng n cnh . V d, hnh khi mu
trng trong nh sng s c mu ch khng l mu trng ; Trong khi , mt khi
trong nh sng xanh lc s c mu en. Ngoi ra, cc vt liu c sng khc nhau s
phn x nh sng khc nhau:
7.3.1.Mu V Anh Sng:
Mu ca i tng trong cnh ph thuc vo mu ca nh sng m n phn x . V
d, nu i tng phn x nh sng xanh lc, th n s c mu xanh lc trong nh sng
trng; Do cc thnh phn mu v xanh dng ca nh sng b hp th ch cn li thnh
phn xanh lc n c mt ngi.
Thng thng, c nh sng mi trng v nh sng khuch tn phn x t i tng
theo cng mt cch. Tc l nu i tng phn x nh sng xanh lc, th n phn x mu
xanh lc i vi nh sng mi trng ln nh sng khuch tn. Trong khi nh sng phn
chiu hu nh lun lun cng mu vi nh sng chiu vo i tng . V d, xt mt khi
vung c th hin trong nh sng vng (mu vng l t hp ng lng ca mu v
xanh dng). Nu mun khi vung c mu , vt liu ca n phi phn x mu ca

nh sng mi trng v nh sng khuch tn. lm khi vung tr nn sng hn, th


phi thit lp cho n tnh phn x mu vng i vi nh sng phn chiu.
OpenGL cho php nh ngha cc tnh cht ca i tng, xc nh loi nh sng m
i tng phn x, v nh vy gin tip xc nh mu cui cng ca i tng.
7.3.2.Thii Lp Cc Mng Gi Tr Vt Liu:
Bc u tin nh ngha cc tnh cht ca vt liu l thit lp cc mng cha cc
gi tr phn x nh sng mi trng khuch tn v nh sng phn chiu.
Glfloat materialAmbient[] = {0.0f, 0.7f, 0.0f, 1.0f}
Glfloat materialSpecular[] = {1.0f, 1.0f, 1.0f, 1.0f}
Mi mng ny cha cc gi tr RGBA cho mt kiu phn x nh sng ring bit,
l cc gi tr RGBA tng ng vi mu sc nh sng di ra t vt liu i tng. Mng
materialAmbient[] nh ngha vt liu phn x 70%mu xanh lc trong nh sng mi
trng khuch tn m n nhn c, nhng khng phn x mu v xanh dng. Mng
materialSpecular[] nh ngha vt liu phn x nh sng trng, gm 100% cc thnh
phn , xanh dng, xanh lc.
7.3.3. Chuyn Mng Vt Liu Cho OpenGL:
chuyn mng vt liu cho OpenGL, dng cc con tr tr n mng lm i s
trong li gi glMaterialv():
GlMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialAmbient);
GlMaterialfv (GL_FRONT, GL_SPECULAR, materialSpecular);
Cc i s hm glMaterialfv() gm mt hng xc nh b mt a gic m ta mun
nh ngha vt liu, mt hng nh ngha tnh cht vt liu, v con tr tr n mng cha
gi tr dng thit lp tnh cht vt liu:
i s u tin l GL_FRONT, GL_BACK, hay GL_FRONT_AND_BACK, tng
ng vi s la chn mt trc, mt sau, hay c mt trc ln sau ca a gic to nn i
tng. i vi i tng c nh hnh khi, GL_FRONT thng c chn v mt sau
s
khng bao gi thy c. Nhng nu hnh khi mt mt mt, th
GL_FRONT_AND_BACK c chn, v mt cnh no c th nhn thy c hai mt
sau v trc a gic.
i s th hai c th l mt trong s cc hng bng 7.2 Cc hng xc nh tnh
cht vt liu. Do i tng lun phn x cc nh sng mi trng v khuch tn nh
nhau, nn hng GL_AMBIENT_END_DIFFUSE thng c dng. Hm glMaterialfv()
c bn phin bn.
Bng 7.2: Cc hng tnh cht dng cho hm glMaterialfv()
Hng s
GL_AMBIENT
GL_AMBIENT_AND_DIFFUSE
GL_COLOR_INDEXES
GL_DIFFUSE

Y ngha
Anh sng mi trng bi nh x
Anh sng mi trng v khuch tn b nh
x
Xc nh cc ch s mu cho nh sng
Anh sng khuch tn b phn x

GL_EMISSION
GL_SHININESS
GL_SPECULAR

Xc nh ngun snh pht.


Xc nh bng vt liu.
Anh sng phn chiu b phn x.

Trong cc hng bng trn, c hng GL_COLOR_INDEXES xc nh cc ch s


mu cho nh sng. Nhng y, ta ch s dng OpenGL ch mu RGBA.
Nu i tng phn x nh sng phn chiu, ta phi xc nh bng vt liu, l
hng s quyt nh phn x nh sng phn chiu. Li gi hm glMaterialfv() lc
nh sau:
glMaterialf (GL_FRONT, GL_SHININESS,60.0f)
Cc i s hm glMaterialf() gm mt hng xc nh b mt a gic cn nh ngha
vt liu, hng GL_SHININESS (ch dng trong trng hp ny), v mt gi tr trong
khong t 0 n128 nh ngha bng.
Cn phn bit r s khc nhau gia ngun sng pht v nh sng do phn x. Khi
nh ngha cc ngun sng, ta quyt nh lng cc nh sng mi trng, khuch tn, v
phn chiu c trong cnh. Khi nh ngha tnh cht vt liu , ta quyt nh lng nh sng
do i tng phn x cc nh sng mi trng, khuch tn, v phn chiu.
7.4.nh Ngha Cc Php Tuyn:
vic chiu sng OpenGL c thc hin tt trn i tng, khng ch nh ngha
cc vertex ca i tng m cn cn nh ngha php tin cho mi vertex.
7.4.1.Php Tuyn V Vertex:
Php tuyn l mt vertor n v biu th hng i din a gic, cho php OpenGL
tnh ton gc nh sng chiu vo a gic. Php tuyn lun trc giao vi b mt m n
biu th .
Php tin ca cc vertex mt a gic c nh ngha bi li gi hm Normal3f()
trc li gi glVertex() nh ngha vertex:
glBegin (GL_POLYGON);
GlNormal3f((Glfloat) x, (GLfloat) y, (GLfloat) z);
glVertex3f(-5.0f, 0.0f, -0.5f);
glVertex3f( 5.0f, 0.0f, 0.5f);
glVertex3f( 0.5f, 0.0f, -0.5f);
glEnd();
i s hm glNormal3f() l cc gi tr Glfloat xc nh cc ta X,Y, v Z ca
im cui php tuyn. C 9 phin bn hm glNormal(). Ch rng php tuyn lin kt
vi mi vertex c nh ngha trong on m trn s tn ti cho n khi glNormal()
c gi li nh ngha php tuyn mi.
7.4.2. Tnh Ton Php Tuyn :
Vic tnh ton php tuyn cho mt a gic i hi mt kin thc ton hc phc tp.
y c trnh by mt hm c to sn c tn CalcNormal() dng tnh ton php
tuyn t cc ta X,Y,Z ca ba vertex bt k ca mt a gic (khng cng nm trn mt
ng thng):
double p1[] = {-0.5, 0.0, -0.5};

double p2[] = {-0.5, 0.0, 0.5};


double p3[] = { 0.5, 0.0, 0.5};
double n[3];
CalcNormal (p1, p2, p3, n) ;
i s ca CalcNormal() l cc con tr tr n bn mng gi tr doumle. Ba mng
u cha cc ta X,Y,Z ca ba vertex. Mng th t, n[], cha cc ta php tuyn.
Sau li gi CalcNormal(), mng n[] c th dng nh ngha php tuyn cho cc vertex ca
a gic nh sau:
glBegin (GL_POLYGON);
GlNormal3f((Glfloat) n[0], (GLfloat) n[1], (GLfloat) n[2]);
glVertex3f(-5.0f, 0.0f, -0.5f);
glVertex3f( 5.0f, 0.0f, 0.5f);
glVertex3f( 0.5f, 0.0f, -0.5f);
glEnd();
on m sau m t s lc cc php ton trong CalcNormal():
Void CalcNormal (double * p1,duoble * p2,double * p3,duoble * n)
{
//To hai vertor t cc con tr.
Double a[3], b[3];
a[0] = p2[0] p1[0];
a[1] = p2[1] p1[1];
a[2] = p2[2] p1[2];
a[0] = p3[0] p1[0];
a[1] = p3[1] p1[1];
a[2] = p3[2] p1[2];
//Tnh ton cho ca haivertor.
n[0] = a[1] * b[2] a[2] * b[1];
n[1] = a[2] * b[0] a[0] * b[2];
n[2] = a[0] * b[1] a[1] * b[0];
//Tiu chun ha vertor mi.
Double length = sqrt (n[0]*n[0]+n[1]+n[2]*n[2]);
If (length !=0)
{
n[0]= n[0]/ length;
n[1]= n[1]/ length;
n[2]= n[2]/ length;
}
}
7.5. Xc nh Kiu Bng V Kch Hot Vic Kim Tra Chiu Su:

Mt phng din quan trng ca OpenGL l kiu bng dng th hin i tng
trong cnh. C hai kiu bng: mt (smooth) v phng (flat). chn kiu bng, s dng
hm glShadeModel() nh sau:
glShadeModel (GL_FLAT);
i s n ca hm l hng th hin kiu bng c chn, l GL_SMOOTH, hoc
GL_FLAT. Vi bng mt, OpenGL phi xc nh mu bng cho tng pixel trn a gic.
Trong khi i vi bng phng, ton b a gic dng chung mt mu bng.
Hnh 7.4 Hnh cu vi bng phng

Hnh 7.5 Hnh cu vi bng mt

v v t bng cho cc a gic c chnh xc, OpenGL cn bit v tr tng i


ca mi a gic trong cnh. Hin nhin l cc a gic nm di cc a gic khc s khng
c th hin. Vic xc nh v tr trc, sau ca a gic c gi l kim tra chiu su.
thc hin, phi kch hot vic kim tra bng hm glEnable():
glEnable (GL_DEPTH_TEST);
Nu vic kim tra khng c thc hin, OpenGL s gp kh khn trong vic xc
nh v a gic no v b qua a gic no, dn n kt qu khng nh .
Tuy vy, ch kch hot thi th cng cha . Do OpenGL s dng mt b m ring
cho vic kim tra chiu su, ta phi xa n trc khi th hin cnh:
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
i s n ca hm l gi tr c c t pho OR gia cc hng
GL_COLOR_BUFFER_BIT v GL_DEPTH_BUFFER_BIT. (Php ton OR so snh
tng bit tng ng gia hai ton hng; Nu c hai bt bng 1, bt kt qu bng 1; Tri li,
bt kt qu bng 0). Nh vy, hm s xa cng lc c hai b m mu v chiu su.
7.6. nh Ngha n Chiu:
n chiu cho chm tia tp trung hp. Cng nh mi ngun sng OpenGL khc,
cng vi vic nh ngha n chiu, ta ng thi phi to cho n mt ngun sng theo v
tr(W bnh mt trong li gi positionLight(), xc nh mt gc ct cho chm tia, nh
ngha v tr v hng ca ngun. on m sau nh ngha mt n chiu:
Glfloat ambientLight1[] = {0.2f, 0.2f, 0.2f, 1.0f};
Glfloat diffuseLight1[] = {1.0f, 1.0f, 1.0f, 1.0f};

Glfloat specularLight[] = {0.0f, 0.0f, 0.0f, 1.0f};


Glfloat positionLight1[] = {0.0f, 0.0f,-2.0f, 1.0f};
Glfloat directionLight1[] = {0.0f, 0.0f, -1.0f};
glLightfv (GL_LIGHT1, GL_AMBIENT, ambientLight1);
glLightfv (GL_LIGHT1, GL_DIFFUSE, diffuseLight1);
glLightfv (GL_LIGHT1, GL_SPECULAR, specularLight1);
glLightfv (GL_LIGHT1, GL_POSITION, positionLight1);
glLightfv (GL_LIGHT1, GL_SPOT_CUTOFF, 10.0f);
glLightfv (GL_LIGHT1, GL_SPOT_DERECTION, derectionLight1);
Trong on m trn, li gi glLight (GL_LIGHT!, GL_SPOT_CUTOFF, 10.0f) gii
hn chm tia n chiu theo cung 20 . i s 10.0 l ng gc gia ng tm v
ng sinh chm tia. Vi gc ct ln hn, chm tia n chiu s rng hn.

Hnh7.6: chm tia hp trn hnh cu

Hnh 7.7: chm tia rng hn trn hnh cu

S khc nhau tip theo ca n chiu so vi cc ngun sng khc l li gi


glLightfv(GL_LIGHT!, GL_SPOT_DIRECTION, directionLight1), thit lp hng chiu
ca n. Cc ta hng chiu c cha trong mng directionLight1[ ] l ta ca
im m nh sng n hng vo.
Hnh7.8 Thay i
ta hng chiu
trong mng directionLight[].

7.7.Th Hin i Tng 3-D c Chiu Sng:


Vic th hin mt cnh OpenGL c chiu snh khng n gin. ngun sng
tc ng n i tng trong cnh i hi phi hiu r cch lm vic ca kiu chiu sng
OpenGL.
7.7.1. Cc Hiu Qu Ca Ngun Sng Mi Trng:
Nh bit, mt cnh c th c ba loi ngun sng: mi trng, khuch tn, v
phn chiu. Ngoi ra, cc tnh cht vt liu i tng quyt nh kiu nh sng phn x t
i tng, cng mu sc v cc hiu qu bng trn i tng. Ta xem xt on m sau:
glShadeModel (GL_SMOOTH);
glEnable (GL_DEPTH_TEST);
glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
glClearColor (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadldentity();
Glfloat materialAmbient[] = {0.0f, 1.0f, 0.1f, 1.0f};
Glfloat materialSpecular[] = {0.7f, 0.7f, 0.7f, 1.0f};
glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, aterialAmbient);
glMaterialfv (GL_FRONT, GL_SPECULAR, materialAmbient);
glMaterialfv (GL_FRONT, GL_SHININESS,100.0f);
Glfloat ambientLight0[] = {0.7f, 0.7f, 0.7f, 1.0f};
Glfloat diffuseLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat specularLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat positionLight0[] = {0.0f, 0.0f, 1.0f, 0.0f};
glLightfv (GL_LIGHT0, GL_AMBIENT, ambientLightO);
glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuseLightO);
glLightfv (GL_LIGHT0, GL_SPECULAR, specularLightO);
glLightfv (GL_LIGHT0, GL_POSITION, positionLightO);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glTranslatef (0.0f, 0.0f, -3.5f);
auxSolidSphere (1.0);
glFlush();
on m trn xc nh vt liu phn x nh sng mi trng , khuch tn xanh lc v
nh sng phn chiu trng. Ngun sng trong cnh th khng c thit lp, ngoi tr nh

sng mi trng trng. Cui cng, i tng l hnh cu c , c v ti gc ta bi


hm auxSolidSphere(). Hm ny c i s l bn knh hnh vu, v n t tnh ton php
tuyn.
Hnh 7.9 th hin on m trn. Ch rng hng cu ch ging mt hnh trn c. l
do n ch phn x nh sng mi trng, l loi nh sng n t mi hng. Trong khi cc
a gic to nn hnh cu phn x cng mt lng nh sng. Hay ni cch khc, ch ring
nh sng mi trng khng cung cp bng to cm gic ba chiu.

Hnh 7.9 Hnh cu


ch vi nh sng
mi trng:

7.7.2.Cc Hiu Qu
Sng Khuch Tn:
Thay i on m trn cnh ch c on m khuch tn:

Ca Ngun

Glfloat diffuseLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};


Glfloat ambientLight0[] = {0.7f, 0.7f, 0.7f, 1.0f};
Glfloat specularLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat positionLight0[] = {0.0f, 0.0f, 1.0f, 0.0f};
Do nh sng khuch tn n t mt hng xc nh, cc tia sng chiu vo i tng
theo cc gc khc nhau, nn ng i ca cc tia sng n cc a gic (to nn hnh cu)
khc nhau, to hiu qu bng cho hnh 7.10:

Hnh 7.10 Hnh cu


ch vi nh sng
khuch tn:

7.7.3.Cc Hiu Qu
Sng Phn Chiu:

Ca Ngun

Xt cnh ch c ngun sng phn chiu:


Glfloat diffuseLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat ambientLight0[] = {0.7f, 0.7f, 0.7f, 1.0f};
Glfloat specularLight0[] = {0.0f, 0.0f, 0.0f, 1.0f};
Glfloat positionLight0[] = {0.0f, 0.0f, 1.0f, 0.0f};
Do cnh khng c nh sng mi trng hay khuch tn, hnh cu ti mu hu ht din
tch (hnh 7.11). im sng trn mn hnh l nh sng phn chiu, to nn mt im
nng trn b mt hnh cu.
7.7.4.Hiu Qu Anh Sng Tng Hp:
to mt cnh sinh ng, cc loi nh sng ca ngun sng, cng nh cc
loi nh sng phn x t b mt tng, cng v tr ngun sng cn c cn nhc
k. on m sau th hin hnh 7.12:
Glfloat ambientLight0[] = {0.2f, 0.2f, 0.2f, 1.0f};
Glfloat diffuseLight0[] = {0.7f, 0.7f, 0.7f, 1.0f};
Glfloat specularLight0[] = {1f, 1f,1f, 1.0f};
Glfloat positionLight0[] = {1.0f, 0.5f, 1.0f, 0.0f};
Glfloat materialAmbient[] = {0.0f, 1.0f,0.0f, 1.0f};
Glfloat materialSpecular[] = {1.0f, 1.0f,1.0f, 1.0f};

7.8.Bng Mu Logic:
OpenGL thc s c thit k cho h thng th hin 64000 mu hoc hn. Trn
h thng 256 mu, OpenGL gp kh khn trong vic th hin chnh xt mu cn c. L
do l trn h thng 256 mu, Windows dnh ring mng mu ch gm 20 mu v
desktop, trong khi OpenGL khng th v chnh xc cc i tng 3-D c bng ch vi
20 mu.

Hnh 7.11 Hnh cu ch


vi nh sng phn chiu

Hnh 7.11 Hnh cu vi nh


sng mi trng, khuch tn
v phn chiu

Nh vy, c kt qu ngon mc, gii php tt nht l dng Windows trn cc h


thng h tr nhiu ngi dng hn. Tuy nhin, cng cn mt cch cung cp cho
OpenGL s mu va s dng trn h thng 256 mu. l thit lp bng mu logic.
7.8.1.To Bng Mu Logic:
Mi ng dng phi nh ngha mu c bng mu logic ca ring n. Khi ngi dng
i ng dng, ng dng m s chuyn mng mu logic ca n cho Windows Windows
thit lp mu thch hp. Nh vy, bng mu logic l tp hp mu lin kt vi mt ng
dng rng bit. Trong khi bng mu h thng cha cc mu ang c th hin trn mn
hnh. Khi chuyn i ng dng, bng mu logic ca ng dng mi c th hin trn
bng mu h thng. Ngha l c th c nhiu mng mu logic, nhng ch c mt mng
mu h thng.
Xt on m sau nh ngha mt cu trc cha thng tin Windows cn to bng mu
logic:
Struct
{
WORD Version;
WORD NumberOfEntries;
PALETTEENTRY aEntries [256];
}logicalPalette = {0x300, 256};
Cc dng trn th hin cu trc LOGPALETTE, mt kiu d liu c nh ngha bi
Winsdows v c s dng khi qun l cc bng mu logic. Thnh phn u tin ca cu
trc l s phin bn, y l gi tr thp lc phn 0x300. Thnh phn th hay l s mu
trong bng mu. y, l 256 mu. Thnh phn cui cng l mng mu cu trc
PALETTEENTRY.Windows nh ngha cu trc
PALETTEENTRY nh sau:
Typedef struct
{
BYTE peRed;
BYTE peGreen;
BYTE peBlue;
BYTE peFlgs;
}PALETTETRY;
Cc thnh phn peRed, peGreen, peBlue ca cu trc cha cng cc mu , xanh
lc, v xanh dng. Thnh phn peFlags xc nh cch Windows qun l entry (mc ghi
trong mng mu), c th c cc gi tr PC_EXPLICT, PC_NOCOLLAPSE,
PC_RESERVED, hay 0.

C PC_EXPLICT cho bit entry cha mt ch s v bng mu h thng, thay v cha


cc gi tr mu thc s. Ch s ny c lu tr t thp ca entry. Rt him khi dng c
PC_EXPLICT.
C PC_NOCOLLAPSE cho bit Windows s a mu vo entry rng ca bng mu
h thng, thay v map n v entry hin c. Nu nh khng c cc entry rng trong bng
mu h thng, Windows b qua c PC_NOCOLLAPSE.
C PC_RESERVED ngn Windows s dng mu ca cc ng dng khc. C ny
thng dng vi bng mu thng xuyn thay i mu.
Khi Windows t qun l entry theo cch m n thy ph hp, th gi tr 0 c thit
lp cho thnh phn peFlags.
Vi cu trc LOGPALETTE nh ngha, c th to bng mu cha mt khong mu
rng nh v d sau:
BYTE Reds[] = {0,36,72,109,145,182,218,255};
BYTE Greens[] = {0,36,72,109,145,182,218,255};
BYTE Blues[] = {0,85,170,255};
For (int colorNum[]=0; colorNum<256; ++colorNum)
{
logicalPalette.aEntries[coloeNum].peRed =
reds[coloeNum& 0x07];
logicalPalette.aEntries[coloeNum].peGreen =
greens[(coloeNum >> 0x03) & 0x07];
logicalPalette.aEntries[coloeNum].peBlue =
blues[(coloeNum >> 0x06) & 0x03];
logicalPalette.aEntries[coloeNum].peFlags =0;
}
Trong vng lp for, chng trnh thc hin mt s thao tc bit tnh ton cc ch s
(theo cc mng red[], green[], v blue[]) cha cc cng mu in vo mng mu.
Cui cng, bng mu c to bng li gi hm Windows API CreatePalette().
7.8.2.La Chn ,Thc Hin, V Xa B Bng Mu Logic:
Trc khi v ln mn hnh, ng dng phi la chn bng mu vo ng cnh dng c
ri thc hin bng mu. Thc hin bng mu tc l bo cho Windows ly bng mu logic
th hin bng mu h thng.
Trc tin, phi gi hm Windows API SelectPalette() v d:
SelectPalette (pDC->m_hDC, m_hPalette, FALSE);
Hm SelectPalette(0 chn bng mu vo ng cnh dng c.Ba i s ca n l handle
theo DC, handle theo bng mu, v mt gi tr Boolean l true biu thi bng mu lun

lun l bng mu nn (backgroundpalette), hay FALSE biu th bng mu c th l bng


mu cn cnh (foreground palette). Thng thng, gi tr FALSE c dng.
Tip theo, hm WindowsAPI Realizepalette() c gi thc hin bng mu:
RealizePalette (pDC ->m_hDC);
Hm ny c i s n l handle ca ng cnh dng c m bng mu ca n c thc
hin.
Sau , c th to th hin OpenGL, v d:
WglMakeCurrent (pDC ->m_hDC, m_hRC);
DrawWithOpenGL();
WglMakeCurrent (pDC ->m_hDC, NULL);
Cui cng, trc khi kt thc, phi xa bng mu logic to, v d:
If (m_hPalette)
DeleteOject (m_hPalette);
i s n ca deleteOject() l handle theo i tng cn xa.
7.8.3.Kim Tra Khi No Cn To Bng Mu Logic:
Mt ng dng c th c nhiu ng dng khc nhau. Nhng bng mu ch cn to ra khi
h thng i hi. Nh vy, cn kim tra nh dng im v c la chn theo yu cu
bng mu ca h thng.
Sau khi thit lp nh dng im v, cu trc PIXELFORMATDESCRIPTOR
c in y bng cc gi tr nh dng dim v hin hnh. Li gi hm nh sau:
DescribePixelformat (clientDC.m_hDC, pixelformat, sizeof (pfd), &pfd);
Nu thnh phn dwFlags ca cu trc PIXELFORMATDESCRIPTOR c cha c
PFD_NEED_PALETTE, bng mu logic s c to cho ng dng. on m kim tra
nh sau:
If(pfd.dwFlags & PFD_NEED_PALETTE)
SetupLogicalPalette();
7.8.4.p ng Cc Thng Bo Bng Mu:
Khi mt ng dng c kch hot, n c th thc hin bng mu logic ca ring
n. iu ny c th dn n s thay i ln mu sc trong bng h thng, tr nn xa l
vi cc ng dng nn. Gii php cho vn ny l phi cho cc ng dng nn bit v s
thay i ca bng mu h thng, bng thng bo WM_PALETTECHANGED.
Khi ng dng nn nhn c thng bo ny, n thc hin bng mu logic ca n, tc
bo cho Windows th hin li bng mu logic ca n theo bng mu h thng. Do ng
dng ang c tc dng c quyn u tin trc ht v mu sc trn bng mu h thng, nn
d c` s p ng i vi WM_PALETTECHANGED, s th hin ca cc ng dng nn

c th b mt tnh ton vn. Tuy nhin Windows c gng cho s hi ha gia cc bng
mu logic ca ng dng nn vi bng mu h thng mi.
Khi mt nn c kch hot li, n c th i quyn u tin trn bng mu h thng.
Windows bo cho ng dng bit c hi ny bng thng bo
WM_QUERYNEWPALETTE. ng dng tr li thng bo bng cch thc hin bng
mu logic ca n, th hin ton b mu sc ca bng mu logic
vo bng mu h thng. Ti thi im ny, cc ng dng khc, nay l ng dng nn, nhn
thng bo WM_PALETTECHANGED, ri th hin li bng mu logic ca chng theo
bng mu h thng mi.
7.9. Tng kt:
OpenGL cung cp bn loi ngun sng: mi trng khuch tn, phn chiu, v ngun
pht. Th hin ca i tng trn mn hnh ph thuc vo loi ngun sng c trong cnh
v cch phn x nh sng ca i tng. Nh vy chiu sng mt cnh, cn nh ngha
mt hay nhiu ngun sng, v nh ngha tnh cht vt liu ca i tng.
OpenGL c th xc nh gc nh sng chiu vo i tng cn nh ngha php
tuyn ca cc vertex trn tt c a gic to nn i tng. Mt s hm trong th vin
OpenGL auxiliary, cung cp php tuyn ca a gic m n to ra. tnh ton php tuyn
ca a gic bt k, ta dng hm CalcNormal() ni trn.
Mt th hin OpenGL l tt nht khi c dng trn h thng 64.000 mu hoc hn.
Khi chy trn h thng 256 mu, do bng mu 20 mu ca Windows cung cp qu t mu
cho th hin OpenGL, nn ng dng cn to, chn la v thc hin bng mu logic.
Ngoi ra th hin ca n c cp nht chnh xc ng dng phi p ng cc thng
bo WM_PALETTECHANGED v WM_QUERYNEWPALETTE.

Chng 8:To Cnh 3D


Cc chng trc cung cp hu ht cc dung c to bt c cnh 3-D no,
nhng vic t hp mt cnh t hng chc, hng trm, hay hng ngn a gic khng phi
l vic n gin. Ngay c khi s dng cc hnh 3-D to sn nh khi vung, hnh chp v
hnh cu ca th vin OpenGL auxiliary, cng cn phi thc hin cc php bin hnh
t chng vo i tng th hin.
Chng ny trnh by:
- Gc ta cc b v gc ta th gii.
- T hp cc cnh t cc i tng 3-D.
- S dng stack ma trn.
- S dng b m i sinh ng ha cnh 3-D.
8.1.S Dng Cc Php Bin Hnh OpenGL To Cnh 3-D:
Chng ta bit cch cung cp cc php bin hnh bao- gm tnh tin, co gin, v
quay cho i tng. Nhng ch mi l cc i tng n l. Ch cha gii quyt vic sp
t nhiu i tng trn mn hnh v gi cho chng mt t chc logic khi thc hin bin
hnh. y l mt trong nhng vn kh trong ha.
8.1.1. Gc Ta Cc B V Gc Ta Th Gii.

C hai phng php tng tng v cch m php bin hnh i tng
(Modelview transformation) OpenGL tc ng ln cnh 3-D nh th no: theo gc ta
cc b v gc ta th gii, hay theo h ta c nh.
chng ha hai chiu GDI v ha ba chiu GDI, ta lp trnh trn
mt h ta c nh. Tc l khi cung cp php quay cho mt m hnh, ta cho rng ton
b h nh l mt tm nha quay quanh mt trc trung tm, v mi i tng v trn tm
nha th quay theo n.
Khi t hp cc i tng nh vo i tng ln, th cch suy ngh v cc php bin
hnh theo cc gc ta cc b v th gii s n gin hn. Gc ta th gii (world
origin) lun lun l gc ta cc ba chiu. l iu hon ton hp l v h cc
3-D l th gii cha cc cnh c v. Nh vy khi nh ngha cc v tr trong h cc
3-D, cc ta c dng l cc ta th gii (world coordinate), c lin quan n gc
ta th gii.
Trong khi gc ta cc b (locol origin) c t tm i tng v di chuyn
cng i tng. Vi h thng ny c th tng vic xy dng cc i tng 3-D l thay
v di chuyn ton b th gii trc khi t cc phn ca i tng vo v tr, th ta ch t
chng vo v tr trong mt th gii tnh.
Gi s khi to ma trn modelview theo ma trn n v nh sau :
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Ti y, nu gi auxSolidCube(),OpenGL s v mt khi vung 3-D c tm trng vi
tm cc 3-D (hnh 8.1). (Khi v khi vung, OpenGL nhn cc vertex khi vung vi
ma trn moldelview, hin l ma trn n v).

Hnh 8.1
Khi vung v khi
Ta th gii.

Hin nhin l khng c vic v mt t i tng ti


gc ta th gii, m cc i tng phi c t cc v tr khc nhau to nn
cc hnh c ngha. Mt cch thc hin iu l tnh tin, tc di chuyn i tng
vi gc ta cc b ca n n v tr mi.

8.1.2.Php Tnh Tin:


Gi s glTranslatef() c gi thm php tnh tin vo ma trn modelview nh sau:
glTranslatef(1.0f, 0.0f, 0.0f);

Nu gi auxSolidCube() v khi vung th hai, th khi vung s xut hin v


tr cch khi vung th nht mt n v pha bn phi, do ma trn modelview cha php
tnh tin mt n v trn trc X. iu ny ging nh di chuyn gc ta cc b ca
khi vung mt n v v pha bn phi (hnh 8.2).

Hnh 8.2
Khi vung c v
sau khi tnh tin mt
n v theo chiu
dng

Nu tip tc thc hin php tnh tin:


glTranslatef(1.0f, 0.0f, 0.0f);
ri v thm mt khi vung bng li gi auxSolidCube(), Kt qu nhn c s nh
hnh 8.3. Ti sao php tnh tin cui cng ch l mt n v theo chiu dng trc X, m
OpenGL li v khi vung th hai cch gc ta th gii hai n v ? L do l mi
php bin hnh c gi u l b phn ca ma trn modelview hin hnh kiu nh cc
lnh MoveTo().
Hnh 8.3
Khi vung c v
sau li gi php tnh
tin th hai.

on m sau th hin nh hnh 8.4 (gi thit rng chng trnh thit lp im nhn xa
thy c cc khi vung):
auxSolidCube(0.5f);
glTranslatef(1.0f, 0.0f, 0.0f);
auxSolidCube(0.5f);
glTranslatef(1.0f, 0.0f, 0.0f);
auxSolidCube(0.5f);
Hnh 8.4: Th hin OpenGL
ca ba khi vung
Tt nhin l c th tnh tin theo

mi hng, trn mi trc. V d on m sau cho hnh 8.5, c th hin OpenGL nh hnh
8.6:
glTranslatef(-1.0f, 1.0f,-1.0f);
auxSolidCube(0.5f);

Hnh 8.5:Thm php tnh tin


v khi vung th t

Hnh 8.6:OpenGL
ca bn khi vung

8.1.3.Php Quay:
Tc dng ca php tnh tin th d hiu. Nhng i vi php quay th khng nh vy,
v php quay thay i hng cc trc cc b ca i tng. V d xt khi vung trong
hnh 8.7 . Sau khi quay 900 trn trc Y, hng ca khi vung nh hnh 8.8, ngha l cc
trc X v Z i hng cho nhau. Ngha l nu mun tnh tin khi vung sang bn
phi mn hnh, ta phi tnh tin n theo hng dng trc Z, ch khng phi theo hng
dng trc X.

Hnh 8.7:Khi vung trc


khi quay

Hnh 8.8: Khi vung sau


khi quay 900 trn trc Y

iu cn nh l sau khi c thc hin, php quay tip tc tn ti trong ma trn


modelview cho n khi ma trn ny c khi to li. Xt an m sau:
glTranslatef(1.0f, 0.0f, 0.0f);
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
auxSolidCube(0.5f);
glTranslatef(0.0f, 0.0f, 1.0f);
auxSolidCube(0.5f);
Dng u tin tnh tin gc ta cc b mt n v theo chiu dng trc X (tc sang
phi, gi s im nhn lc u nhn theo hng m trc Z). Sau dng th hai quay gc
ta cc b quanh trc Y, ri dng th ba v khi vung. Lc ny, v khi vung
th hai bn phi khi th nht, ta phi tnh tin theo trc Z ch khng phi trc X nh
dng th t. Do khi vung th hai quay tng t khi vung th nht, nn trc Z ca n
s chy t tri sang phi.
Trong trng hp h ta c nh, vic s dng cc php bin hnh phi c hiu
theo cch ngc li vi trng hp h ta cc b. V d, khi s dng h ta cc b,
nu gi glTranslatef() tnh tin theo trc dng trc X, ri gi glRotatef() quay
quanh trc Z, th hnh v vn nm trn trc X sau khi quay. Nhng nu glRotatef()
c gi trc, th hnh s nm gia cc trc X v Y. Cn i vi h ta c nh th
sao ?
Hy tng tng mt tm nha trong vi khi vung bng g ti gc ta . Trn mt
bn pha di tm nha, ta v cc trc X v Y.(hay ni cch khc, khi tm nha quay
quanh trc Z ti gc ta , cc trc X,Y vn c nh). Trc tin, tm nha c quay
quanh gc ta c nh. Sau khi quay khi vung vn gc ta . By gi php tnh
tin c thc hin bng cch trt tm nha sang phi. Khi vung di chuyn cng vi
tm nha nhng vn trn trc X. Nu gi glTranslatef() trc glRotatef(), tm nha di
chuyn sang phi, ri mi quay quanh gc ta c nh trn bn. Nh vy, khi vung
quay cng vi tm nha s nm u gia cc trc X v Y.
(Trong trng hp gc ta cc b, ta khng di chuyn tm nha, m ch di chuyn
khi vung.)
8.2.S Dng Cc Stack Ma Trn:
S tht l hu ch nu c kh nng thit lp mt ma trn modelview lm ma trn nn,
dng n thc hin cc php bin hnh, ri tr li ma trn nn, theo trng thi ban u
ca n. V d ta mun thit lp im nhn lc bt u chng trnh, sau khng phi
quan tm n n na. Nhng mi php bin hnh c thc hin sau khi thit lp im
nhn s thay i ma trn modelview, m ma trn ny cha php bin i im nhn. C
ngha l phi khi to li im nhn ln thay i cnh k tip.

Nhng OpenGL c cch lu tr v han tr ni dung mt ma trn, l s dng cc


stack ma trn. Stack ma trn th tng t nh stack m my tnh s dng, nhng cha cc
gi tr cho cc ma trn lin quan, thay v cc kiu d liu dng cho stack my tnh. Mi
ma trn bin hnh c stack ma trn ring. lu ni dung ma trn hin hnh, ch n
gin thc hin li gi hm sau:
glPushMatrix();
Sau khi y ma trn hin hnh vo pha trn stack ma trn, ta c th thc hin mi
php bin hnh m khng lo ma trn gc b bin i. Khi mun tr li ma trn gc, l gi
sau c thc hin:
glPopMatrix();
C hai hm trn u khng c i s. Chng lun lun tc ng n ma trn hin c
chn. V d cc dng sau lu ni dung ma trn modelview:
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
Cn cc dng sau lu ni dung ma trn chiu:
glMatrixMode(GL_PROJECTION);
glPushMatrix();
S dng cc thao tc stack ma trn trn, ta d dng thit lp mt ma trn modelview c
s nh ngha mt im nhn, v tr n v khi cn thit. Khi bt u chng trnh
(trong chng trnh MFC l hm OnCreate()), cc li gi hm nh sau:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 2.0, 9.0);
glViewport(0, 0, cx, cy);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f ,-5.0f);
Bn dng u tin thit lp khng gian quan st v viewport. Trong khi ba dng sau
nh ngha im nhn bng cch di chuyn mt 5 n v theo chiu m trc Z. (Thc
ra l di chuyn ra xa mt gc ta cc b ca bt k i tng no c v).
v cnh m khng lm thay i ni dung ma trn modelview (l ma trn ang cha
php bin hnh thit lp im nhn), th phi lu n trc khi thc hin bt k php bin
i no:
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(1.0f, 0.0f ,0.0f);
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
auxSolidCube(0.5f);
glTranslatef(0.0f, 0.0f ,1.0f);
auxSolidCube(0.5f);
glPopMatrix();
an m trn lu ma trn modelview, thc hin cc php bin hnh cn thit v i
tng, sau tr li ma trn modelview, xa mi php bin hnh thc hin sau li gi

glPushMatrix(). ln thc hin bin hnh tip theo, php bin hnh s khng nh hng
bi cc php bin hnh trc. Nh vy ta c th thy stack ma trn c gi tr ln lao khi
to o gic chuyn ng OpenGL, v khi cc php bin hnh tng t nhau s c
gi lp i lp li vi cc gi tr khc nhau.
Mi loi ma trn c stack ma trn ring. Chng hn ma trn modelview c stack ring,
v ma trn chiu c stack ring. Khi gi glPushMatrix(), thc cht l bn sao ca ma trn
hin ti c y vo nh stack ma trn ca ring n, v ta c hai ma trn n v trn
nh stack. Khi gi glPopMatrix(), OpenGL loi b bn sao, lc ny c th b thay
i, v li ma trn gc trn nh stack.
an m sau y th hin mt ngi my nh hnh 8.9:
GLfoat materialAmbDiffGreen[]={0.2f, 0.8f, 0.5f, 1.0f};
GLfoat materialAmbDiffRed[]={1.0f, 0.0f, 0.0f, 1.0f};
GLfoat materialAmbDiffGray[]={0.2f , 0.2f, 0.2f, 1.0f};
GLfoat materialAmbDiffBlue[]={0.0f, 0.0f, 1.0f, 1.0f};
//Save the base tranformatin.
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
//Draw the robots body
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialAmbDiffGreen);
auxSolidCube(1.0f);
glTranslatef(0.0f, -1.1f ,0.0f);
auxSolidCube(0.9f);
//Draw the robots head
glTranslatef(0.0f, 2.1f ,0.0f);
auxSolidCube(0.75f);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialAmbDiffGray);
glTranslatef(0.0f, -0.1f ,0.6f);
auxSolidCube(0.25f);
glTranslatef(-0.2f, 0.3f ,0.0f);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialAmbDiffBlue);
auxSolidCube(0.2f);
glTranslatef(0.4f, 0.0f ,0.0f);
auxSolidCube(0.2f);
//save the robots transformation.
glPushMatrix();

//Draw the robots right arm.


glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialAmbDiffRed);
glTranslatef(-0.7f, -1.2f ,0.0f);
glRotatef(90.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
glTranslatef(0.0f, 1.0f ,0.0f);
glRotatef(-45.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
glTranslatef(0.0f, 1.0f ,0.0f);
glRotatef(-45.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
//restore the body transformation.
glPopmatrix();
//Draw the robots left arm.
glTranslatef(0.3f, -1.2f ,0.0f);
glRotatef(-90.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
glTranslatef(0.0f, 1.0f ,0.0f);
glRotatef(45.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
glTranslatef(0.0f, 1.0f ,0.0f);
glRotatef(45.0f, 0.0f ,0.0f, 1.0f);
auxSolidCylinder(0.15f, 0.8f);
//restore the base transformation.
glPopMatrix();

Hnh 8.9: Ngi my OpenGL

on m bt u bng vic nh ngha


cc
mng dng cho vt liu i tng trong cnh. Ma trn modelview c la chn. Sau
bn sao ca n c y vo pha trn stack ma trn modelview. Nh vy lc ny trn
stack c hai bn sao ma trn bin i hin hnh (cha php bin i im nhn dng
mi ch trong chng trnh).
K tip on m gi glmaterialfv() thit lp cc tnh cht vt liu, v v hai khi
vung th hin thn ngi my. Khi vung th hai c t di khi vung th nht
bng php tnh tin.

v u robot, trc tin on m tnh tin theo phng Y, ri v khi vung


trn khi vung th nht ca phn thn mt v mi c v sau khi thit lp cc tnh cht
vt liu v thc hin php tnh tin.
n y, stack ma trn modelview cha ma trn gc (l ma trn ch c php bin
i im hnh ), v trn nh ca n l bn sao ma trn gc c thay i (cha php
bin i im nhn v php bin hnh khc ). Do cc tay ngi my c v tng quan
vi thn, nn on m gi glPushMatrix( ) lu trng thi hin ti ca php bin i.
Nh vy, stack ma trn modeliview by gi cha mt ma trn gc, v hai bn sao php
tnh tin hnh ngi my.
Tip theo vic v cnh tay tri bt u bng hm glMaterialfv( ) xc nh tnh
cht vt liu mt php tnh tin v mt php quay thit lp ma trn modelview v on
th nht ti mt gc chnh xc vi thn v li gi auxSolidCylinder( ) thc s v on
tay ny. Cc on cn li ca tay tri c v vi php tnh tin v quay tng t.
Sau khi hon tt vic v cnh tay tri, li gi glPopMatrix ( ) loi b ma trn ang
cha cc php bin hnh dng cho cnh tay tri ra khi stack ma trn, khi phc li trng
thi ma trn sau khi va v song thn v u ngi my. Ri on m v tip cnh tay
phi. Cui cng glPopMatrix ( ) c gi stack ma trn ch cn cha ma trn gc.
8.3. To Ao Gic Chuyn ng Vi OpenGL:
Cc cnh 3- D s tr nn sng ng khi b m i c dng. V trong trng hp
ny, stack ma trn t bit hu dng.
8.3.1. Gii Thiu B m i:
Vic thit k o gic chuyn ng nhp nhng lun l s thch thc i vi ngi lp
trnh. Trc tin, chng trnh phi c kh nng v 30 hnh (hay khung) trong mt
giy, to s chuyn ng uyn chuyn. iu ny i hi phn cng c tc cao v
chng trnh c thit k tt. K tip, mi vic phi v khut, v mi khung hnh phi
to c s chuyn ng i vi mt ngi dng. May thay, vn tc ngy cng tr
nn t quan trng khi my tnh ngy cng nhanh hn. Cn gii php cho vn th hai l
s dng b m i .
Vi b m i, hai vng nh c s dng to o gic chuyn ng. Mt vng
cha nh trn mn hnh. Trong thi gian vng b m ny ang c th hin, khng
lnh v no c dng sa i n. Vng th hai c s dng chng trnh v
vo, nhng khng c th hin trn mn hnh. Nn ngi dng khng thy cc thao tc
v. Sau khi vic v hon tt, chng trnh ch n gin hon i cc b m.
8.3.2. B m i Trong OpenGL:
Trong OpenGL, cc b m trong b m i c gi l b m trc (b m
khng thy c). Khi thit lp b m i OpenGL, mi lnh v s lun lun n b
m sau hin hnh, nh vy ngi dng s khng thy thao tc v. Khi chng trnh v
xong nh, n hon i b m trc v sau lm xut hin nh mi trn mn hnh. Sau
chng trnh to khung hnh k tip trong b m sau mi, ri li hon i cc b
m. Qa trnh ny tip din trong sut ton b thi gian o gic chuyn ng c thc
hin, v vic hon i gia cc b m c thc hin nhiu ln trong giy.

8.3.3. S Dng B m i:
Mc d vic qun l b m i l k thut kh trong lp trnh ha thng thng
OpenGL thc hin iu ch vi hai thay i nh trong chng trnh. Trc tin
OpenGL phi c thng bo thit lp mi trng b m i. Vic ny c thc hin
bng cch thm c PFD_DOUBLEBUFFER vo thnh phn dwFlags ca cu trc
PIELFORMATDESCRIPTOR nh sau:
PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR), // Kch thc cu trc.
1,
//S version ca cu trc.
PFD_DRAW_TO_WINDOW |
// cc c thuc tnh
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
// 24 bit mu
0, 0, 0, 0, 0, 0,
// khng chn la cc ch .
0,0,0, 0, 0, 0,0,0
32
// b m chiu su 32 bit
0,0,
// khng dng b m stencil hay b m ph tr
PFD_MAIN_PLANE,
//kiu lp ch yu
0,
0, 0, 0
};
Nh vy, ta
ch
n
gin
s
dng
php ton OR c
PFD_DOUBLEBUFFER vi cc c khc trong thnh phn cu trc dwFlags.
Mt thay i khc cn c li gi hm SwapBuffers() sau khi chng trnh v xong
hnh mi. Li gi ny i b m sau (l b m va c v vo) thnh b m trc,
v nh vy ngi dng thy c hnh mi. Cn b m trc tr thnh b m sau, v
mi lnh v trc li gi SwapBuffers() k tip s c tc dng vi n.
8.4.Tng Kt:
Vic sp xp cc hnh dng vo mt cnh 3-D ch l vn s dng cc php tnh tin
v quay nh v tng i tng.
d dng tng tng v php bin hnh yu cu, th ta dng cc gc ta th gii
v cc b. iu quan trng phi ghi nh mi php bin hnh c thc hin s tr thnh
mt phn ca ma trn modelview hin hnh. Cc php bin hnh ny tip tc c tc dng
cho n khi ma trn b xa, bng li gi glLoadIdentity() hay bng cch khi phc ma
trn c lu gi trong stack ma trn.
to mt cnh chuyn ng, OpenGL dng b m i. Trong , b m trc
cha cnh ang c th hin trn mn hnh, cn b m sau cha cnh ang c v.
Vic hon i gia cc b m s chuyn cnh mi ra mn hnh.

Chng 9: Anh V Gn Cu Trc:

Trong lp trnh ha thng phi gii quyt cc nh c nhiu chi tit hn l ta c th


v vi OpenGL. V d nh mc d c th mt hnh ch nht th hin mt bn, nhng a
gic c in y khng c cc chi tit nh l th g, c th th hin l mt bn.
cung cp cc chi tit nh vy, ta s dng cc nh OpenGL thc hin gn cu trc
(texture mapping) cho cc i tng.
Nhng trc khi tm hiu texture mapping, ta cn bit v cc nh OpenGL v cch s
dng cc bitmap c - lp - vi - thit- b (DIBs, device independent bitmaps). Hai
kiu d liu ha ny cho php to cc hnh nh bng cch sao chp cc hnh ch nht
t b nh, hay v chng bng mt chng trnh v. Mt khi c cc nh trong b nh, ta
c th s dng chng nng cp cc cnh 3-D.
Chng trnh ny trnh by:
Bitmap v nh OpenGL.
Lm th no np bitmap c - lp - vi - thit b.
Bng danh sch mu v cc phng thc chuyn di pixel.
Cch thit lp texture mapping OpenGL.
Cch thc hin texture mapping mt a gic
9.1.Bitmap v nh OpenGL.
OpenGL h tr hai loi i tng ha. Loi u tin l bitmap, l mt mask n sc
dng to c th n gin nh cc k t trong mt font. Loi th hai l nh, l bitmap y
mu sc, v c th cha ng mt hnh tng hay mt bc tranh y chi tit.
Khng may l cc loi my khc nhau lu tr nh theo cc cch khc nhau. Do l th
vin chun, OpenGL phi c cch h tr bt c kiu lu tr hnh nh no, nn n nh
ngha mt s hng kiu pixel nh bng 9.1.
Bng 9.1: Cc hng s kiu pixel OpenGL
Hng s
GL_ALPHA
GL_BLUE
GL_COLOR_INDEX
GL_DEPTH_COMPONENT
GL_GREEN
GL_LUMINANCE
GL_LUMINANCE_ALPHA
GL_RED
GL_RGB
GL_RGBA
GL_STENCIL_INDEX

ngha
Mi pixel l mt phn t mu alpha
Mi pixel l mt phn t mu xanh dng
Mi pixel l mt ch s mu
Mi pixel l mt phn t chiu su
Mi pixel l mt phn t mu xanh l
Mi pixel l mt phn t luminance
Mi pixel l mt phn t mu alpha v luminance
Mi pixel l mt phn t mu
Mi pixel l mt phn t mu , xanh l, xanh lc
Mi pixel l mt phn t mu , xanh l, xanh
lc,v alpha
Mi pixel l mt ch s stencil

Ngoi ra, kch thc d liu th hin mt phn t nh n th thay i gia cc nh


v gia cc my, nn OpenGL nh ngha mt s hng kiu d liu nh bng 9.2.
Bng 9.2: Cc hng s kiu d liu OpenGL

Hng s
GL_BITMAP
GL_BYTE
GL_FOAT
GL_INT
GL_SHORT
GL_UNSIGNED_BYTE
GL_UNSIGNED_INT
GL_UNSIGNED_SHORT

ngha
S nguyn 8-bit khng du cha d liu bit n
S nguyn 8-bit c du
Du chm ng chnh xc n
S nguyn 32-bit c du
S nguyn 16-bit c du
S nguyn 8-bit khng du
S nguyn 32-bit khng du
S nguyn 16-bit khng du

9.1.1.c Anh OpenGL:


OpenGL cung cp ba hm c bn thao tc d liu nh: glReadPixel(),
glDrawPixel(), v glCopyPixels(). Hm glReadPixel() sao chp hnh ch nht t b m
mu v lu tr d liu trong b nh. V d cc dng sau nh ngha kho cha nh v c
d liu nh t b m mu hin hnh vo kho:
Glubyte image[64][64][3];
glReadPixels(0, 0, 64, 64, GL_RGB, GL_UNSIGNED_BYTE, image)
on m trn nh ngha kho nh mng ba chiu lu tr nh 64x64 gm ba thnh phn
pixel, trong trng hp ny l cc gi tr RGB. Hm glReadPixels() c d liu nh t
b m mu v lu tr trong mng image[][][]. By i s ca hm l cc ta X, Y
ca gc tri di hnh ch nht, chiu rng v chiu cao ca hnh ch nht, kiu pixel v
kiu d liu ca pixel c c, cui cng l a ch lu tr d liu nh. Li gi trn c
mt nh 64x64 t gc tri di ca b m mu. Anh ny c th hin bi cc phn t
mu , xanh l, v xanh lc lu tr nh cc byte khng du.

9.1.2.V Anh OpenGL:


Mt khi c d liu nh trong b nh, c th dng hm glDrawPixel() th hin d
liu ln mn hnh. Anh lu bng on m trc c th hin vi li gi nh sau:
glDrawPixels(64, 64, GL_RGB, GL_USIGNED_BYTE, image );
Hm glDrawPixels() th hin nh ti v tr raster hin ti. Nm i s ca hm l chiu
rng v chiu cao nh, kiu pixel v kiu d liu ca d liu nh v a ch nh.
kim sot v tr raster m ti glDrawPixel() th hin d liu nh, ta dng hm
glRasterPos3f() nh sau:
glRasterPos3f(1.0f, 1.0f, 0.0f);
Hm ny thit lp v tr raster hin hnh bng ba i s X, Y, Z. Cc gi tr ny khng
phi l cc ta mn hnh nh trong hm glReadPixels(), m la cc ta cc c
bin i sang ta mn hnh bi cc php bin hnh i tng v phi cnh.
glRasterPos() c 24 phin bn.
9.1.3.Tm Hiu Thao Tc Anh:

on m sau to mt nh RGB trong b nh, th hin nh gc di tri ca s, sao


chp nh vo mt vng nh khc, v th hin bn sao gc trn phi ca s nh hnh
9.1:
Glubyte image1[64][64][3];
Glubyte image2[64][64][3];
for (int i = 0; i < 64; i++)
for(int j = 0; j < 64; j++)
{
image1[i][j][0]=(GLubyte) 0;
image1[i][j][1]=(GLubyte) 0;
image1[i][j][2]=(GLubyte) (255-i*3.5);
}
glRasterPos3f(-1.0f,- 1.0f, 0.0f);
glDrawPixels(64, 64, GL_RGB, GL_UNSIGNED_BYTE, image1);
Glint rasPos[4];
glGetIntegerv(GL_CURRENT_RASTER_POSITION, rasPos);
glReadPixels(rasPos[0],rasPos[1],64,64,GL_RGB,
GL_UNSIGNED_BYTE, image2);
glRasterPos3f(1.0f, 1.0f, 0.0f);
glDrawPixels(64, 64, GL_RGB, GL_UNSIGNED_BYTE, image2);
glFlush();

Hnh 9.1: c v v
cc nh OpenGL

Vng lp for trong an m trn to mt nh t cc ng thng xanh dng xp


t sng ti y n m nh. (Anh c lu tr o ngc trong b nh, nn cc byte
u tin trong mng s y nh). Sau khi to nh, on m thit lp v tr raster v v
nh ti v tr mi.
sao chp nh, chng trnh cn bit cc ta ca s ca nh. Nhng
glRastePos3f() s dng cc ta cc. Vy lm th no bit cc ta cc c
bin i sang cc ta mn hnh ra sao? iu c thc hin nh hm
glGetInteger() vi i s l hng GL_CURRENT_RASTER_POSITION v a ch ca
mng bn phn t, m hm lu tr v tr raster hin hnh trong ta ca s.

Sau khi cc ta ca s ca nh, an m c nh vo mng th hai, image[][][]. Sau


thit lp li v tr raster v th hin nh mi, chng t bn gc thc s c sao chp.
Tt nhin gi thuyt rng khng gian quan st v im nhn c thit lp ng n. Nu
khng ta s thy g trn mn hnh.
9.1.4.Sao Chp Anh OpenGL:
Hm glCopyPixels() cho php sao chp nh t ni ny sang ni khc trn mn hnh m
khng cn trc phi c nh vo b m. C th ni li gi glCopyPixels() tng t
nh li gi c hai hm glReadPixels() v glDrawPixels(), m khng i hi kho cha
ph tr. Nu s dng glCopyPixels(), on m trn c vit li nh sau:
Glubyte image1[64][64][3];
for (int i = 0; i < 64; i++)
for(int j = 0; j < 64; j++)
{
image1[i][j][0]=(GLubyte) 0;
image1[i][j][1]=(GLubyte) 0;
image1[i][j][2]=(GLubyte) (255-i*3.5);
image1[i][j][3]=(GLubyte) 1;
}
glRasterPos3f(-1.0f,- 1.0f, 0.0f);
glDrawPixels(64, 64, GL_RGB, GL_UNSIGNED_BYTE, image1);
Glint rasPos[4];
glGetIntegerv(GL_CURRENT_RASTER_POSITION, rasPos);
glRasterPos3f(1.0f, 1.0f, 0.0f);
glCopyPixels(rasPos[0], rasPos[1], 64, 64, GL_COLOR);
glFlush();
Phin bn ny ngn hi v yu cu b nh t hn. Hm glCopyPixels() c cc i s l
cc ta c s X, Y ca hnh ch nht c sao chp, chiu rng v chiu cao ca hnh
ch nht, v kiu d liu sao chp. Kiu d liu sao chp c th l GL_COLOR,
GL_DEPTH, hoc GL_STENCIL. Trong trng hp GL_COLOR, OpenGL sao chp
hnh ch nht nh l d liu GL_RGBA hay GL_COLOR_INDEX, ty thuc ch
mu hin hnh ca h thng. Trong cc trng hp khc, OpenGL sao chp hnh ch
nht nh l d liu GL_DEPTH_COMPONENT hay GL_STENCIL_INDEX.
Nh vy x l nh OpenGL th kh d. Nhng vic th hin bitmap Windows thng
xy ra hn vic th hin nh OpenGL. Do , phn tip theo l trnh by cch ti bitmap
Windows vo b nh, ni OpenGL s c dng thao tc chng.

9.2.Bitmap Phc Thuc Thit B V Bitmap c Lp Vi Thit B:

Khi lp trnh trong Windows, bitmap khp ni, do nh dng BMP l nh dng
ha duy nht m Window h tr trc tip. Cc hm nh CreateBitmap(), LoadBitmap(),
StetchDIBits() v BitBIt() trong lp trnh Windows cho php to, ti hay th hin bitmap
ln mn hnh. Trong khi khng c hm tng t cho c kiu dng ha khc.
C hai lai windows bitmap:
Bitmap ph thuc thit b (Device dependent bitmap) l cc nh ha ch
c th hin trn mt loi thit b vt l duy nht. V d cc hm Windows
nh CreateBitmap() v LoadBitmap() to trong b nh mt nh bitmap
tng thch vi thit b nht nh, thng l mn hnh. Cc loi bitmap nh
vy i khi c gi l GDI bitmap, do giao din thit k ha Windows
c th thao tc chng mt cch trc tip. Bitmap ph thuc thit b c lu
tr m khng c bng danh sch mu (color table), do chng s dng mu
ca thit b m chng kt hp. Ngoi ra, bitmap ph thuc thit b ch tr ng
trong b nh, ch khng th ta file trn a.
Bitmap c lp vi thit b (Device independent bitmap, DIB) l cc nh
ha c th th hin trn nhiu loi thit b vt l khc nhau. Cc loi bitmap
ny mang theo bng danh sch mu thit b hin hnh s dng khi th
hin chng. Nh vy cc th hin ca bitmap c lp vi thit b trn cc
thit b khc nhau l nh nhau. V d th hin ca mt bitmap c lp vi
thit b trong Windows hay DOS hay OS/2 s nh nhau. Do bitmap c lp
vi thit b c tnh c ng gia cc h thng, chng thng c dng file trn
a. V d c th tm thy trong th mc Windows, nhiu file c phn m
rng BMP, l cc bitmap c lp vi thit b. C th ta cc bitmap c lp
vi thit b bng cch s dng cc loi chng trnh v khc nhau, k c
Windows PaintBrush, hay s dng phn bin son bitmap ca Visual C++.
9.3.nh Dng DIB:
D lu tr trn a hay trn b nh th cu trc ca DIB khng thay i. Mt DIB c
to thnh t nhiu kiu cu trc khc nhau ni tip nhau. Cc kiu cu trc ny bao gm
BITMAPFILEHEADER, BITMAPINFO, BITMAPINFOHEADER, v RGBQUAD.
9.3.1.Cu Trc BITMAPFILEHEADER:
Khi u mt DIB file l cu trc BITMAPFILEHEADER, c nh ngha bi
Windows nh sau:
Typedef struct tagBITMAPFILEHEADER
{
WORD
bfType;
DWORD bfSize;
WORD
bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;

Cu trc ny bt u mt file DIB trn a, nhng khng cn thit trong trng hp


bitmap trong b nh. Thnh phn u tin ca cu trc,bfType l m ASCII ca cc ch
ci BM, cho bit file l bitmap. Trong h thp lc phn, dfType l 4D42. Vi cc gi tr
khc, file khng phi l bitmap. Thnh phn th hai, bfSize l kch thc file bitmap tnh
theo byte. Tuy nhin, do s khng r rng trong ti liu Windows gc, bfSize th khng
ng tin cy v c th b qua. Ngoi ra, thnh phn bfOffBits cha s byte t u bitmap
file n d liu bitmap.
Bng 9.3 Cu trc BITMAPFILEHEADER
Thnh phn
BfType
BfSize
BfReserved1
BfReserved2
BfOffBits

Kiu d liu
WORD
DWORD
WORD
WORD
DWORD

M t
Cha gi tr ASCII ca cc ch ci BM
Kch thc file
Bng 0
Bng 0
S byte t u file n d liu bitmap

9.3.2.Cu Trc BITMAPINFO:


Theo sau cu trc BITMAPFILEHEADER l cu trc BITMAPINFO, c Windows
nh ngha nh sau:
Typedef struct tagBITMAPINFO
{
BITMAPFINFOHEADER bmiHeader;
RGBQUAD bmiColors[1];
}BITMAPINFO;
Cu trc ny gm mt header, th hin bi cu trc BITMAPFINFOHEADER,
v mt bng danh sch mu (color table), th hin bi mt mng ca cu trc
RGBQUAD.
9.3.3.Cu Trc BITMAPFINFOHEADER:
Cu trc BITMAPFINFOHEADER c Windows nh ngha nh sau:
Typedef struct tagBITMAPFINFOHEADER
{
DWORD biSize;
DWORD biWidth;
DWORD biHeight;
DWORD biPlanes;
DWORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
DWORD biXPelsPerMeter;
DWORD biYPelsPerMeter;

DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPFINFOHEADER;
biSize cha kch thc ca cu trc BITMAPFINFOHEADER, thng l 40 byte.
biWidth v biHeight l chiu rng v chiu cao bitmap theo pixel. biPlanes lun lun
bng 1. biBitCount biu th s bit trn mt pixel, c th l 1, 4, 8, hay 24, tng ng vi
nh n sc, 16 mu, 256 mu hay 16.7 triu mu.
biCompression cho bit kiu nn c dng vi nh bitmap, vi 0 l khng nn, 1
tng ng kiu nn RLE-8, v 2 tng ng kiu nn RLE-4. Rt him khi nn DIB, m
thng l biCompression mang gi tr 0.
biSizeImage l kch thc bitmap theo byte v ch dng bitmap nn. Gi tr ny
lu tm n s byte trong mi dng ca bitmap phi lun l bi s ca 4. Nu cn cc
byte trng s c m vo dng m bo iu . Tuy nhin tr khi vit chng
trnh to file DIB, ta khng phi x l vic thm vi dng v s phc tp ca m sinh ra
t n.
Cc thnh phn biXPelsPerMeter v biXPelsPerMeter cha s pixel ngang v dc
trn mt, nhng thng thit lp bng 0. biClrUsed v biClrImportant cha tng s mu
dng trong bitmap v s mu quan trng trong bitmap, cng thng thit lp bng 0.
Ch rng cc thnh phn ca cu trc BITMAPFINFOHEADER sau biBitCount
thng bng 0, nn khi c cu trc t file, c th b qua cc gi tr ny. iu cn bit
l cch tnh cc gi tr cn thit nh s mu dng trong nh v cch lu tr chng trong
cc thnh phn thch hp truy xut v sau.
Bng 9.4 Cu trc BITMAPFINFOHEADER
Thnh phn
BiSize
BiWidth
BiHeight
BiPlanes
BiBitCount
BiCompression
BiSizeImage
BiXPelsPerMeter
BiYPelsPerMeter
BiClrUsed
BiClrImportant

Kiu d liu
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD
DWORD

M t
Kch thc cu trc theo byte ( 40 byte)
Chiu rng bitmap theo pixel
Chiu cao bitmap theo pixel
Lun lun bng 1
S bit ca mt pixel. L 1, 4, 8, hay 24
Kiu nn:0 =khng nn, 1=RLE-8, 2=RLE-4
Kch thc bitmap theo byte
S pixel ngang trn mt
S pixel dc trn mt
S mu c dng
S mu quan trng

9.3.4.Cu Trc RGBQUAD:


Cu trc RGBQUAD c Windows nh ngha nh sau:
Typedef struct tagRBGQUAD
{
BYTE rgbBlue;

BYTE rgbGreen;
BYTE rgbRed;
BYTE rgbReserve;
}RGBQUAD;
Cu trc ny cha cng cc thnh phn mu , xanh dng, xanh lc. Mi mu
trong DIB c th hin bi mt cu trc RGBQUAD. Tc l bitmap 16 mu (4 bit) c
mt bng danh sch mu gm 16 cu trc RGBQUAD. Trong khi bitmap 256 mu (8 bit)
c mt bng danh sch mu gm 256 cu trc RGBQUAD. Ngoi tr nh 24 bit mu th
khng c bng danh sch mu.
Sau cu trc BITMAPINFO ca DIB l d liu nh. Kch thc d liu tt nhin ph
thuc kch thc nh. Hnh 9.2 th hin ton b b tr ca mt DIB file.
BitmapFileHeader
BitmapInfoHeader
Bitmapinfo
Rgbquad[256]
Image Data
Hnh 9.2 Cu trc DIB
9.4.Gii Thiu Lp CDib:
Mc d Visual C++ m t lp cho nhiu i tng ha, nhng khng c lp no
cho DIB. Vi mt lp qun l DIB s gip t chc m vo cc module s dng nhiu
ln. Do ta s xy dng mt lp n gin, vi tn gi Cdib, c cc CDib t a vo
b nh, v tr v thng tin quan trng v DIB.
9.4.1.Giao din lp CDib:
Giao din lp CDib c th hin bi header file trong bng k 9.1 nh sau:
Bng k 9.1: CDib.h
#ifndef _ _CDIB_H
#define _ _CDIB_H
class CDib : public CObject
{
protected:
LPBITMAPINFOHEADER m_pBmInfoHeader;
LPBITMAPINFO m_pBmInfo;
LPBITMAPFILEHEADER m_pBmFileHeader;
BYTE* m_numColors;
RGBQUAD* m_pRGBTable;
BYTE* m_pDibBits;
public:
CDib(const char* fileName);
~CDib();

DWORD GetDibSizeImage();
UINT GetDibNumColors();
UINT GetDibHeight();
UINT GetDibWidth();
LPRGBQUAD GetDibRGBTablePtr();
LPBITMAPINFO GetDibInfoPtr();
LPBITMAPINFOHEADER GetDibInfoHeaderPtr();
BYTE* GetDibBitsPtr();
protected:
void LoadBitmapFile(const char* fileName);
};
#endif
Cc thnh phn d liu lp CDib hu ht l cc con tr tr n cc phn khc nhau
DIB. Cc con tr ny cha a ch cc cu trc BITMAPINFO, BITMAPFILEHEADER,
v BITMAPINFOHEADER, cng nh a ch bng danh sch mu v d liu nh.
Thnh phn m_numColors cha s mu trong DIB.
Nh hu ht cc lp, CDib c hm to v hm hy. Theo khai bo hm to, mt i
tng CDib c to bng cch truyn tn file ca bitmap cn ti cho hm.
Lp CDib m t tm hm thnh vin chung, cho php ta c thng tin quan trng v
Dib sau khi ti n. Bng k 9.5 lit k cc hm trn v nhim v ca chng.
Cui cng hm thnh vin protected LoadBitmapFile() ca lp CDib c dng gi
ni b ti file DIB. Hm ny khng th gi trc tip.
Bng k 9.5: Cc hm thnh vin chung ca lp CDib
Tn hm
GetDibSizeImage()
GetDibWidth()
GetDibHeight()
GetDibNumColors()
GetDibInfoHeaderPtr()
GetDibInfoPtr()
GetDibRGBTablePtr()
GetDibBitsPtr()

M t
Tr v kch thc nh theo byte
Tr v chiu rng DIB theo pixel
Tr v chiu cao DIB theo pixel
Tr v s mu trong DIB
Tr v con tr tr n cu trc BITMAPINFO
HEADER
Tr v con tr tr n cu trc BITMAPINFO
Tr v con tr tr n bng danh sch mu
Tr v con tr tr n d liu nh

9.4.2.Lp Trnh Lp CDib:


on m trong CDib.cpp bng k 9.2 nh ngha lp CDib.
Bng k 9.2: CDib.cpp
//////////////////////////////////////////////////////

// CDib.cpp : implementation file


//////////////////////////////////////////////////////
#include "stdafx.h"
#include "DibView.h"
#include "CDib.h"
#include "windowsx.h"
//////////////////////////////////////////////////////
// CDib ::CDib()
/////////////////////////////////////////////////////
CDib::CDib(const char *fileName)
{
//load the bitmat and initialize the class's data members.
LoadBitmapFile(fileName);
}
//////////////////////////////////////////////////////
// CDib ::~CDib
/////////////////////////////////////////////////////
CDib::~CDib()
{
//Free the memory assigned to the bitmap.
GlobalFreePtr(m_pBmInfo);
}
//////////////////////////////////////////////////////
// CDib ::LoadBitmapFile()
/////////////////////////////////////////////////////
void CDib::LoadBitmapFile(const char *fileName)
{
//Construct and open a file object
CFile file(fileName, CFile::modeRead);
//Read a bitmap's file header into memory
BITMAPFILEHEADER bmFileHeader;
file.Read((void*)&bmFileHeader,sizeof(bmFileHeader));
//Check whether the file is really a bitmap
if(bmFileHeader.bfType!=0x4d42)
{
AfxMessageBox(" Not a bitmap file");
m_pBmFileHeader=0;
m_pBmInfo=0;
m_pBmInfoHeader=0;
m_pRGBTable=0;
m_pDibBits=0;
m_numColors=0;
}

//
else
{ //Calculate the size of the DIB,which is the
// file size minus the size of the file hear
DWORD fileLength=file.GetLength();
DWORD dibSize=fileLength-sizeof(bmFileHeader);
// Allocate enough memory to fit the bitmap.
BYTE* pDob=(BYTE*)GlobalAllocPtr(GMEM_MOVEABLE,dibSize);
//Read the bitmap into memory and close the file.
file.Read((void*)pDib,dibSize);
file.Close();
//Initialize pointer to the bitmap's
//and BITMAPINFOHEADER structures.
m_pBmInfo=(LPBITMAPINFO) pDib;
m_pBmInfoHeader=(LPBITMAPINFOHEADER) pDib;
//Calculate a pointer to the bitmap's color table.
m_pRGBTable=(RGBQUAD*)(pDib + m_pBmInfoHeader->biSize);
//Get the number of colors in the bitmap.
int m_numColor = GetDibNumColors();
//Calculate the bitmap image's size.
m_pBmInfoHeader->biSizeImage = GetDibSizeImage();
//Make sure the biClrUsed field is initialized property.
if(m_pBmInfoHeader->biClrUsed ==0)
m_pBmInfoHeader->biClrUsed=m_numColors;
//Calculate a pointer to the bitmap's actual data.
DWORD clrTableSize = m_numColors * sizeof(RGBQUAD);
m_pDibBits = pDib + m_pBmInfoHeader->biSize + clrTableSize;
}
}
//////////////////////////////////////////////////////
// CDib ::GetDibSizeImage()
/////////////////////////////////////////////////////
DWORD CDib::GetDibSizeImage()
{
//if the bitmap's biSizeImage field contains
if(m_pBmInfoHeader->biSizeImage ==0)
{ //Get the width in bytes of a single row.

DWORD byteWidth=(DWORD) GetDibWidth();


//Fet the height of the bitmap.
DWORD height=(DWORD) GetDibHeight();
//Multiply the byte width by the number of rows.
DWORD imageSize = byteWidth * height;
return imageSize;
}
//Otherwise, just returnthe size stored in the BITMAPINFOHEADER structure.
else
return m_pBmInfoHeader->biSizeImage;
}
//////////////////////////////////////////////////////
// CDib ::GetDibWidth()
/////////////////////////////////////////////////////
UINT CDib::GetDibWidth()
{
return(UINT)m_pBmInfoHeader->biWidth;
}
UINT CDib::GetDibHeight()
{
return(UINT)m_pBmInfoHeader->biHeight;
}
//////////////////////////////////////////////////////
// CDib ::GetDibNumColors()
/////////////////////////////////////////////////////
UINT CDib::GetDibNumColors()
{
if((m_pBmInfoHeader->biClrUsed
==0)
>biBitCount<9))
return(1<< m_pBmInfoHeader->biBitCount);
else
return(int)m_pBmInfoHeader->biClrUsed ;
}
//////////////////////////////////////////////////////
// CDib ::GetDibInfoHeaderPtr()
/////////////////////////////////////////////////////

&&(m_pBmInfoHeader-

LPBITMAPINFOHEADER CDib::GetDibInfoHeaderPtr()

{
return m_pBmInfoHeader;
}
// CDib ::GetDibInfoPtr()
LPBITMAPINFO CDib::GetDibInfoPtr()
{
return m_pBmInfo;
}
//////////////////////////////////////////////////////
// CDib ::GetDibRGBTablePtr()
/////////////////////////////////////////////////////
LPRGBQUAD CDib::GetDibRGBTablePtr()
{
return m_pRGBTable;
}
//////////////////////////////////////////////////////
// CDib ::GetDibBitsPtr()
/////////////////////////////////////////////////////
BYTE* CDib::GetDibBitsPtr()
{
return m_pDibBits;
}
9.4.3.Ti DIB Vo B Nh:
Mt i tng CDib c to bng li gi hm to vi tn file DIB mun ti. Hm to
truyn tn file ny n hm thnh vin protected LoadBitmapFile() l hm thc s ti
bitmap. LoadBitmapFile() to m cho lp CDib. Cc hm thnh vin CDib khc tr v
cc gi tr c tnh tan bi LoadBitmapFile().
Trc tin LoadBitmapFile() xy dng mt i tng Cfile:
CFile file(fileName, CFile::modeRead);
Dng m ny khng ch xy dng i tng CFile tn l file, m cn m file (tn file
c truyn trong i s fileName) trong ch ch c (read-only).
Tip theo hm khai bo mt cu trc BIMAPFILEHEADER v c header file ca
DIB vo cu trc:
BITMAPFILEHEADER bmFileHeader;
file.Read((void*)&bmFileHeader,sizeof(bmFileHeader));

Hm thnh vin Read() ca i tng CFile yu cu hai i s gm con tr tr n b


m lu tr d liu v kch thc b m. Trong trng hp ny b m l cu trc
BITMAPFILEHEADER.
Sau header file ca DIB c lu tr trong cu trc bmFileHeader. Nhim v u
tin l kim tra file m c phi l bitmap khng, bng cch kim tra thng phn bfType
c mang gi tr thp lc phn 0x4D42 (m ASCII ca cc ch ci BM) khng:
if(bmFileHeader.bfType!=0x4d42)
{
AfxMessageBox(" Not a bitmap file");
m_pBmFileHeader=0;
m_pBmInfo=0;
m_pBmInfoHeader=0;
m_pRGBTable=0;
m_pDibBits=0;
m_numColors=0;
}
Nu thnh phn cu trc bfType khng cha gi tr ng, hm thit lp mi thnh phn
d liu ca lp bng 0 v thot. Ngc li LoadBitmapFile() s gi hm thnh vin
GetLength() ly kch thc file m:
DWORD fileLength = file.GetLength();
Sau kch thc ca DIB c tnh ton bng cch ly kch thc file tr i kch
thc file header:
DWORD dibSize = fileLength- sizeof(bmFileHeader);
Chng trnh s dng kt qu dibSize va c cp pht b nh lu tr DIB:
BYTE* pDib = (BYTE*) GlobalAllocPtr(GMEM_MOVEABLE, dibSize)
;
GlobalAllocPtr() l hm Windows cp pht b nh v tr v mt con tr tr n b
nh . Hai i s ca hm l mt c cho bit b nh c cp pht th no v kch
thc b nh c cp pht.
Sau khi cp pht b nh, hm thnh vin Read() c DIB vo b nh ri hm Close()
ng file:
file.Read((void*) pDib, dibSize);
file.Close();
Ti y, DIB c lu tr trong b nh, v LoadBitmapFile() by gi c th tnh
ton cc gi tr m lp CDib cn. a ch cc cu trc BITMAPINFO v
BITMAPINFOHEADER l ng nht, cng mt a ch b m m DIB c lu tr:

m_pBmInfo = (LPBITMAPINFO) pDib;


m_pBmInfoHeader = (LPBITMAPINFOHEADER) pDib;
LoadBitmapFile() tnh ton con tr tr n bng danh sch mu bng cch thm kch
thc cu trc BITMAPHEADER vo a ch ca DIB trong b nh:
m_pRGBTable = (RGBQUAD*) (pDib + m_pBmInfoHeader -> bisize);
Khi thc hin kiu ton con tr ny, cn cn thn vi kiu d liu s dng. V d do
pDib l con tr theo BYTE, s byte lu tr trong biSize c thm vo con tr ny.
Nhng nu pDib c nh ngha nh con tr theo cu trc BITMAPINFO, th gi tr
biSize* sizeof(BITMAPINFO) s c thm vo pDib.
Tip theo thnh phn d liu m_numColors c khi to bng li gi
GetDibnumColors():
int m_numColors = GetDibnumColors();
Cch lm vic ca GetDibnumColors() s ni n sau.
Thnh phn d liu biSizeImage ca cu trc BITMAPINFOHEADER c in y
bng li gi GetDibSizeImage():
m_pBmInfoHeader -> biSizeImage = GetDibSizeImage();
sau nu thnh phn biClrUsed ca BITMAPINFOHEADER bng 0,
LoadBitmapFile() s khi to n theo gi tr ng, ang c lu tr trong thnh phn
d liu m_numColors:
if(m_pBmInfoHeader -> biSizeImage = =0)
m_pBmInfoHeader -> biSizeImage = m_numColors;
Cui cng LoadBitmapFile() tnh ton a ch nh DIB bng cch cng kch thc cu
trc BITMAPINFOHEADER v kch thc bng danh sch mu vo con tr pDib (cha
a ch ca DIB trong b nh):
DWORD clrTableSize = m_numColors * sizeof(RGBQUAD);
m_bDibBit = pDib + m_pBmInfoHeader -> biSize + clrTableSize;
9.4.4.Cc Hm Thnh Vin Khc Ca Lp CDib:
trn, mt s thnh phn d liu CDib c khi to bng li gi cc hm thnh vin
CDib. Mt trong s cc hm thnh vin l GetDibImage(), dng tnh ton kch thc
DIB theo byte. Hm ny trc tin kim tra thnh phn biSizeImage cu trc
BITMAPINFOHEADER c cha gi tr 0 hay khng:
if(m_pBmInfoHeader -> biSizeImage = = 0)
Nu c hm tr v gi tr lu tr trong biSizeImage:
return m_pBmInfoHeader -> biSizeImage;

Ngc li, hm s dng thng tin c tnh ton kch thc nh. Trc tin hm
ly chiu rng v chiu cao DIB theo pixel:
DWORD byteWidth = (DWORD) GetWidth();
DWORD height = (DWORD) GetDibHeight();
Sau , nhn chiu rng vi chiu cao c kch thc ton b nh bitmap:
DWORD imageSize = byteWidth * height;
Ch rng cc tnh ton ny c thc hin sau t WORD loi tr s ct b thng
xy ra vi s nguyn. DIB c th ln.
Mt hm thnh vin khc c th phi thc hin mt s tnh ton l
GetDibNumColors(). Trc tin hm kim tra gi tr thnh phn biClrUsed ca cu trc
BITMAPINFOHEADER:
if((m_pBmInfoHeader -> biClrUsed = = 0) &&
(m_pBmInfoHeader -> biBitCount < 9))
Nu gi tr ny khc 0, hm tr v gi tr :
return (int) m_pBmInfoHeader -> biClrUsed;
Nu gi tr ny bng 0, hm tnh s mu bng cch di gi tr 1 sang tri, dng thnh
phn biBitCount lm di:
return(1<< m_pBmInfoHeader -> biBitCount);
Kt qu l gi tr 2 cho 1 bit (n sc) DIB, 16 cho 4 - bit DIB, v 256 cho 8 bit
DIB.
Cc hm thnh vin cn li ca CDib tr v gi tr cc thnh phn d liu CDib. V d
hm GetDibRGBTablePtr() tr v mt con tr tr n bng danh sch mu ca DIB, mt
gi tr c lu tr trong thnh phn d liu m_pRGBTable:
LPRGBQUAD CDib::GetDibRGBTablePtr()
{
return m_pRGBTable;
}
9.5.Gn Cu Trc Cho a Gic:
Nh bit, cc a gic c in y thiu cc chi tit ha lm cho a gic ging
i tng cn to. V d cn xy dng khi ch ci t su a gic to thnh khi vung.
Nhng khi vung n gin th khng ging hnh mun to, m phi cn sn cc chi tit
ln b mt a gic. Vic ny c thc hin vi texture mapping (gn cu trc).
Mc d texture mapping l qu trnh i hi tnh ton nhiu, OpenGL x l mi php
ton cho bn. gn cu trc cho mt a gic, ta ch cn thit lp mt s thng s v

cho OpenGL bit v tr nh gn vo a gic. Tuy nhin cng c s phc tp khi gn


cu trc.
9.5.1.Anh v DIB:
Vn lp trnh l phi bo cho OpenGL cch qun l cc nh c to bi cc
chng trnh ha Windows. Loi nh thng dng nht s dng vi Windows l
bitmap c lp vi thit b. Nhng OpenGL khng h tr trc tip vic s dng loi
bitmap ny. OpenGL s dng DIB trong qu trnh gn cu trc, ta phi thng dch d
liu nh DIB.
OpenGL qun l mt nh ha da vo loi nh. V d mt DIB 256 mu gm cc
ch s mu biu th mu sc trong bng danh sch mu v cc pixel trong nh. Hay
mt DIB 24-bit cha cc gi tr RGB thc s, cho bit cng cc thnh phn mu ,
xanh l, xanh dng cho mi pixel trong nh. l loi thng tin m OpenGL phi bit
v DIB trc khi tm ra cch th hin n. y ta nghin cu cch dng DIB 256 mu
vi OpenGL. Cc lai DIB khc s tng t.
Do DIB 256 mu cha cc ch s mu, cn bin i sang dng RGB OpenGL c th
th hin n trong ch mu RGBA. iu ny i hi cc bc sau:
1. Ti DIB vo b nh.
2. To cc bng danh sch mu (color table) t bng mu (palette) ca DIB
3. Gi glPixelMapfv() trao cc bng danh sch mu cho OpenGL.
4. Gi plPixelTransferi thit lp OpenGL theo ch color-mapping.
9.5.1.1.To Cc Bng Danh Sch Mu:
Nh lp CDib, DIB c ti vo b nh mt cch n gin bng li gi hm to
vi tn file. Con tr tr n bng mu DIB cng d dng c c bng li gi hm
GetDibRGBTablePtr(). Nhng s dng DIB vi OpenGL th phi to ba bng danh
sch cho cc mu , xanh l, xanh dng, OpenGL s dng cc gi tr trong cc bng
danh sch mu ny th hin cc pixel ca nh.
D liu nh ca DIB gm cc ch s mu. Cn bng mu ca DIB cha cc gi tr
RGB cho mi mu trong 256 mu dng trong nh. S tht tuyt nu c th s dng trc
tip cc gi tr RGB ca bng mu khi xy dng cc bng danh sch mu OpenGL.
Nhng bng mu DIB dng cc s nguyn t 0 n 256 biu din mu, trong khi cc
bng danh sch mu dng cho openGL s dng cc gi tr du chm ng trong di t
0.0 n 1.0. Tuy nhin vic bin i cc ga tr RGB ca DIB sang cc gi tr
muOpenGL th d dng. on m sau thc hin cng vic :
Void CreateColorTable(CDib* pDib)
{
LPRGBQUAD pColorTable = pDib
>GetDibRGBTablePtr( )
for(UINT i=0; i<256; i++)
{
red[i]= (GLfoat) pColorTable[i].rgbRed /255;
green[i]= (GLfoat) pColorTable[i].rgbGreen /255;
blue[i]= (GLfoat) pColorTable[i].rgbBlue /255;

}
}
i s n gin ca hn l con tr tr n i tng CDib. Dng u tin trong thn
hm dng con tr CDib ly con tr tr n bng mu DIB. Vng lp for c thc
hin cho ton b 256 mu trong bng mu, bin i cc gi tr s nguyn RGB ca DIB
thnh cc gi tr mu OpenGL du chm ng. Vic bin i ch l chia cc gi tr ,
xanh l, xanh dng cho 255. Kt qu tnh ton c l tr trong cc bng danh sch
mu red[], green[], blue[], l cc mng 256 phn t kiu GLfoat.
Khi hm CreateColorTable() kt thc, cc bng danh sch mu red[], green[], blue[]
cha cc gi tr t 0.0 n 1.0 th hin cc phn t mu , xanh l v xanh dung cho
mi ch s mu. V d tm cc gi tr RGB cho pixel c ch s mu 57, OpenGL ly
gi tr ti ch s 57 trong bng danh sch red[], gi tr ti ch s 57 trong bng danh sch
green[], gi tr ti ch s 57 trong bng danh sch blue[]. Sau tm mu trong bng mu
logic (Dc to cho ng dng) ging vi mu kt qu nht.
Hnh 9.3 n hnh 9.5 tng kt qu trnh color-mapping. Trong hnh 9.3, chng trnh
c DIB vo b nh. Nh bit, d liu y ca DIB boa gm
BITMAPINFOHEADER, bng mu c thit lp 256 u vo (entry), mi u vo
cha mt gi tr , xanh l, xanh dng. (D liu khng thch hp vi qu trnh colormapping khng th hin trn hnh). Trong hnh 9.4 hm CreateColorTable() chia mi gi
tr R, G, B cho 255 v t kt qu vo bng danh sch mu tng ng. Cui cng, trong
hnh 9.5, OpenGL xc nh cc mu cho nh bng cch mapping cc ch s mu DIB vo
bng danh sch mu hin cha cc gi tr RGB c hiu lc.

Hnh 9.3 Ti DIBVo b nh

Hnh 9.4 ta cc bng danh sch mu OpenGL:

Hnh 9.5: Mapping d liu nh DIB vi cc bng danh s ch mu:

9.5.1.2 .Chuyn Cc Bng Danh Sch Mu Cho OpenGL:


Sau khi to cc bng danh sch mu, OpenGL phi c bo thit lp cc
bng mapping bng li gi hm glPixelMapfv() nh sau:
glPixelMapfv(GL_PIXEL_MAP_I_TO_R, 256, m_red);
glPixelMapfv(GL_PIXEL_MAP_I_TO_G, 256, m_green);
glPixelMapfv(GL_PIXEL_MAP_I_TO_B, 256, m_blue);

Ba i s ca hm glPixelMapfv() gm mt hng cho bit kiu mapping, kch thc


bn , v a ch bn . Kiu mapping l mt trong cc hng lit k bng 9,6. Hm
glPixelMapfv() c hai phin bn khc l glPixelMapuiv() v glPixelMapusv(). on
m trn, glPixelMapfv() c gi ba ln, ln lt cho mt bng danh sch mu , xanh
l, xanh dng.
Bng 9.6: Cc kiu mapping cho hm glPixelMap()
Tn kiu
GL_PIXEL_MAP_A_TO_A
GL_PIXEL_MAP_B_TO_B
GL_PIXEL_MAP_G_TO_G
GL_PIXEL_MAP_I_TO_A
GL_PIXEL_MAP_I_TO_B
GL_PIXEL_MAP_I_TO_G
GL_PIXEL_MAP_I_TO_I
GL_PIXEL_MAP_I_TO_R
GL_PIXEL_MAP_R_TO_R
GL_PIXEL_MAP_S_TO_S

M t
Map cc thnh phn alpha theo cc thnh phn alpha
Map cc thnh phn xanh dung theo cc thnh phn
xanh dng
Map cc thnh phn xanh l theo cc thnh phn xanh
l
Map cc ch s mu theo cc thnh phn alpha
Map cc ch s mu theo cc thnh phn xanh dng
Map cc ch s mu theo cc thnh phn xanh l
Map cc ch s mu theo cc ch s mu
Map cc ch s mu theo cc thnh phn
Map cc thnh phn theo cc thnh phn
Map cc thnh phn stencil theo cc ch s stencil

9.5.1.3.Mapping Mu:
Sau khi c cc bng danh sch mu v chuyn chng cho OpenGL, hm
glTransferi() c gi mapping mu nh sau:
glPixelTransferi(GL_MAP_COLOR, TRUE);
Hai i s ca hm l hng xc nh kiu bn ha pixel v gi tr thit lp kiu.
Hm glTransferi() c nhiu cch dng. Nhng phn ln khng phi mapping d liu
nh DIB theo cc bng danh sch mu. Ch vi hai i s GL_MAP_COLOR v TRUE
th hm khi ng vic mapping mu OpenGL.
Khi mapping mu, OpenGL thc hin DIB vi 256 mu, tnh ton vn ca th hin
ph thuc ph hp gia bng mu logic v cc mu dng ta DIB. Do OpenGL
c thit k cho cc h thng 64.000 mu hoc hn, nn cc h thng OpenGL
th hin DIB thc s hon ho. Cn h thng 256 mu, s th hin s c vi suy bin.
9.5.2.Thit Lp Vic Gn Cu Trc:
Vic gn cu trc c th bt u sau khi ti DIB v to cc bng danh sch mu
ca n. Bc u tin l cho OpenGL bit cch thc hin texture mapping, bng cch gi
hm glTexParameteri() thit lp cc thng s khc nhau nh sau:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,
GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST);
Hm glTexParameteri() c bn phin bn. Cc i s ca hm gm hng xc nh kiu
cu trc, thng s cn thit lp, v gi tr thit lp cho thng s. i s u tin l
GL_TEXTURE_1D cho cu trc mt chiu, hay GL_TEXTURE_2D cho cu trc hai
chiu. GL_TEXTURE_2D, l nh hnh ch nht, thng c s dng.
i s th hai cho OpenGL bit cch qun l texture mapping di cc iu kin no
. V d vi GL_TEXTURE_WRAP_S v GL_TEXTURE_WRAP_T, OpenGL dng
nh n hoc a cu trc, tng ng vi cu trc theo phng ngang hay ng. Cc
thng s ny phi thit lp vi GL_CLAMP (cho nh n) hay vi GL_REPEAT (cho
mu lp li). Khi dng nh n cho a gic, phi s dng GL_CLAMP, nu khng kt
qu
nhn
c
s
k
d.
GL_TEXTURE_MAG_FILTER,
GL_TEXTURE_MIN_FILTER xc nh cch phng to hay thu nh cu trc khi din
tch ni n to hn hoc nh hn cu trc. Vic s dng GL_NEAREST vi cc thng
s ny cho php texture mapping nhanh, va nhn c kt qu sc nt nht. GL_NEAR
th chm hn do phi tnh ton mu sc cho mt pixel trn c s mc trung bnh ca bn
pixel.
Sau khi thit lp cc thng s cu trc, phi thit lp mi trng cu trc, tc l xc
nh hm cu trc no (hm ton hc, khng phi hm C++) m OpenGL dng tnh ton
cc gi tr mu cho b mt cu trc. Vic ny c thc hin vi li gi hm
glTexEnvi():
glTexEnvi(GL_TEXTURE_ENVI, GL_TEXTURE_ENVI_MODE, GLDECAL);
Hai i s u ca hm ln lt phi l GL_TEXTURE_ENVI v
GL_TEXTURE_ENVI_MODE, hay GL_MODULATE. Thng thng GL_DECAL
c s dng. Khi hm thay th cc pixel ni n bng cu trc. Hai hng cn li kt
hp ni n v cc gi tr cu trc theo cc cch khc nhau.
Bc cui cng l khi ng texture mapmping:
glEnable( GL_TEXTURE_2D);
Nu cu trc mt chiu c s dng th i s s l GL_TETURE_1D.
9.5.3.nh Ngha Cc Vertex V Cu Trc Ca Chng:
thit lp texture mapping c rt nhiu vic phi lm, nhng hu ht c hon
tt trn. Cc vic cn li l trao cu trc cho OpenGL, nh ngha cc vertex a gic v
nu quan h gia chng vi cc ta cu trc. on m sau thc hin iu :
glTexImage2D(GL_TEXTURE_2D, 0, 3 , width, height,
0, GL_COLOR_INDEX, GL_UNIGNED_BYTE, pTextureBits);
glBegin(GL_POLYGON);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1,0f, 1.0f, 0.0f);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1,0f, -1.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(1,0f,-1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(1,0f, 1.0f, 0.0f);
glEnd();
glFlush();
Trong on m trn, li gi glTexImage2D() cho OpenGL bit ni cha cu trc
cn s dng. i s u tin phi l GL_TEXTURE_2D. i s th hai l cu ca chi
tit, tr khi dng vi nh a cu trc, cn li gi tr 0 c dng cho i s ny. i s
th ba cho bit thnh phn mu trong cu trc. Trong trng hp dng nh RGB, gi tr
ny l 3. i s th t v nm l chiu rng v chiu cao cu trc. i s th su xc
nh chiu rng ng vin cu trc, l 0 hay 1, thng l 0. i s th by cho bit
nh dng ca d liu nh cu trc. Do d liu nh DIB th hin ch s mu, i s ny l
GL_COLORINDEX trong on m trn. Cc gi tr khc c th c l GL_ALPHA,
GL_BLUE, GL_GREEN, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RED,
GL_RGB, GL_RGBA. Hai i s cui cng l kiu d liu v a ch cu trc.
Sau khi trao cu trc cho OpenGL, ta phi nh ngha cc vertex ca a gic, cng
lc cho bit quan h gia chng vi cc ta cu trc bng li gi hm
glTexCoord2f(). Hai i s hm ny l cc ta S v T ca cu trc. (khi ni v cu
trc, S v T tng t nh X v Y trong khi R v Q tng t nh Z v W).
Hnh 9.6 th hin cc cch ta cu trc ph hp vi nh cu trc.Nu ch nh
gc tri trn ca cu trc theo gc tri trn a gic, gc tri di theo gc tri di, v
tng t, cu trc s xut hin ng theo hng nhn a gic.Vic ch nh cc gc trn
ca cu trc theo cc gc di ca a gic cho ta cu trc phn chiu theo phng ng.
Tng t, vic ch nh cc gc tri ca cu trc theo cc gc phi ca a gic cho ta mt
cu trc phn chiu theo phng ngang. Cc kiu ch nh khc s dn n kt qu k
quc.
9.6.Tng Kt:
OpenGL h tr trc tip hai loi i tng ha l bitmap v nh. Bitmap l nh
n sc thng dng nh cc mask. Anh l bc tranh y mu sc. Nhiu hm OpenGL
cho php di chuyn nh trong b nh v th hin chng ln mn hnh. Ta c th s dng
nh gn cu trc.
Gn cu trc l qa trnh phc tp, i hi s hiu bit v cch lu tr nh trong b
nh, v cch OpenGL thao tc chng. V d, s dng cc bitmap c lp vi thit b
(DIB) lm cu trc, phi bit ti DIB vo b nh v thit lp c ch truyn pixel map
cc mu sc ca DIB vo cc bng danh sch mu c to t bng mu DIB.
gn cu trc, trc ht phi khi to cc thng s gn cu trc, thit lp mi
trng gn cu trc, v kch hot vic gn cu trc. Ngoi ra, phi truyn cu trc cn
gn cng cc thng tin th hin cu trc cho OpenGL. Cng cn phi lin kt cc ta
cu trc vi cc vertex ca a gic c gn cu trc.

Tuy vy, chng ny ch mi cp mt cch tng qut kh nng texture mapping


ca OpenGL.

Chng 10: Pha Trn, Gim Hiu ng Rng Ca V Sng M


Chng trc trnh by cc k thut ci thin nh OpenGL 3-D gm cch s
dng nh bitmap c lp vi thit b v gn cu trc cho a gic. Cn mt s k thut tin
vi khc nh pha trn, gim hiu ng rng ca v sng m s c trnh by trong
chng ny.
Vi cc thao tc pha trn, antialiasing, v sng m, ta c th thm nhiu hiu ng c
bit cho cnh 3-D. Thng thng, pha trn c dng to i tng trong m.
Antialiasing gip kh hin tng rng ca, cn sng m to cm gic xa gn ca i
tng so vi im nhn.
10.1.Pha Trn:
pha trn (blending) l phng php kt hp mu ca cc pixel ngun v ch theo
cc cch khc nhau to nhng hiu qu t bit. Pha trn thng c s dng to
cc i tng trong m. khi mt i tng c pha trn chng ln i tng khc th c
th nhn xuyn qua i tng c bao ph do mu ca i tng ngun kt hp vi mu
ca pixel c bao ph to ra mu mi.
Cng c th dng pha trn t c cc hiu qu t bit khc. V d mt
chng trnh v OpenGL chng hn c th s dng pha trn cho php ngi dng v
cc lp mu ln cc bc tranh. OpenGL cng dng pha trn lm phng cc mp rng
ca ca ng thng (gi l antialiasing s ni n sau)
10.1.1.Kch Hot Vic Pha Trn:
Gng nh hu ht cc hm OpenGL t bit (nh chiu sng, kim tra chiu su,
hay v ng chm), trc ht phi kch hot vic pha trn nh sau:
glEnable(GL_BLEND);
Hng GL_BLEND bo OpenGL cho php pha trn. tt vic pha trn, cng dng
hng trn cho hm glDisable():
glDisable(GL_BLEND);
10.1.2.Chn La Cc Hm Pha Trn:
OpenGL bit cch kt hp cc mu ta dng hm glBlendFunc() la chn cc
hm pha trn ngun v ch nh sau:
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
Cc hng lm i s cho glBlendFunc() ln lt xc nh cc hm pha trn ngun
v ch, c lit k trong cc bng 10.1 v 10.2.
ngha cc bng ny nh sau: quyt nh mu sc cho mt pixel c pha trn,
OpenGL phi nhn cc thnh phn R,G,B,A ca mu ngun v ch vi mt h s. H s
ny c quyt nh bi cc hm pha trn ngun v ch . Mi tnh ton c th hin

trong cc bng trn dn n bn gi tr m OpenGL dng nhn vi cc thnh phn mu


R, G, B, A.
V d, nu ch nh GL_ONE l hm pha trn ngun, OpenGL s nhn cc thnh
phn mu R,G,B,A vi 1 (d nhin l nhn c cng mu xut pht). Bn s 1 trong
ngoc n tng ng cho bn thnh phn mu. Trong trng hp chn GL_ZERO lm
hm ngun, kt thc s l khng c mu ngun
Kt qu tnh ton quyt nh mc nh hng ca cc mu ngun v ch ln mu
cui cng nhn c. V d vi chn la glBlendFunc (GL_ONE , GL_ZERO ), kt qu
l khng c s pha trn do mu ngun hon ton lau sch mu ch
Chn la thng dng nht nh sau :
glBlendFunc (GL_SRC_ALPHA , GL_ONE_MINUS_SRC_ALPHA );
GL_SRC_ALPHA c ngha l OpenGL nhn cc thnh phn mu ngun vi gia tr alpha
ca mu ngun.
Vi GL_ONE_MINUS_SRC_ALPHA th trc ht gi tr alpha ca mu ngun
phi c tr i 1, sau nhn kt qu php tr vi cc gi tr RGBA ch.
Gi s pixel ngun (l pixel m OpenGL sp sa v ) c cc ga tr
RGBA (0.7 , 0.5 , 0.8. 0.6 ) v pixel ch ( l pixel m OpenGL s v pixel ngun ln) c
cc gi tr RGBA (0.6, 0.3 , 0.6 . 1.0 ). Trc tin OpenGL cung cp hm
GL_SRC_ALPHA cho cc gi tr RGBA ngun, tc l nhn 0.6 cho 0.7, 0.5 , 0.8, v 0.6.
Kt qu nhn c cc gi tr pixel ngun l (0.42, 0.3, 0.48 , 0.36). Sau OpenGL cung
cp hm
GL_ONE_MINUS_SRC_ALPHA cho pixel ch, tc l ly 1 tr i gi tr alpha ngun,
c 0.4 ri nhn kt qu ny cho 0.6, 0.3, 0.6 v 1.0
Kt qu nhn c cc gi tr pixel ch l (0.24, 0.12 , 0.24, 0.4 )
Nh vy vi chn la GL_SRC_ALPHA l hm pha trn ngun v
GL_ONE_MINUS_SRC_ALPHA l hm pha trn ch, gi tr alpha ngun s quyt nh
phn trm mi mu c OpenGL kt hp to nn mu cui cng. Vi gi tr alpha
0.6, 60% mu n t ngun v 40% mu n t ch
Gi tr alpha cng ln th kt qu cng tr nn m c. Do c th coi gi tr alpha
nh m c mun v.
Bng 10.1 :cc hng pha trn ngun
Hng s
GL_DST_ALPHA
GL_DST_COLOR
GL_ONE
GL_ONE_MINUS_ DST_ALPHA
GL_ONE_MINUS_ DST_COLOR
GL_ONE_MINUS_SRC_ALPHA
GL_ SRC_ALPHA
GL_ SRC_ALPHA_SATURATE
GL_ZERO

H s kt qu
(AD , AD , AD , AD )
(RD , GD , BD ,AD )
(1,1,1,1)
(1,1,1,1) - (AD , AD , AD , AD )
(1,1,1,1) - (RD , GD , BD ,AD )
(1,1,1,1) - (AS,AS,AS,AS)
(AS,AS,AS,AS)
(F,F,F,1) vi F= min( AS,(1-A0) )
( 0,0,0,0 )

Bng 10.2 : Cc hng pha trn ch


Hng s
GL_DST_ALPHA
GL_ONE
GL_ONE_MINUS_ DST_ALPHA
GL_ONE_MINUS_SRC_ALPHA
GL_ONE_MINUS_SRC_COLOR
GL_ SRC_ALPHA
GL_ SRC_COLOR
GL_ZERO

H s kt qu
(AD , AD , AD , AD )
(1,1,1,1)
(1,1,1,1) - (AD , AD , AD , AD )
(1,1,1,1) - (AS,AS,AS,AS)
(1,1,1,1) (RS , GS , BS , AS )
(AS,AS,AS,AS)
(RS , GS , BS , AS )
( 0,0,0,0 )

10.1.3.Pha Trn a Gic:


pha trn a gic, tt c vic phi lm l chn la mu v v v cc hnh.
OpenGL s cung cp cc hm pha trn v v kt qu ln mn hnh. on m sau c th
hin nh hnh 10.1 :
glClearColor (1.0f , 1.0f , 1.0f , 1.0f );
glClear (GL_COLOR_BUFFER_BIT);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA_GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0.0f , 1.0f , 1.0f , 1.0f);
glBegin(GL_POLYGON);
glVertex3f ( -1.0f , 0.25f , 0.0f );
glVertex3f ( -1.0f , -1.0f , 0.0f );
glVertex3f ( 0.25f , -1.0f , 0.0f );
glVertex3f ( 0.25f , 0.25f , 0.0f );
glEnd ();
glColor4f ( 1.0f , 0.0f , 0.0f , 0.5f );
glBegin (GL_POLYGON);
glVertex3f (-0.25f , 1.0f , 0.0f );
glVertex3f ( -0.25f , -0.25f , 0.0f );
glVertex3f ( 1.0f , -0.25f , 0.0f );
glVertex3f ( 1.0f , 1.0f , 0.0f );
glEnd ();
glFlush;
glDisable( GL_BLEND ):
Trong on m trn, gi tr alpha dng cho pha trn l 0.5 (nm li gi
glColor4f() th hai ). C ngha l trong vng m hai hnh vung ln nhau, mi mu

ngun v ch nh hng 50% trn mu pha trn cui cng. Gi tr alpha cng ln hnh
vung th hai cng tr nn m c.
Ngoi ra, th t v cc hnh cng nh hng n vic pha trn.
V d, nu v hnh vung trc c th s nhn c kt qa khc vi vic v hnh
vung xanh trc.

10.1.4. Pha Trn i Tng 3-D :


Pha trn i tng 3-D th phc tp hn pha trn i tng 2-D, do vic kim tra chiu
su OpenGL s lm bin mt cc i tng b che. V d, khi v mt khi vung trong
m bn trong mt khi vung c, do vic khi kim tra chiu su OpenGL ta s khng
thy khi vung c. kt hp pha trn trong cnh 3-D phi theo cc bc sau:
1. Kch hot vic kim tra chiu su
2. V tt c i tng m c
3. Thit lp thuc tnh ch c(read-only cho b m chiu su)
4. V tt c i tng trong m.
5.Tr li thuc tnh c vit (read/write) cho b m chiu su
D nhin cc bc ny khng ch ra s phc tp vn c khi th hin cnh 3-D bao gm
vic khi to vic chiu sng v thc hin cc php bin hnh modelview. Nhim v
quan trng trong cc bc trn l thit lp thuc tnh ch c cho b m chiu su trc
khi v cc i tng trong m. OpenGl s dng b m chiu su xc nh hnh no
trc hnh no sau. Vic thit lp thuc tnh ch c cho b m chiu su ngn tr
OpenGL thay i ni dung b m ny khi v cc t tng trong m; V nh vy
OpenGL khng th xo b cc i tng b khut m ta mun thy xuyn qua cc i
tng trong m.
thit lp thuc tnh ch c cho b m chiu su ta s dng hm
glDepthMask() :
glDepthMask ( GL_FALSE );
i s Glboolean ca hm cho php hay xa b kh nng ghi vo b m chiu su
ca OpenGL. Gi tr GL_FALSE thit lp thuc tnh ch c cho b m chiu su trong
khi GL_TRUE thit lp thuc tnh c/vit .
on m sau c th hin nh hnh 10.2 :
glClearColor ( 0.3f , 0.3f , 0.f , 0.0f );
glClear(GL_COLOR_BUFFER_BIT | GL_GL_DEPTH_BUFFER_BIT );
glEnable ( GL_BLEND );
glEnable (GL_LIGHTING );
glEnable (LIGHT0);
glEnable (GL_DEPTH_TEST);
glBlendFunc (GL_ONE , GL_ZERO);
GLfloat lightAmbient []={0.1f , 0.1f , 01f , 0.0f};
GLfloat lightDiffuse[]={1.0f , 1.0f , 1.0f , 0.0f};

GLfloat lightSpecular[]={1.0f , 1.0f , 1.0f , 0.0f};


GLfloat lightPosition[]= {2.0f , 0.5f , 3.0f , 1.0f };
GLfloat materialSpecular[]={1.0f , 1.0f , 1.0f , 0.0f};
GLfloat materialSphere1[]={1.0f , 0.0f , 0.0f , 0.0f};
GLfloat materialSphere2[]= {0.0f , 1.0f , 0.0f , 0.0f};
GLfloat materialCube[]= {1.0f , 1.0f , 0.0f , 0.0f};
glLightfv (GL_LIGHT0 , GL_ AMBIENT, lightAmbient);
glLightfv (GL_LIGHT0 , GL_DIFFUSE, lightDiffuse);
glLightfv (GL_LIGHT0, GL_SPECULAR, lightSpecular);
glLightfv (GL_LIGHT0, GL_POSITION , lightPosition);
glMaterialfv(GL_FRONT , GL_SPECULAR , materialSpecular);
glMaterialf ( GL_FRONT , GL_SHININESS , 50.0f );
glTranslatef(-1.5f , 0.5f , -3.0f);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialSphere1);
auxSolidSphere(1.0);
glTranslatef(2.0f ,- 0.8f , 3.0f);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialSphere2);
auxSolidSphere(0.75);
glDepthMask(GL_FALSE);
glBlendFunc(GL_SRC_ALPHA , GL_ONE);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,
materialCube);
glTranslatef(-1.0f , 0.0f , 0.0f );
glRotatef(40.0f , 1.0f , 0.0f , 0.0f );
glRotatef(40.0f , 0.0f , 1.0f , 0.0f );
auxSolidCube(1.0);
glFlush();
glDepthMask(GL_TRUE);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);

Hnh 10.2
Pha trn i
tng 3-D

Khi pha trn trong cnh 3-D c chiu sng , cc gi tr mu dng trong cc hm pha
trn nm trong mu nh sng khuch tn ca vt liu.V d trong on m trn gi tr
alpha 0.5 cho hm pha trn ca khi vung l phn t alpha ca mng materialCube[]
10.2.Gim Hiu ng Rng Ca:
Trn mn hnh mt ng thng l tp hp ca cc pixel c chiu sng trong h
thng k vung (Hnh 10.3 ). Do ch c ng nm ngang hay thng ng l c
v mt cch sung s cn cc ng nghing s c hin tng rng ca (alias). phn
gii cng cao th hin tng rng ca cng gim nhng khng th khng c. Gii php k
thut gim hiu ng rng ca (antialiasing ) l s dng cc st thi mu khc nhau
che du cnh rng ca ca ng thng trn mn hnh. Thc t antialiasing ch l mt
kiu hiu qu pha trn OpenGL.

Hnh 10.3:ngrng
ca trn mn hnh

10.2.1.Kch Hot Antialiasing:


Ging nh vic pha trn, thao tc u tin thc hin antialiasing l kch hot
antialiasing nh sau:
glEnable (GL_LINE_SMOOTH );
Hng GL_LINE_SMOOTH bo cho OpenGL thc hin antialiasing cho ng thng.
i vi im hay a gic, antialiasing c kch hot bi cc hng
GL_POINT_SMOOTH hay GL_POLYGON_SMOOTH.
10.2.2.Kch Hot Pha Trn Cho Antialasing:
Do antialiasing l mt hiu qu pha trn nn cn phi kch hot pha trn v chn
hm pha trn :
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
Vi cc hm pha trn khc nhau s nhn c cc kt qu antialiasing khc nhau.
Nhng thng dng nht l s dng hm ngun GL_SRC_ALPHA v hm ch
GL_ONE_MINUS_SRC_ALPHA.Cn nh rng vi chn la nh vy, thnh phn alpha
ca i tng s nh hng ti kt qu antialiasing. Ngoi ra cc mu trong bng mu
logic s quyt nh chnh xc ca antialiasing.
10.2.3.Gi Lm Phng Cho OpenGL:

OpenGL c th thc hin antialiasing theo nhiu cch tng ng vi s thit lp cc


thng s. cho OpenGL bit mun th hin nhanh hay chm vi chnh xc cao hay
khng u tin g c, ta dng hm glHint() nh sau :
glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
i s th nht ca hm xc nh thao tc ngh, c th l GL_FOG_HINT ,
GL_LINE_SMOOTH, GL_PERSPECTIVE_CORRECTION_HINT,
GL_POINT_SMOOTH_HINT hay GL_POLYGON_SMOOTH_HINT.
i s th hai xc nh li gi , c th l GL_DONT CARE (cho php OpenGL
thc hin ty ) hay GLFASTEST (OpenGL th hin phng thc nhanh nht) hay
GL_NICEST (OpenGL thc hin phng thc chnh xc nht).

10.2.4.Cc ng Thng Antialiasing:


Bc cui cng v cc ng thng khng c rng ca l thit lp b rng ng
v mu. Phi nh rng OpenGL s dng cc gi tr mu c chn trong cc hm pha
trn. on m sau l mt v d chun b v ng thng :
glLineWidth (2.0f);
glColor4f (0.0f , 0.0f , 0.0f , 1.0f );
Trong trng hp cc hm pha trn ngun, ch l GL_SRC_ALPHA v
GL_ONE_MINUS_SRC_ALPHA , chn la mu trn cho gi tr alpha bng 1.0 , ng
c v m nht.Vi alpha bng 0.0 s khng c ng no c v c.
on m sau c thc hin nh hnh 10.4. Hnh 10.5 cho cng mt hnh mng nhn
nhng khng c antialiasing :
glClearColor (1.0f , 1.0f , 1.0f , 0.0f );
glClear (GL_COLOR_BUFFER_BIT);
glShadeModel (GL_FLAT);
glEnable (GL_LINE_SMOOTH);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint (GL_LINE_SMOOTH_HINT,GL_DONT_CARE);
glLineWidth (2.0);
glColor4f (0.0f , 0.0f , 0.0f , 1.0f );
auxWireSphere (1.0);
glDisable (GL_LINE_SMOOTH);
glDisable (GL_BLEND);

Hnh 10.4: Hnh mng nhn vi antialiasing

Hnh 10.5: Hnh mng nhn khng dng


antialiasing

10.3.Sng M:
Khng kh cng nh mi vt cht khc khng hon ton trong sut nn nh sng i qua
n s b hp th mt phn hay ton b. Ni mt cch khc, i tng cng xa th th
hin ca n cng m nht. OpenGL c th xem sng m nh mt loi knh lc c hiu
qu cng ln trn i tng cng xa. Bng cch chn la cc hm sng m, mu sc,
mt v.v... ta c th quyt nh mc hiu qu.
10.3.1.Kch Hot Fog :
Fog c kch hot nh sau :
glEnable (GL_FOG);
Hng GL_FOG bo cho OpenGL kch hot hiu ng sng m
10.3.2.Chn Hm Sng M :
Ging nh pha trn sng m c s dng theo nhiu cch. bo cho OpenGL bit
loi hm sng m no c s dng khi xc nh mu th hin cc pixel, hm glFog()
c gi nh sau:
glFogi (GL_FOG_MODE , GL_LINE);
i s u tin ca hm xc nh thng s sng m mun thit lp, c th l
GL_FOG_DENSITY, GL_FOG_END, GL_FOG_INDEX , GL_FOG_MODE hay
GL_FOG_START. i s th hai l gi tr thit lp cho thng s xc nh bi i s
th nht. Vi GL_FOG_MODE, cc gi tr c th dng i s th hai l GL_EXP,
GL_EXP2, GL_LINEAR (glFog() c bn phin bn).
GL_EXP v GL_EXP2 s dng cc hm s m xc nh mu ca pixel sng m. Tc
dng ca GL_EXP2 ln hn tc dng ca GL_EXP. Do OpenGL qun l hu ht cc chi

tit, cc hm GL_EXP v GL_EXP2 d s dng trong chng trnh. Nhng GL_LINEAR


hm cung cp hiu ng sng m trn c s kch thc vng sng m cho php ngi
dng kim sot nhiu hn. Vi GL_LINEAR c th bo cho OpenGL chnh xc ni bt
u v kt thc sng m trong cnh bng li gi glFogf() :
glFogf (GL_FOG_START , 0.0f);
glFogF (GL_FOG_END, 10.0f );
Hng GL_FOG_START bo cho OpenGL thit lp im bt u sng m. i s
th hai l khong cch k t im nhn m hiu ng fog bt u. Hng GL_FOG_END
bo cho OpenGL tht lp im kt thc sng m, vi i s th hai cng l khong cch
k t im nhn. Ch c th thit lp im bt u v kt thc sng m khi dng
GL_LINEAR. Vic thit lp l khng hiu lc khi dng GL_EXP v GL_EXP2 . Tuy
nhin khi dng GL_EXP v GL_EXP2 ta c th thit lp mt sng m bng li gi
glFog() vi GL_FOG_DENSITY lm i s th nht v gi tr mt lm i s th hai.
Khong cch gia im bt u v kt thc sng m cng ln th hiu qu sng m
cng km. V d vi im bt u l 0.0 nu im kt thc l 5.0 th cc i tng trong
vng ny s chu tc dng sng m nhiu, nhng nu im kt thc l 20.0 th hiu qu
sng m b gim r rt do tc dng b tri ra trn khong cch ln hn.
10.3.3.Thit Lp Mu Sng M:
Vi vic thit lp mu sng m c th t c hiu qu ln hn mu st s dng
trong cnh. Trong a s trng hp thng dng sng m mu trng vi sng va
phi:
GLfloat fogColor[]={0.6f , 0.6f , 0.6f , 1.0f};
GlFogfv (GL_FOG_COLOR , fogColor);
Hai i s ca hm l thng s sng m mun thit lp v a ch mng cha gi tr
thit lp cho thng s. C th c c cc kt qu th v bng cch s dng cc mu khc
mu trng. Sng m mu en cho php to cnh ban m hay tri ti.
10.3.4.Nu Gi Sng M :
Tong antialiasing, ta lm quen vi glHint(). Hm ny cng c th s dng trong hiu
ng sng m viGL_FOG_HINT lm i s th nht:
glHint (GL_FOG_HINT , GL_DONT_CARE);
Cng nh trc y GL_DONT_CARE cho php OpenGL s dng ty cc phng
php sng m.
10.3.5.Thc Hin Sng M Cho Cnh 3_D :
Trc khi thc hin sng m cho cnh 3-D phi kch hot chiu sng v kim tra
chiu su cng nh thit lp cc thng s chiu sng v vt liu;

Sau thc hin cc php bin hnh modelview v v i tng. OpenGL s dng sng
m khi c ch nh trn c s khong cch i tng t im nhn. on m sau th
hin nh hnh 10.6 :
glClearColor (0.3f , 0.3f , 0.3f , 1.0f );
glClear (GL_COLOR_BUFFER_BIT / GLDEPTH_BUFFER_BIT);
glShadeModel (GL_SMOOTH);
glEnable (GL_FOG):
Fogi (GL_FOG_MODE , GL_LINEAR);
Gloat fogColor[]={0.6f , 0.6f , 0.6f , 1.0f};
glFogfv (GL_FOG_COLOR , fogColor);
glFogfv (GL_FOG_START , 0.0f);
glFogfv (GL_FOG_END , 10.0f);
glHint (GL_FOG_HINT , GL_DONT_CARE);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable (GL_DEPTH_TEST);
GLfloat lightAmbient []={0.1f , 0.1f , 01f , 0.0f};
GLfloat lightDiffuse[]={1.0f , 1.0f , 1.0f , 0.0f};
GLfloat lightSpecular[]={1.0f , 1.0f , 1.0f , 0.0f};
GLfloat lightPosition[]= {2.0f , 0.5f , 3.0f , 1.0f };
GLfloat materialSpecular[]={1.0f , 1.0f , 1.0f , 0.0f};
GLfloat materialAmbDiff[]={1.0f , 0.0f , 0.0f , 0.0f);
glLightfv (GL_LIGHTO,GL_ AMBIENT, lightAmbient);
glLightfv (GL_LIGHTO , GL_DIFFUSE, lightDiffuse);
glLightfv (GL_LIGHTO, GL_SPECULAR, lightSpecular);
glLightfv (GL_LIGHTO, GL_POSITION , lightPosition);
glMaterialfv (GL_FRONT , GL_AMBIENT_AND_DIFFUSE ,
materialAmbDiff);
glMaterialfv ( GL_FRONT , GL_SPECULAR , materialSpecular );
glMaterialf ( GL_FRONT , GL_SHININESS , 30.0f );
glTranslatef(-2.0f , 2.0f , -6.0f);
auxSolidTorus (0.5 , 1.0);
glTranslatef(1.5f ,-2.0f , 3.0f);
auxSolidTorus (0.5 , 1.0);
glTranslatef(1.5f ,-1.0f , 3.0f);
auxSolidTorus (0.5 , 1.0);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_FOG);

Hnh 10.6
Thc hin sng m
cho cnh 3-D.

Hnh th hin ba ng
g trn, xp xa dn im nhn. Hnh gn nht gi c hnh mu , trong khi hnh xa
nht hu nh trng m hon ton do i tng cng xa th tc dng sng m ln n
cng ln.

Chng11:Display List
11.1.nh Ngha:
L mt nhm lnh OpenGL c lu li sau khi thc thi. C th s dng immediate
mode v display list trong cng mt chng trnh, cc lnh s c thc thi theo ng
trt t m n xut hin.
11.2.Ti Sao Phi S Dng Display List ?:
Khi ta c nh v li hoc thay i trng thi nhiu ln mt i tng, s dng
display list lm tng kh nng thc thi chng trnh.
Trong m hnh client server : display list s lm gim s hao ph thi gian truyn d
liu.
V d:
Gluint thetorus;
Static void torus (int numc, int numt )
{
int i, k, j;
double s, t, x, y, z, twopi;
twpoi =2* (double) 3.14;
for (i =0; i<numc ; j++) {
glBegin (GL_QUAD_STRIP);
for (j =0; j<numt; j++) {
for (k =0; k>=0; k--) {
s = (i+k)%numc +0.5;

t = j%numt;
x = (1 +0.1*cos (s*twopi/numc))
*cos (t*twpoi / numt);
y = (1 +0.1*cos (s*twopi/numc))
*sin (t*twpoi / numt);
z =0.1*sin (s*twopi / numc;
glVertex3f (x, y, z);
}
}
glEnd();
}
static void init (void)
{
theTorus = glGenList (1);
glNewList (theTorus, GL_COMPILE);
torus (8, 25);
glEndList ();
}
void Drawsine (void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 0.0);
glCallList (theTorus);
glFush ();
}
11.3.Cc Tnh Cht Ca Display List:
Nu mt display list to ra th khng th no sa i. Display list cng lm vic tt vi
cc lnh ca th vin gl. C nhiu cch thc hin display list.
S thc thi ca display list khng chm hn thc thi cc lnh c cha bn trong n
mt cch c lp.
11.4.Cc Trng Hp C Th S Dng Display List:
Cc tc v trn ma trn.
Raster cc bitmaps v cc nh.
c tnh ngun sng, cht liu v m hnh chiu sng.
Textures.
Polygon stiple pattern
11.5.Nhc im Ca Dislay List:
Tnh khng bin i ca dislay list.
Tn vng nh nu cn lu tr d liu c phn chia t dislay list.
Nu danh sch l nh th khng hiu qu.
11.6.To V Thc Thi Mt Dislay List:

11.6.1.t Tn Vo Mt Dislay List:


Hm glNewList (Gluint list, Glenum mode) v glEndList (void) dng bt u v kt
thc mt dislay list. List l tn ca mt dislay list, mi dislay list c t tn bng mt
gi tr integer. Gi tr ca mode c th l:GL_COMPLE and
GL_COMPLE_AND_EXCUTE. Ch c mt dislay list ti mt thi im.
Nn trnh s trng tn ta dng hm glGenList (Glsizei range).
Khi khng s dng dislay list ta dng hm:
GlDeleteList (Glint list, Glsizei range ) xa dislay list nh ngha.
Hm glIsList (Gluint list) dng kim tra dislay list c nh ngha cha.
11.6.2. Nhng Lnh Khng c Cha Trong Dislay List:
glColorPointer ()
glFlush ()
glNormalPointer ()
glDeleteList ()
glGenList ()
glPixelStore ()
glDisableClienState ()
glGet* ()
glReadPixel ()
glEdgeflagPointer (),
11.6.3.Thc Thi Mt Dislay List:
Dislay list c thc thi bng glCallList (Gluin list), c th gi glCallList (Gluin
list) bt c ni no trong chng trnh min l OpenGL context truy cp dislay list tch
cc.
11.6.4.Cp Bc Dislay List:
L dislay list m n c nh ngha trong mt dislay list khc. trnh s qui v
hn ch s phn t trong dislay list.
OpenGL cho php to mt dislay list m n gi ti mt ci khc nhng ci ny cha
c ngha, kt qu l khng c g xy ra.
11.7. Qun L Bin Trng Thi Trong Dislay List:
Cc bin trng thi ca OpenGL sau khi ra khi dislay list vn cn nh hng n cc
lnh tip theo trong chng trnh.
Khng th dng glGet*() trong dislay list, do lu tr v phc hi bin trng thi
phi dng glPushAttr() v glPopAttrib().
V d:
glNewList (listIndex, GL_COMPLE) ;
glPushMatrix () ;
glPushAttrib ( GL_ CURRENT_BIT) ;
glColor3f( 1.0, 0.0, 0.0) ;
glBegin ( BOLYGON );

glvertex2f ( 0.0,
glvertex2f ( 1.0,
glvertex2f ( 1.0,
glEnd () ;
glTranslatef (1.5, 0.0,
glPopAttrib () ;
glPopMatrix () ;
glEndList ();

0.0);
0.0);
1.0);
0.0 );

Chng 12: QUADRIC:

Trong GLU c cc hm h tr cho vic biu din mt s dng 3D c bn nh cc khi


cu, cylinder, cc a c gi chung l Quadric.
s dng i tng Quadric, thc hin theo cc bc sau:
+ To mt i tng quadric:
GLUquadricObj* gluNewQuadric(void): to mt i tng quadric v tr v mt
pointer.
+ Ch nh nhng thuc tnh cho i tng quadric bng: gluQuadricOrientation (),
gluQuadricDrawStyle (), gluQuadricNormal ().
+ Qun l s xut hin li trong qu trnh biu din.
void glQuadricCallback(GLUquadric quad, Glenum which, Glvoid (CallbackFunc)
()).
+ Gi nhng routines biu din nhng i tng mong mun.
Void GluSphere(GLUquadricObj *qobj, Glduoble radius, Glint slices, Glint stacks )
v hnh cu bn knh radius tm ti gc.
Void gluCylinder( GLUquadricObj *qobj, Gldouble basicRadius, Gldouble topRadius,
Gldouble height, Glint slices, Glint stacks) v hnh tr c trc l trc z mt mt tip xc
vi mt z=0 v c chiu cao l height
Void gluDisk(GLUquadricObj *qobj, Gldouble innerRadius, Gldouble outerRadius,
Glint slices, Glint stacks) v hnh a c bn knh ng trn trong interRadius v bn
knh ng trn ngoi outerRadius.
Void gluPartialDisk(GLUquadric *qobj, Gldouble innerRadius, Gldouble outerRadius,
Glint slices, Glint rings, Gldouble starAngle, Gldouble sweepAngle);
+ Loi b vng void gluDeleteQuadric(GLUquadric*quad);

PHN 2: NG DNG M PHNG CC GII THUT

HA 3 D VI OPENGL
Chng 1: Tng Quan
Mt trong nhng u im quan trng ca ha l cho php d dng thao tc ln
cc i tng c to ra. Mt nh qun l c nhu cu phng to hay thu nh mt i
tng trong mt bo co, hay nhng nh thit k mun xem sn phm ca mnh t cc
gc khc nhau, Tt c cc thao tc ny c th c h tr mt cch d dng nh vo
cc php bin i hnh hc. Cc php bin i hnh hc s lm thay i m t v ta
ca cc i tng, t lm cho ta thay i v hng, kch thc v hnh dng. Cc
php bin i hnh hc c s gm: tnh tin (tranlation), quay (rotation) v bin i t l.
Ngoi ra mt s bin i khc cng thng c p dng l php i xng (reflection)
v bin dng (shearing).
C hai quan im v php bin i hnh hc l: bin i i tng (object
transformation) v bin i h ta (coordinate transformation). Bin i i tng l
thay i cc im m t n theo mt quy tc no , cn bin i h ta l to ra mt
h ta mi v tt c cc im m t i tng s c chuyn v h ta mi. Hai
cch ny c mi lin h cht ch vi nhau. y chng ta ch ni n php bin i h
to .
1.1. Mt S Khi Nim Lin Quan
1.1.1 Php Bin i Affine
Php bin i affine l php bin i tuyn tnh, kh nghch. Php bin i ny bo
ton tnh song song ca cc ng thng cng nh bo ton tnh t l v khong cch gia
cc on thng. Tuy nhin , php bin i ny khng bo ton gc nghing v chiu di
cc on thng. Cc php bin i ny cng bo ton v t l v khong cch. Cc h trc
to quy c bn tay phi v bn tay tri

x
x^ y=z
(a)

z
y^ x=z
(b)

Hnh 1.1- cc h ta quy c bn tay tri (a) v quy c bn tay phi (b )

1.1.2. H Ta Thun Nht:


Trong mt h ta thun nht , mi im (x,y,z) trong khng gian Dercarters c
biu din bi 4 ta trong khng gian 4 chiu thu gn (hx,hy,hz,h). tin li, ngi ta
thng chn h=1. Nh vy, mt im (x,y,z) trong h ta dercarts s bin thnh im
(x,y,z,1) trong h ta thun nht (vi w <> 0) s tng ng vi im (x/w,y/w,z/w)
trong h ta descartees
homogeneous
(x/w,y/w,z/w)
W=1

project

Descartes
(x/w,y/w,z/w,1)

(x,y,z,w)

homogeneous

1.1.3. Dng Ma Trn Cho Php Bin i Affine Trong H Ta Thun Nht
T l, quay ,bin dng

Tnh Tin

a
d
g

(x y z 1) = (x y z 1)
trx try trz 1

b
e
h

c
f
I

0
0
0

Hnh 1.1.3 :Dng Tng Qut Ca Php Bin i Affine Ba Chiu


1.2. Cc Php Bin i:
1.2.1. Php Tnh Tin:
y
(x,y,z)

(x,y,z)
tr = ( trx , try , trz )
z

Hnh1.2.1: Php Tnh Tin Vi vect tnh tin tr = ( trx , try , trz )
Vector tnh tin tr trong php bin i ba chiu c tc ng rt trc quan: mi im
c dch di mt khong l trx , try , trz , theo ba trc.
1.2.2. Php Bin i T L

x
z
Hnh 1.2.2 :Php bin i t l
Nh hnh 1.2.2: i tng phng to gp i, ng thi vi tc ng ca php bin i
lm cho i tng b y ra xa gc ta hn
1.2.3. Php Bin Dng:
Bin dng theo bt k trc ta no cng b nh hng bi ta ng vi hai trc
cn li.

Hnh 1.2.3: Php Bin Dng


1.2.4. Php Quay:
1.2.4.1. Quay quanh mt trc to :
Khc vi php quay trong hai chiu quanh 1 im bt k, trong ba chiu ta c php
quay quanh mt trc ta . y ta s dng h ta quy c bn tay tri v quy
nh chiu quay dng l ngc chiu kim ng h.

x
z
Hnh 1.2.4.1: Php Quay Quanh Trc Z
y

Chng 2: Xy dng ng dng m phng thut gii ha 3-D


Phn tip theo ca lun vn s dng OpenGL xy dng mt ng dng thut gii
ha 3-D.
2.1.Xy dng ng dng OpenGL:
Cc bc sau th hin qu trnh xy dng mt ng dng c tn OpenGL, s dng th
vin OpenGL minh ha.
2.1.1. To ng dng c bn v sa i giao din:
2.1.1.1. Dng AppWizard to ng dng OpenGL vi cc chn la sau trong
cc hp thoi:
Bc 1: Multil document.
Bc 2: Mc nh.
Bc 3: Mc nh.
Bc 4: Use 3D Controls.
Bc 5: As a statically linked library.
Bc 6: Mc nh.
Bng tng kt chn la nh sau:

Hnh 2.1.1.1: Bng tng kt chn la ng dng OpenGL


2.1.1.2. To hp thoi c ID l IDD_FORM_COMMAND v cc Picture, Check
box,
Radio
button,
Slider
c
ID
l
IDC_FRAME_COLOR_BACK,
IDC_FRAME_COLOR_LIGHT_AMBIENT,
IDC_CHECK_ANTIALIAS,
IDC_CHECK_SMOOTH, IDC_CHECK_LIGHTING,
IDC_RADIO_MODEL_0,
IDC_RADIO_MODEL_1, IDC_RADIO_MODEL_2, IDC_CHECK_VROTATION,
IDC_CHECK_LINK_SCALE, IDC_SLIDER_X, IDC_SLIDER_Y, IDC_SLIDER_Z
(hnh 2.2)
2.1.1.3. Dng ClassWizard to lp CformCommandView cho hp thoi
IDD_FORM_COMMAND, vi cc bin kiu BOOL
nh
m_Antialias, m_Lighting, m_LinkScale, m_Smooth,
m_Vrotate,
v
kiu
CStatic
nh
m_ControlBackColor,
m_ControlColorLightAmbient, kiu CsliderCtrl nh
m_SliderScaleX, m_SliderScaleY, m_SliderScaleZ (
hnh
2.1.1.3)

Hnh 2.1.1.3: Hp thoi


FormCommandView

2.1.2. Thm cc bin thnh vin, cc hm p ng


thng bo, hm COMMAND, cc hm thanh vin,
hon chnh lp COpenGLView
2.1.2.1. Thm cc bin thnh vin public sau cho lp COpenGLView:
float m_zTranslation;
float m_yTranslation;
float m_xTranslation;
float m_zScaling;
float m_yScaling;

float m_xScaling;
float m_zRotation;
float m_yRotation;
float m_xRotation;
CPoint m_RightDownPos;
BOOL m_RightButtonDown;
CPoint m_LeftDownPos;
BOOL m_LeftButtonDown;
HGLRC m_hGLContext;
int m_GLPixelIndex;
HCURSOR m_CursorRotation;
float m_ClearColorGreen;
float m_ClearColorRed;
float m_ClearColorBlue;
2.1.2.2. Dng MFC ClassWizard thm cc hm p ng thng bo WM_CREATE,
WM_DETROY,
WM_LBUTTONDOWN,
WM_LBUTTONUP,
WM_MOUSEMOVE,
WM_PAINT,
WM_RBUTTONDOWN,
WM_RBUTTONUP,
WM_SIZE, v WM_TIMER.

Hnh 2.1.2.2: To lp
CFormCommandView

Thm m cho cc hm OnCreate(), OnDetroy(), OnSize(),


OnLButtonDown(),OnLButtonUp(),OnRButtonDown(),OnRButtonUp(),
OnMouseMove(), OnPaint() ca lp COpenGLView nh bng k 2.3.2
2.1.2.3. Thm cc hm thnh vin public sau vo lp COpenGLView:
void InitGeometry(void);
BOOL CreateViewGLContext(HDC hDC);
BOOL SetWindowPixelFormat(HDC hDC);
M cc hm trn c ci t trong bng k 2.3.
2.1.2.5. Thm vo sau ch th #endif ca OpenGLView.cpp cc dng sau:
#include "gl\glu.h"
#include "gl\gl.h"
2.1.2.6. Thm vo Project cc file th vin Glaux.lib, OpenGL32.lib v glu32.lib
(ng dn ..\Vc98\lib)

Hnh 2.1.2.5: Thm cc file th vin

2.2 Cch lm vic ca ng dng:


Hnh 2.2 l ca s khi bt u ng dng th hin mt hnh cu 3-D .Thng qua hnh
cu ny ta c th minh ha c mt s gii thut ha 3-D.

Hnh 2.2: Trc khi thc


hin cc php bin hnh

2.2.1. Cc php bin hnh OpenGL.


Trc khi thc hin cc php bin hnh th i tng hnh cu c khi ng bng
cc gi tr:
m_xRotation = 0.0f;
m_yRotation = 0.0f;
m_zRotation = 0.0f;
m_xTranslation = 0.0f;
m_yTranslation = 0.0f;
m_zTranslation = -5.0f;
m_xScaling = 1.0f;
m_yScaling = 1.0f;
m_zScaling = 1.0f;
2.2.1.1.Php tnh tin:
thc hin php tnh tin ta dng phm phi ca con chut di chuyn hnh
cu, cc bin m_xTranslation, m_yTranslation, m_zTranslation nhn gi tr mi th
InvalidateRect c gi v li hnh.

Hnh 2.2.1.1a: Trc khi tnh tin

Hnh 2.2.1.1b: Sau khi tnh tin

2.2.1.2. Php Quay:


Ngc li vi php tnh tin thc hin php quay ta dng phm tri ca con
chut iu khin hnh cu quay theo cc trc tu , lc ny cc bin m_xRotation,
m_yRotation, m_zRotation nhn gi tr mi th InvalidateRect c gi v li hnh.

Hnh 2.2.1.2: Sau khi thc hin php quay


2.2.1.3. Php Co gin:
thc hin php co gin hnh cu ta thng qua ba thanh trt tng ng vi ba
trc X, Y, Z. Thanh trt c gi tr t 1 100, khi ta di chuyn cc thanh trt cc bin
m_xScaling, m_yScaling, m_zScaling nhn gi tr mi th InvalidateRect c gi v
li hnh.

Hnh 2.2.1.3: Sau khi thc hin php co gin theo ba trc
2.2.2. Kiu bng , chiu sng, hiu ng rng ca v cc thao tc v i tng 3-D:
2.2.2.1. Kiu bng:
Mt phng din quan trng ca OpenGL l kiu bng dng th hin i tng trong
cnh. Co hai kiu bng: mt (smooth) v phng (flat). chn kiu bng, s dng hm
glShadeMode() nh sau:
glShadeModel(GL_FAT);

i s n ca hm l hng th hin kiu bng c chn, l GL_SMOOTH, hoc


GL_FAT. Vi bng mt, OpenGL phi xc nh mu bng cho tng pixel trn a gic.
Trong i s bng phng, ton b a gic dng chung mt mu bng. Hm
OnCheckSmooth() kim tra kiu bng.
void CFormCommandView::OnCheckSmooth()
{
// TODO: Add your control notification handler code here
m_Smooth = !m_Smooth;
If(m_Smooth)
glShadeModel(GL_SMOOTH);
else
glShadeModel(GL_FLAT);
this->GetRenderView()->InvalidateRect(NULL,FALSE);

Hnh 2.2.2.1a:Kiu bng mt

Hnh 2.2.2.1 Kiu bng phng

2.2.2.2. Chiu sng i tng:


u tin i tng c v c mu trong sut i tng c nh sng chiu vi
mu sc ty chng trnh s dng CColorDialog cho ngi dng ty chn.

Hnh 2.2.2.2a: Chn mu chiu sng


2.2.2.3. Hiu ng rng ca:

Hnh 2.2.2.2b:Chiu sng

Trn mn hnh, mt ng thng l tp hp ca cc pixel c chiu sng trong h


thng k vung. Do , ch c ng nm ngang hoc thng ng l c v mt cch
sung s. Cn cc ng nghing s c hin tng rng ca. Hm OnCheckAntialias() s
lm gim hiu ng rng ca:
void CFormCommandView::OnCheckAntialias()
{
m_Antialias = !m_Antialias;
if(m_Antialias)
{
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glLineWidth(1.5);
}
else
{
glDisable(GL_LINE_SMOOTH);
glDisable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glLineWidth(1.0);
}
GetRenderView()->InvalidateRect(NULL,FALSE);
}

Hnh 2.2.2.3a:Cha kh rng ca


Hnh 2.2.2.3b: kh rng ca
2.2.2.4. Cc thao tc v i tng 3-D:
a gic l hnh to bi cc ng ni (cnh) gia mt tp hp cc vertex. Mt a
gic c t nht ba cnh. Nh vy, a gic n gin nht l tam gic.
OpenGL c th v a gic nh cc im, cc ng ngoi, hay i tng c.
OpenGL cn c th in y a gic vi mu c nh ngha. Thm vo , mt a

gic OpenGL c hai mt trc v sau c th v theo cch ring, v c th quay mt a


gic xem mt bn kia.
Hm glPogonMode() c dng v a gic:
Chng trnh cho php v hnh cu vi cc ch im (GL_POINT), khung li
(GL_LINE), a gic c (GL_FILL).
void CFormCommandView::OnRadioModel0()
{
glPolygonMode(GL_FRONT_AND_BACK,GL_POINT);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnRadioModel0()
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnRadioModel0()
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}

Hnh 2.2.2.4a: Hnh cu v bng khung li

Hnh 2.2.2.4b: Thao tc v hnh cu c

Hnh 2.2.2.4c: Hnh cu v bng im


2.3. Bng k chng trnh:
Bng k 2.3.1 : OpenGLView.h
// OpenGLView.h : interface of the COpenGLView class
//

#if
!defined(AFX_OPENGLVIEW_H__B5E77933_7225_11D5_9ABA_BAADD0C6
8D13__INCLUDED_)
#define
AFX_OPENGLVIEW_H__B5E77933_7225_11D5_9ABA_BAADD0C68D13__I
NCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class COpenGLDoc ;
class COpenGLView : public CView
{
protected: // create from serialization only
COpenGLView();
DECLARE_DYNCREATE(COpenGLView)
// Attributes
public:
COpenGLDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COpenGLView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
float m_zTranslation;
float m_yTranslation;
float m_xTranslation;
float m_zScaling;
float m_yScaling;
float m_xScaling;
float m_zRotation;

float m_yRotation;
float m_xRotation;
CPoint m_RightDownPos;
BOOL m_RightButtonDown;
CPoint m_LeftDownPos;
BOOL m_LeftButtonDown;
HGLRC m_hGLContext;
int m_GLPixelIndex;
HCURSOR m_CursorRotation;
float m_ClearColorGreen;
float m_ClearColorRed;
float m_ClearColorBlue;
void InitGeometry(void);
BOOL CreateViewGLContext(HDC hDC);
BOOL SetWindowPixelFormat(HDC hDC);
virtual ~COpenGLView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(COpenGLView)
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in OpenGLView.cpp
inline COpenGLDoc* COpenGLView::GetDocument()
{ return (COpenGLDoc*)m_pDocument; }

#endif
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the
previous line.
#endif //
!defined(AFX_OPENGLVIEW_H__B5E77933_7225_11D5_9ABA_BAADD0C6
8D13__INCLUDED_)
Bng k 2.3.2: OpenGLView.cpp
// OpenGLView.cpp : implementation of the COpenGLView class
#include "stdafx.h"
#include "OpenGL.h"
#include "OpenGLDoc.h"
#include "OpenGLView.h"
#include "gl\glu.h"
#include "gl\gl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COpenGLView
IMPLEMENT_DYNCREATE(COpenGLView, CView)
BEGIN_MESSAGE_MAP(COpenGLView, CView)
//{{AFX_MSG_MAP(COpenGLView)
ON_WM_PAINT()
ON_WM_MOUSEMOVE()
ON_WM_TIMER()
ON_WM_SIZE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_CREATE()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)

ON_COMMAND(ID_FILE_PRINT_PREVIEW,
CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COpenGLView construction/destruction
COpenGLView::COpenGLView()
{
// TODO: add construction code here
m_hGLContext = NULL;
m_GLPixelIndex = 0;
// Mouse
m_LeftButtonDown = FALSE;
m_RightButtonDown = FALSE;
//
m_CursorRotation = AfxGetApp()>LoadCursor(IDC_CURSOR_ROTATION);
// Colors
COpenGLApp *pApp = (COpenGLApp *)AfxGetApp();
m_ClearColorRed = GetRValue(pApp->m_OptionColorGlBack);
m_ClearColorGreen = GetGValue(pApp->m_OptionColorGlBack);
m_ClearColorBlue = GetBValue(pApp->m_OptionColorGlBack);
InitGeometry();
}
COpenGLView::~COpenGLView()
{
}
BOOL COpenGLView::PreCreateWindow(CREATESTRUCT& cs)
{
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// COpenGLView drawing
void COpenGLView::OnDraw(CDC* pDC)
{
COpenGLDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}

/////////////////////////////////////////////////////////////////////////////
// COpenGLView printing
BOOL COpenGLView::OnPreparePrinting(CPrintInfo* pInfo)
{
return DoPreparePrinting(pInfo);
}
void COpenGLView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo*
/*pInfo*/)
{
}
void COpenGLView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo*
/*pInfo*/)
{
}
/////////////////////////////////////////////////////////////////////////////
// COpenGLView diagnostics
#ifdef _DEBUG
void COpenGLView::AssertValid() const
{
CView::AssertValid();
}
void COpenGLView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
COpenGLDoc* COpenGLView::GetDocument() // non-debug version is
inline
{
ASSERT(m_pDocument>IsKindOf(RUNTIME_CLASS(COpenGLDoc)));
return (COpenGLDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// COpenGLView message handlers
void COpenGLView::OnPaint()

{
CPaintDC dc(this);
COpenGLDoc *pDoc = (COpenGLDoc*)GetDocument();
ASSERT_VALID(pDoc);
// Useful in multidoc templates
HWND hWnd = GetSafeHwnd();
HDC hDC = ::GetDC(hWnd);
wglMakeCurrent(hDC,m_hGLContext);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(m_ClearColorRed,m_ClearColorGreen,m_ClearColor
Blue,1.0f);
glPushMatrix();
// Position / translation / scale
glTranslated(m_xTranslation,m_yTranslation,m_zTranslation);
glRotatef(m_xRotation, 1.0, 0.0, 0.0);
glRotatef(m_yRotation, 0.0, 1.0, 0.0);
glScalef(m_xScaling,m_yScaling,m_zScaling);
// Start rendering...
pDoc->RenderScene();
glPopMatrix();
// Double buffer
SwapBuffers(dc.m_ps.hdc);
}
void COpenGLView::OnMouseMove(UINT nFlags, CPoint point)
{
if(m_LeftButtonDown)
{
m_yRotation -= (float)(m_LeftDownPos.x - point.x)/3.0f;
m_xRotation -= (float)(m_LeftDownPos.y - point.y)/3.0f;
m_LeftDownPos = point;
InvalidateRect(NULL,FALSE);
}
CView::OnMouseMove(nFlags, point);
}

void COpenGLView::OnTimer(UINT nIDEvent)


{
switch(nIDEvent)
{
case 0:
break;
// Rotation
case 1:
m_yRotation += 5.0f;
m_xRotation += 5.0f;
m_zRotation += 5.0f;
InvalidateRect(NULL,FALSE);
break;
default:
{}
}
}
void COpenGLView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// Set OpenGL perspective, viewport and mode
CSize size(cx,cy);
double aspect;
aspect = (cy == 0) ? (double)size.cx : (double)size.cx/(double)size.cy;
glViewport(0,0,size.cx,size.cy);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,aspect,1,15.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDrawBuffer(GL_BACK);
glEnable(GL_DEPTH_TEST);
// TODO: Add your message handler code here
}
void COpenGLView::OnLButtonDown(UINT nFlags, CPoint point)
{
m_LeftButtonDown = TRUE;
m_LeftDownPos = point;
CView::OnLButtonDown(nFlags, point);

}
void COpenGLView::OnLButtonUp(UINT nFlags, CPoint point)
{
m_LeftButtonDown = FALSE;
CView::OnLButtonUp(nFlags, point);
}
BOOL COpenGLView::SetWindowPixelFormat(HDC hDC)
{
PIXELFORMATDESCRIPTOR pixelDesc;
pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pixelDesc.nVersion = 1;
pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER |
PFD_STEREO_DONTCARE;
pixelDesc.iPixelType = PFD_TYPE_RGBA;
pixelDesc.cColorBits = 32;
pixelDesc.cRedBits = 8;
ixelDesc.cRedShift = 16;
pixelDesc.cGreenBits = 8;
ixelDesc.cGreenShift = 8;
pixelDesc.cBlueBits = 8;
ixelDesc.cBlueShift = 0;
pixelDesc.cAlphaBits = 0;
ixelDesc.cAlphaShift = 0;
pixelDesc.cAccumBits = 64;
pixelDesc.cAccumRedBits = 16;
ixelDesc.cAccumGreenBits = 16;
pixelDesc.cAccumBlueBits = 16;
ixelDesc.cAccumAlphaBits = 0;
pixelDesc.cDepthBits = 32;
ixelDesc.cStencilBits = 8;
pixelDesc.cAuxBuffers = 0;
ixelDesc.iLayerType = PFD_MAIN_PLANE;
pixelDesc.bReserved = 0;
ixelDesc.dwLayerMask = 0;
pixelDesc.dwVisibleMask = 0;
ixelDesc.dwDamageMask = 0;
m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);
if(m_GLPixelIndex == 0) // Choose default

{
m_GLPixelIndex = 1;
if(DescribePixelFormat(hDC,m_GLPixelIndex,
sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)
return FALSE;
}
if(!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc))
return FALSE;
return TRUE;
}
BOOL COpenGLView::CreateViewGLContext(HDC hDC)
{
m_hGLContext = wglCreateContext(hDC);
if(m_hGLContext==NULL)
return FALSE;
if(wglMakeCurrent(hDC,m_hGLContext)==FALSE)
return FALSE;
return TRUE;
}
void COpenGLView::InitGeometry()
{
m_xRotation = 0.0f;
m_yRotation = 0.0f;
m_zRotation = 0.0f;
m_xTranslation = 0.0f;
m_yTranslation = 0.0f;
m_zTranslation = -5.0f;
m_xScaling = 1.0f;
m_yScaling = 1.0f;
m_zScaling = 1.0f;
}
int COpenGLView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)

return -1;
HWND hWnd = GetSafeHwnd();
HDC hDC = ::GetDC(hWnd);
if(SetWindowPixelFormat(hDC)==FALSE)
return 0;
if(CreateViewGLContext(hDC)==FALSE)
return 0;
// Default mode
glPolygonMode(GL_FRONT,GL_LINE);
glPolygonMode(GL_BACK,GL_LINE);
glShadeModel(GL_FLAT);
glEnable(GL_NORMALIZE);

// Lights, material properties


GLfloat ambientProperties[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloat diffuseProperties[] = {0.8f, 0.8f, 0.8f, 1.0f};
GLfloat specularProperties[] = {1.0f, 1.0f, 1.0f, 1.0f};
glClearDepth( 1.0 );
glLightfv( GL_LIGHT0, GL_AMBIENT, ambientProperties);
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseProperties);
glLightfv(GL_LIGHT0,GL_SPECULAR,specularProperties);
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 1.0);
// Default : lighting
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
return 0;
}
void COpenGLView::OnDestroy()
{
if(wglGetCurrentContext() != NULL)
wglMakeCurrent(NULL,NULL);
if(m_hGLContext != NULL)
{
wglDeleteContext(m_hGLContext);

m_hGLContext = NULL;
}
CView::OnDestroy();
}
Bng k 2.3.3: FormCommandView.h
#if
!defined(AFX_FORMCOMMANDVIEW_H__B5E7793B_7225_11D5_9ABA_B
AADD0C68D13__INCLUDED_)
#define
AFX_FORMCOMMANDVIEW_H__B5E7793B_7225_11D5_9ABA_BAADD0
C68D13__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// FormCommandView.h : header file
// CFormCommandView form view
#ifndef __AFXEXT_H__
#include <afxext.h>
#endif
class COpenGLDoc;
class CFormCommandView : public CFormView
{
protected:
CFormCommandView();
DECLARE_DYNCREATE(CFormCommandView)
// Form Data
public:
//{{AFX_DATA(CFormCommandView)
enum { IDD = IDD_FORM_COMAMAND };
CStatic m_ControlColorLightAmbient;
CSliderCtrl m_SliderScaleZ;
CSliderCtrl m_SliderScaleY;
CSliderCtrl m_SliderScaleX;
CStatic m_ControlBackColor;
BOOL m_Antialias;
BOOL m_Lighting;
BOOL m_LinkScale;
BOOL m_Smooth;
BOOL m_VRotate;
//}}AFX_DATA

// Attributes
public:
// Operations
public:
BOOL UpdateScale();
COpenGLDoc* GetDocument();
CView *GetRenderView();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFormCommandView)
public:
virtual void OnInitialUpdate();
protected:
virtual void DoDataExchange(CDataExchange* pDX);
//}}AFX_VIRTUAL

// DDX/DDV support

// Implementation
protected:
virtual ~CFormCommandView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(CFormCommandView)
afx_msg void OnPaint();
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnCheckAntialias();
afx_msg void OnCheckLighting();
afx_msg void OnCheckLinkScale();
afx_msg void OnCheckSmooth();
afx_msg void OnCheckVrotation();
afx_msg void OnRadioModel0();
afx_msg void OnRadioModel1();
afx_msg void OnRadioModel2();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in RenderView.cpp
inline COpenGLDoc* CFormCommandView::GetDocument()

{ return (COpenGLDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the
previous line.
#endif //
!defined(AFX_FORMCOMMANDVIEW_H__B5E7793B_7225_11D5_9ABA_B
AADD0C68D13__INCLUDED_)
Bng k 2.3.4: FormCommandView.cpp
// FormCommandView.cpp : implementation file
//
#include "stdafx.h"
#include "OpenGL.h"
#include "FormCommandView.h"
#include "ChildFrm.h"
#include "MainFrm.h"
#include "OpenGLView.h"
#include "OpenGLDoc.h"
//#include "
#include "gl\glu.h"
#include "gl\gl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFormCommandView
IMPLEMENT_DYNCREATE(CFormCommandView, CFormView)
CFormCommandView::CFormCommandView()
: CFormView(CFormCommandView::IDD)
{
//{{AFX_DATA_INIT(CFormCommandView)
m_Antialias = FALSE;
m_Lighting = FALSE;
m_LinkScale = FALSE;
m_Smooth = FALSE;

m_VRotate = FALSE;
//}}AFX_DATA_INIT
}
CFormCommandView::~CFormCommandView()
{
}
void CFormCommandView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CFormCommandView)
DDX_Control(pDX, IDC_FRAME_COLOR_LIGHT_AMBIENT,
m_ControlColorLightAmbient);
DDX_Control(pDX, IDC_SLIDER_Z, m_SliderScaleZ);
DDX_Control(pDX, IDC_SLIDER_Y, m_SliderScaleY);
DDX_Control(pDX, IDC_SLIDER_X, m_SliderScaleX);
DDX_Control(pDX, IDC_FRAME_COLOR_BACK, m_ControlBackColor);
DDX_Check(pDX, IDC_CHECK_ANTIALIAS, m_Antialias);
DDX_Check(pDX, IDC_CHECK_LIGHTING, m_Lighting);
DDX_Check(pDX, IDC_CHECK_LINK_SCALE, m_LinkScale);
DDX_Check(pDX, IDC_CHECK_SMOOTH, m_Smooth);
DDX_Check(pDX, IDC_CHECK_VROTATION, m_VRotate);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CFormCommandView, CFormView)
//{{AFX_MSG_MAP(CFormCommandView)
ON_WM_PAINT()
ON_WM_HSCROLL()
ON_WM_LBUTTONUP()
ON_BN_CLICKED(IDC_CHECK_ANTIALIAS, OnCheckAntialias)
ON_BN_CLICKED(IDC_CHECK_LIGHTING, OnCheckLighting)
ON_BN_CLICKED(IDC_CHECK_LINK_SCALE, OnCheckLinkScale)
ON_BN_CLICKED(IDC_CHECK_SMOOTH, OnCheckSmooth)
ON_BN_CLICKED(IDC_CHECK_VROTATION, OnCheckVrotation)
ON_BN_CLICKED(IDC_RADIO_MODEL_0, OnRadioModel0)
ON_BN_CLICKED(IDC_RADIO_MODEL_1, OnRadioModel1)
ON_BN_CLICKED(IDC_RADIO_MODEL_2, OnRadioModel2)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFormCommandView diagnostics

#ifdef _DEBUG
void CFormCommandView::AssertValid() const
{
CFormView::AssertValid();
}
void CFormCommandView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CFormCommandView message handlers
void CFormCommandView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
// Slider
TRACE("Sliders : updating...\n");
m_SliderScaleX.SetRange(1,100,TRUE);
m_SliderScaleY.SetRange(1,100,TRUE);
m_SliderScaleZ.SetRange(1,100,TRUE);
m_SliderScaleX.SetPos(50);
m_SliderScaleY.SetPos(50);
m_SliderScaleZ.SetPos(50);
}
void CFormCommandView::OnPaint()
{
// Device context for painting
CPaintDC dc(this);
// Options are stored in Application
COpenGLApp *pApp = (COpenGLApp *)AfxGetApp();
CRect rect;
// Color back
m_ControlBackColor.GetWindowRect(&rect);
ScreenToClient(&rect);

CBrush BrushBack(pApp->m_OptionColorGlBack);
dc.FillRect(&rect,&BrushBack);
// Color light ambient
m_ControlColorLightAmbient.GetWindowRect(&rect);
ScreenToClient(&rect);
CBrush BrushLightAmbient(pApp->m_OptionColorGlLightAmbient);
dc.FillRect(&rect,&BrushLightAmbient); // TODO: Add your message handler
code here
// Do not call CFormView::OnPaint() for painting messages
}
void CFormCommandView::OnHScroll(UINT nSBCode, UINT nPos,
CScrollBar* pScrollBar)
{
// TODO: Add your message handler code here and/or call default
switch( nSBCode )
{
case TB_BOTTOM:
UpdateScale();
break;
case TB_ENDTRACK:
UpdateScale();
break;
case TB_LINEDOWN:
UpdateScale();
break;
case TB_LINEUP:
UpdateScale();
break;
case TB_PAGEDOWN:
UpdateScale();
break;
case TB_PAGEUP:
UpdateScale();
break;
case TB_THUMBPOSITION:
UpdateScale();
break;
case TB_THUMBTRACK:
UpdateScale();
break;
case TB_TOP:
UpdateScale();

break;
default:
{}
}
// Update scaling
GetRenderView()->InvalidateRect(NULL,FALSE);
CFormView::OnHScroll(nSBCode, nPos, pScrollBar);
}
void CFormCommandView::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CRect rect;
COpenGLApp *pApp = (COpenGLApp *)AfxGetApp();
// Option back color
m_ControlBackColor.GetWindowRect(&rect);
ScreenToClient(&rect);
if(rect.PtInRect(point))
{
CColorDialog dlg(pApp->m_OptionColorGlBack);
if(dlg.DoModal()==IDOK)
{
pApp->m_OptionColorGlBack = dlg.GetColor();
COpenGLView *pView = (COpenGLView *)GetRenderView();
pView->m_ClearColorRed = (float)GetRValue(pApp>m_OptionColorGlBack) / 255.0f;
pView->m_ClearColorGreen = (float)GetGValue(pApp>m_OptionColorGlBack) / 255.0f;
pView->m_ClearColorBlue = (float)GetBValue(pApp>m_OptionColorGlBack) / 255.0f;
this->InvalidateRect(&rect,FALSE);
pView->InvalidateRect(NULL,FALSE);
}
}
// Option ambient light color
m_ControlColorLightAmbient.GetWindowRect(&rect);
ScreenToClient(&rect);
if(rect.PtInRect(point))
{
CColorDialog dlg(pApp->m_OptionColorGlLightAmbient);
if(dlg.DoModal()==IDOK)

{
pApp->m_OptionColorGlLightAmbient = dlg.GetColor();
COpenGLView *pView = (COpenGLView *)GetRenderView();
// Refresh Light0
float r = (float)GetRValue(pApp->m_OptionColorGlLightAmbient) /
255.0f;
float g = (float)GetGValue(pApp->m_OptionColorGlLightAmbient) /
255.0f;
float b = (float)GetBValue(pApp->m_OptionColorGlLightAmbient) /
255.0f;
float ambientProperties[] = {r,g,b,1.0f};
glLightfv( GL_LIGHT0, GL_AMBIENT, ambientProperties);
// Refresh views
this->InvalidateRect(&rect,FALSE);
pView->InvalidateRect(NULL,FALSE);
}
}
CFormView::OnLButtonUp(nFlags, point);
}
CView *CFormCommandView::GetRenderView()
{
COpenGLApp *pApp = (COpenGLApp *)AfxGetApp();
CMainFrame *pMainFrame = (CMainFrame *)pApp->m_pMainWnd;
CChildFrame *pFrame = (CChildFrame *)pMainFrame->GetActiveFrame();
CView *pView = (CView *)pFrame->m_wndSplitter.GetPane(0,1);
return pView;
}
COpenGLDoc* CFormCommandView::GetDocument()
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(COpenGLDoc)));
return (COpenGLDoc*)m_pDocument;
}
BOOL CFormCommandView::UpdateScale()
{
COpenGLView *pView = (COpenGLView *)GetRenderView();
pView->m_xScaling = (float)m_SliderScaleX.GetPos()/50.0f;

pView->m_yScaling = (float)m_SliderScaleY.GetPos()/50.0f; // TODO : link


pView->m_zScaling = (float)m_SliderScaleZ.GetPos()/50.0f;
if(m_LinkScale)
{
m_SliderScaleY.SetPos(m_SliderScaleX.GetPos());
m_SliderScaleZ.SetPos(m_SliderScaleX.GetPos());
pView->m_yScaling = pView->m_zScaling = pView->m_xScaling;
}
return TRUE;
}
void CFormCommandView::OnCheckAntialias()
{
// TODO: Add your control notification handler code here
m_Antialias = !m_Antialias;
if(m_Antialias)
{
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glLineWidth(1.5);
}
else
{
glDisable(GL_LINE_SMOOTH);
glDisable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glLineWidth(1.0);
}
GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnCheckLighting()
{
// TODO: Add your control notification handler code here
m_Lighting = !m_Lighting;
if(m_Lighting)

glEnable(GL_LIGHTING);
else
glDisable(GL_LIGHTING);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnCheckLinkScale()
{
m_LinkScale = !m_LinkScale;
if(m_LinkScale)
{
COpenGLView *pView = (COpenGLView *)GetRenderView();
m_SliderScaleY.SetPos(m_SliderScaleX.GetPos());
m_SliderScaleZ.SetPos(m_SliderScaleX.GetPos());
pView->m_yScaling = pView->m_zScaling = pView->m_xScaling;
}
m_SliderScaleY.EnableWindow(!m_LinkScale);
m_SliderScaleZ.EnableWindow(!m_LinkScale);
GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnCheckSmooth()
{
m_Smooth = !m_Smooth;
if(m_Smooth)
glShadeModel(GL_SMOOTH);
else
glShadeModel(GL_FLAT);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnCheckVrotation()
{
// TODO: Add your control notification handler code here
m_VRotate = !m_VRotate;
COpenGLView *pView = (COpenGLView *)GetRenderView();
if(m_VRotate)
pView->SetTimer(1,10,NULL);
else
pView->KillTimer(1);

}
void CFormCommandView::OnRadioModel0()
{
// TODO: Add your control notification handler code here
glPolygonMode(GL_FRONT_AND_BACK,GL_POINT);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnRadioModel1()
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}
void CFormCommandView::OnRadioModel2()
{
// TODO: Add your control notification handler code here
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
this->GetRenderView()->InvalidateRect(NULL,FALSE);
}