OpenGL ES紋理處理
使用OpenGL ES的紋理可以將圖片貼到3D模型上,從而產生逼真的3D情境。紋理是以圖片檔案形式存在的,圖片被歸一化為(0.0, 0.0)到(1.0, 1.0)的矩形地區,通常一個3D物體具有一個紋理檔案即可,每處三角片所使用的紋理可以通過uv座標來指定。通過三角片每個頂點在歸一化後圖片中的座標,可以從紋理圖片中取出相應的三角形地區,OpenGL ES將該地區進行放縮旋轉後繪製到三角片上。具體處理代碼如下所示:
obj = new MgnavObject(true, true, false); // 第一個參數表示使用紋理座標,第三個參數表示不使用顏色
下面代碼匯入紋理:
// 裝入紋理資料
Bitmap bmp = null;
bmp = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/building/L6HF2703.JPG");
String textureId = "cube";
if (bmp != null) {
Shared.textureManager().addTextureId(bmp, textureId, false);
bmp.recycle();
TextureVo tvo = new TextureVo(textureId);
obj.textures().add(tvo);
}
scene.lightingEnabled(false);
從上面的代碼中可以看出,是讀取SD卡中的一個檔案作為紋理圖片。
下面為立方體正面賦給紋理座標:
// 1. front
normalX = 0f; normalY = 0f; normalZ = 1.0f;
// 1.1. 加入前面右上部三角片
textureU = 0.0f; textureV = 0.0f;
short f1p1Idx = vertices().addVertex(-width, height, deepth,
textureU, textureV,
normalX, normalY, normalZ,
colorR, colorG, colorB, colorA);
textureU = 1.0f; textureV = 1.0f;
short f1p3Idx = vertices().addVertex(width, -height, deepth,
textureU, textureV,
normalX, normalY, normalZ,
colorR, colorG, colorB, colorA);
textureU = 1.0f; textureV = 0.0f;
short f1p2Idx = vertices().addVertex(width, height, deepth,
textureU, textureV,
normalX, normalY, normalZ,
colorR, colorG, colorB, colorA);
faces().add(f1p1Idx, f1p3Idx, f1p2Idx);
// 1.2. 加入前面的左下部三角片
textureU = 0.0f; textureV = 1.0f;
short f1p4Idx = vertices().addVertex(-width, -height, deepth,
textureU, textureV,
normalX, normalY, normalZ,
colorR, colorG, colorB, colorA);
faces().add(f1p1Idx, f1p4Idx, f1p3Idx);
對於上面的紋理座標比較難以理解,下面通過圖形來加以說明:
圖1
上面是立方體正面頂點編號,上面代碼加入了1、3、2及1、4、3這兩個三角片。
本來的紋理座標如所示:
圖2
其座標原點在左下角,與OpenGL ES幾何元素的座標是上下顛倒的。在從其他3D軟體匯出時,這些軟體將自動將圖片進行上下顛倒。但是我們這裡直接用圖片貼圖時,我們需要人工將紋理圖片顛倒一下,在這裡將紋理座標進行上下顛倒:
圖3
這時與頂點所對就的紋理座標就是代碼中所設定的值。
註:由於不能將圖片貼上,請看本博文新浪部落格上的完整版:http://blog.sina.com.cn/s/blog_5d8486b40100q2vc.html