[500行程式碼學懂OpenGL]之一畫點
專案來自tinyrenderer ,作者嘗試用500行程式碼來寫一個tiny render,讓我們來明白OpenGL是怎樣工作的,同樣,這個系列可以理解為我的讀書筆記或者心得或翻譯。
從畫點開始
TGAImage
生成影象我們使用TGAImage,這個使用起來很簡單:
#include
“tgaimage。h”
const
TGAColor
white
=
TGAColor
(
255
,
255
,
255
,
255
);
const
TGAColor
red
=
TGAColor
(
255
,
0
,
0
,
255
);
int
main
(
int
argc
,
char
**
argv
){
TGAImage
image
(
100
,
100
,
TGAImage
::
RGB
);
image
。
set
(
52
,
41
,
red
);
image
。
flip_vertically
();
// i want to have the origin at the left bottom corner of the image
image
。
write_tga_file
(
“output。tga”
);
return
0
;
}
生成的影象(注意中間哪一個小小的紅色點):
compile:
g++ main。cpp tgaimage。cpp -o main
wavefront obj
然後我們來學習一種3d格式檔案,wavefront obj file:
# List of geometric vertices, with (x, y, z [,w]) coordinates, w is optional and defaults to 1。0。
v 0。123 0。234 0。345 1。0
v 。。。
。。。
# List of texture coordinates, in (u, [v ,w]) coordinates, these will vary between 0 and 1, v and w are optional and default to 0。
vt 0。500 1 [0]
vt 。。。
。。。
# List of vertex normals in (x,y,z) form; normals might not be unit vectors。
vn 0。707 0。000 0。707
vn 。。。
。。。
# Parameter space vertices in ( u [,v] [,w] ) form; free form geometry statement ( see below )
vp 0。310000 3。210000 2。100000
vp 。。。
。。。
# Polygonal face element (see below)
f 1 2 3
f 3/1 4/2 5/3
f 6/4/1 3/5/3 7/6/5
f 7//1 8//2 9//3
f 。。。
。。。
# Line element (see below)
l 5 8 1 2 4 9
我們現在只需要知道了解頂點是v,現在我們想把一個檔案中的3d模型的頂點 v (x, y, z) 給畫出來,(因為我們已經知道怎麼在圖上相應的位置放畫素)這個檔案所有的 x, y, z ∈ [-1, 1],所以我們
需要把它們對映到合適範圍。
然後注意我們畫的點
image。set(52, 41, red);
, 這裡的 52 和 41 是 int,對映之後需要轉成int,因為我們總是畫在一個一個畫素點上。
寫一個簡單的parser讀入檔案建立模型,畫之。
核心部分長這樣:
for
(
int
i
=
0
;
i
!=
model
->
nverts
();
i
++
)
{
Vec3f
v
=
model
->
vert
(
i
);
Vec2i
p
=
world2screen
(
v
);
image
。
set
(
p
。
x
,
p
。
y
,
white
);
}
compile:
g++ main。cpp tgaimage。cpp model。cpp -o main